Is it possible for consecutive json and jsonp requests to fail on Crossrider?

I am currently utilizing crossrider to develop a plugin that works across various browsers.

Within my implementation, I have two consecutive AJAX requests (one JSON and one JSONP):

  1. The first request involves a JSON call for "login" which sets a browser cookie.
  2. The second request is a JSONP call for "save" which sends data to the server using the previously set cookie.


Here is a simplified version of the code:

$.ajax({ 
    url : "https://app.testafy.com/api/v0/user/login", 
    type : 'GET', 
    cache : false, 
    dataType : 'json', 
    data : {login_name: "abashir", password: "P@ssw0rd"} 
}).done(function(response) { 
    alert("Login Successful"); 
    $.ajax({ 
        url : 'https://app.testafy.com/api/v0/test/save', 
        type : 'GET', 
        cache : false, 
        dataType : 'jsonp', 
        data : {"pbehave":"For+the+url+http%3A%2F%2Fstackoverflow.com%2F%0D%0A","title":"test","description":" "} 
    }).done(function(response) { 
        alert("Saving Successful:\n\n" + JSON.stringify(response, undefined)); 
    }).fail(function(jqXHR, textStatus, errorThrown) { 
        alert("Saving Failure:\n\n" 
            + JSON.stringify(jqXHR, undefined) + "\n\n" 
            + JSON.stringify(textStatus, undefined) + "\n\n" 
            + JSON.stringify(errorThrown, undefined)); 
}); 
}).fail(function(jqXHR, textStatus, errorThrown) { 
    alert("Login Failure:\n\n" 
        + JSON.stringify(jqXHR, undefined) + "\n\n" 
        + JSON.stringify(textStatus, undefined) + "\n\n" 
        + JSON.stringify(errorThrown, undefined)); 
}); 

This code functions smoothly across Internet Explorer, Firefox, and Chrome when placed in an HTML file (auto-login followed by auto-save).

However, when integrated into a crossrider extension.json file (using appAPI.ready), it exhibits varied behavior across different browsers.

For Chrome:

  • Login process completes successfully.
  • Saving operation encounters issues with the following output:

{"readyState":4,"status":200,"statusText":"success"}
"parseerror"
{}


For Firefox:

  • Login process succeeds.
  • A popup prompts for credentials (even though cookies should have been set during login !!)
  • Upon entering credentials (abashir & P@ssw0rd), saving fails as well.

{"readyState":4,"status":200,"statusText":"success"}
"parseerror"
{}


For IE9:

  • Login attempt fails with the following error:

{"readyState":0, "setRequestHeader":{},....,"statusText":"No Transport"}
"error"
"No Transport"


In reviewing through Fiddler, I observed that despite the ajax fail function being triggered in Chrome, the server response is actually correct. Here's the request/response pair captured from Fiddler:


REQUEST:

GET https://app.testafy.com/api/v0/test/save?callback=jQuery17107044411341194063_1364461851960&pbehave=For%2Bthe%2Burl%2Bhttp%253A%252F%252Fstackoverflow.com%252F%250D%250A&title=test&description=+&_=1364461865618 HTTP/1.1 
Host: app.testafy.com 
Connection: keep-alive 
Accept: */* 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22 
Referer: http://stackoverflow.com/ 
Accept-Encoding: gzip,deflate,sdch 
Accept-Language: en-US,en;q=0.8 
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 
Cookie: __utma=124963983.2014233417.1360749029.1362583015.1362996135.12; __utmc=124963983; __utmz=124963983.1362322761.9.3.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/; GSG_SESSIONID=ee03a02cdb6f3c0e3d812795be63c788


RESPONSE:

HTTP/1.1 200 nginx 
Access-Control-Allow-Origin: * 
Content-Type: application/json; charset=utf-8 
Date: Thu, 28 Mar 2013 09:03:48 GMT 
P3P: CP="ALL ADM DEV PSAi COM OUR OTRo STP IND ONL" 
Set-Cookie: GSG_SESSIONID=ee03a02cdb6f3c0e3d812795be63c788; domain=app.testafy.com; path=/; secure; HttpOnly 
Content-Length: 273 
Connection: keep-alive 

jQuery17107044411341194063_1364461851960({"test_id":"558","message":"Phrase check has found the following error(s), but your test was still saved:\nThere's no For rule for '+the+url+http%3A%2F%2Fstackoverflow.com%2F%0D%0A'\n\nSaved new test as id#558","project_id":"151"});

It is evident that the callback function generated contains the correct JSON object, yet the execution falls back to the fail function! Consequently, accessing and extracting data from this response becomes impossible.

How can I ensure that these two consecutive requests work consistently across all three browsers (IE, FF, Chrome) when using crossrider?

Answer №1

It seems like the issue is related to the cross-domain restrictions that can occur when using $.ajax within the Extension scope.

To circumvent this problem, you can utilize our appAPI.request.post method as shown in the example code below. This code has been successfully tested in Chrome, with both login and save operations working as intended.

If you require further assistance, please feel free to reach out.

appAPI.ready(function ($) {
    appAPI.request.post({
        url: "https://app.testafy.com/api/v0/user/login",
        onSuccess: function (response) {
            alert("Login Success");
            appAPI.request.post({
                url: 'https://app.testafy.com/api/v0/test/save',
                onSuccess: function (response) {
                    alert("Saving Success:\n\n" + appAPI.JSON.stringify(response));
                },
                onFailure: function (httpCode) {
                    alert("Saving Failure:\n\n" + httpCode);
                },
                postData: {
                    "pbehave": "For+the+url+http%3A%2F%2Fstackoverflow.com%2F%0D%0A",
                    "title": "test",
                    "description": " "
                }
            });
        },
        onFailure: function (httpCode) {
            alert("Login Failure:\n\n" + httpCode);
        },
        postData: {
            login_name: "abashir",
            password: "P@ssw0rd"
        }
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing difficulties when trying to input text into a React text field

For a university assignment, I am using the create-react-app to build a website. I am facing issues with the input text field as I cannot type into it when clicked. There are no error messages indicating what could be wrong. The objective is for users to ...

Tips for using JavaScript to set images from Flickr API as img src

I've been attempting to populate a table with images fetched from flickr. The array I'm using consists of urls like: ["https://www.flickr.com/photos/113081696@N07/24695273486", "https://www.flickr.com/photos/113081696@N07/24565358002", "https:// ...

Iterate over a collection of JSON objects and dynamically populate a table with statistical data

In JavaScript, I am trying to dynamically generate a table with statistical data from an API that contains an array of JSON objects. The JSON data has a property called "score" which is interpreted as follows: score: 5 (excellent); score: 4 (very good); ...

I want to search through an array of tuples to find a specific value in the first index, and if there is a match, I need to return the value in the second index of the matching tuple

I am dealing with an array of tuples: var tuparray: [string, number][]; tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]]; const addressmatch = tuparray.includes(manualAddress); In my function, I aim to verify if the t ...

What is the best way to send the index variable to an HTML element in Angular?

Is there a way to pass the index variable to construct HTML in the append() function? .directive('grid', ['$compile', function(compile) { return { restrict: "E", scope: { elements: '=' ...

Do we really need to use the eval function in this situation?

Just wondering, is it reasonable to exclude the eval() function from this code? Specifically how <script> ... ... function addGeoJson (geoJsonPath, iconPath = "leaflet-2/images/marker-icon.png", iconSize = [30,50], popUpContent, ...

Is there a way to use JavaScript to choose options within a <select> element without deselecting options that are disabled?

Here's the code snippet I am working with at the moment: <select id="idsite" name="sites-list" size="10" multiple style="width:100px;"> <option value="1" disabled>SITE</option> ...

Namespacing is not applied to dynamic modules in Vuex

I've been tackling a modular vue application that enrolls the modules during compile time. Take a look at the code snippet below - app.js import store from './vue-components/store'; var components = { erp_inventory: true, erp_purc ...

Unable to attach eventName and callback to addEventListener due to the error message stating 'No overload matches this call'

I am attempting to attach an event listener to the input element stored within a class method. This method takes a props object containing eventName and callback. public setTextFieldInputListener({ eventName, callback }: TextFieldListenerProps): void { ...

Cease the execution of processes once a Promise has been rejected

My current code is functioning correctly, but I am facing an issue where if an error occurs, I want it to halt all other promises in the chain. Specifically, when chi.getCommand(val1, val2) returns a reject and triggers the exception catch block, I need to ...

Steps for registering a function on $rootScope when angularjs is ready

In order to make a method accessible throughout angularjs, I am looking to register it with 2 arguments (the resource id and the delete callback) using the resource provider to handle the deletion process. To properly register this method, I need angularj ...

Implementing paginated query results using PHP and AJAX

I am working on a filter form in my website's HTML, which sends data to PHP via AJAX to execute a query. I want to implement pagination for the results retrieved from this query. What is the most effective way to achieve this? You can visit the site ...

unable to load variables in google extension due to technical difficulties

I'm encountering an error even though I've already loaded the DOM. I have no idea how to fix this issue and I've been sitting here for hours trying to troubleshoot. The error message I'm getting is: btncheck.js:10 Uncaught TypeError: C ...

Pass data between JavaScript and PHP using the Phaser framework

I am trying to pass a JavaScript variable to PHP and then store it in a database. Despite searching for solutions on Google, I have not been successful. Most suggestions involve using AJAX, but the code doesn't seem to work when I try it. I attempted ...

Utilize Express.js to load a random HTML page

Hey there, it's Nimit! I could really use some assistance with my code. I'm trying to figure out if it's possible to load different HTML pages on the same URL like www.xyz.com/home/random. Can more than one HTML page be randomly loaded? I ...

What could be causing the 403 Error when using Blogger API with AngularJS?

I'm relatively new to working with 3rd Party APIs and I'm currently exploring how to integrate Blogger's API into my AngularJS website to create a blog feed feature. After setting everything up, I've made a request and received a 200 s ...

Expand and collapse dynamically while scrolling

// Closing Button for Main Navigation $('button#collapse-button').click(function () { $('nav#main-nav').toggleClass('closed'); }); $(window).on('scroll', function () { if ($(wind ...

The issue of not displaying the top of the page when utilizing NavigationHandler.handleNavigation was encountered

Following the advice given in this Stack Overflow thread (ExternalContext.dispatch() not working), I am using NavigationHandler.handleNavigation due to an ajax request. Although it successfully navigates, the next page appears in the middle of the screen ...

Creating a rhombus or parallelogram on a canvas can be easily achieved by following these simple

I'm new to working with the canvas element and I want to create some shapes on it. Can someone provide me with guidance on how to draw a Rhombus or Parallelogram on a canvas? Something similar to what is shown in this image: https://i.stack.imgur.c ...

Convert a large MySQL table into JSON format

I am facing a challenge with converting a large mysql table containing 2.8 million records to JSON format. The script I wrote for the conversion stops with a memory warning. As an alternative, I attempted to create smaller files - such as file1 containing ...