How do I send through ajax each element from the following array? - javascript

Send through ajax each element from the following array. Note: Each request must
be made once the previous has finished.
[‘This’, ‘is’, ‘a’, ‘fake, ‘array’]
I am a little confused by this question because I thought Ajax is asynchronous, meaning the script keeps sending requests to the server without waiting for the reply.

***Was downvoted so going to clarify something: It specifically states in the problem statement that the REQUEST must be made synchronously. I do realize that there are better ways of doing this via def/promises asynchronously so order remains for the result but that isn't the request.
Ajax has a async parameter you can set to false which will block until call completion.
Per documentation:
async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done().
http://api.jquery.com/jquery.ajax/
Example:
$.each(["This", "is", "a", "fake", "array"], function( index, value ) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
data : { json: JSON.stringify( value ) },
async: false,
success: function(data) { alert(data);}
});
});
Working fiddler example: https://jsfiddle.net/zm9bb4xk/

I was talking about JQuery Ajax.
So, first, based on documentation, Ajax has many events that run at certain times, for example:
beforeSend (Local Event)
This event, which is triggered before an Ajax request is started,
allows you to modify the XMLHttpRequest object (setting additional
headers, if need be.)
error (Local Event)
This event is only called if an error occurred with the request (you
can never have both an error and a success callback with a request).
complete (Local Event)
This event is called regardless of if the request was successful, or
not. You will always receive a complete callback, even for synchronous
requests.
success (Local Event)
This event is only called if the request was successful (no errors
from the server, no errors with the data).
More in documentation.
Second, following your example (you have to complete this with your own data and this code is not tested, maybe it has some small sintax errors), an approximation is:
// Variables
var myArray = ["This", "is", "a", "fake", "array"];
var globalIndex = 0;
// Function for Ajax Calls
function myFunction(){
$.ajax({
url: 'myURL', // Your own controller/url
type: "GET", // Or POST
dataType: "json", // Or other datatype
data: {
arrayContent: myArray[globalIndex] // arrayContent = your controller param name
},
/**
* A function to be called if the request succeeds.
*/
success: function(data) {
alert('Load was performed. Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information! ');
alert(data); // Do what you want with your data, this is an example
globalIndex = globalIndex +1;
// Recursive/next call if current call is finished OK and there are elements
if(globalIndex < myArray.length){
myFunction();
}
},
/**
* A function to be called if the request fails.
*/
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... Look at the console (F12 or Ctrl+Shift+I, Console tab) for more information!');
alert('<p>status code: '+jqXHR.status+'</p><p>errorThrown: ' + errorThrown + '</p><p>jqXHR.responseText:</p><div>'+jqXHR.responseText + '</div>');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
// We don't do a recursive/next call because current call has failed
},
});
}
// First call to myFunction
myFunction();

Related

How should I fail gracefully when ERR_BLOCKED_BY_CLIENT? [duplicate]

I'm making an ajax jsonp request, but the failure error handling wont work. If the request is 404 or 500 it won't handle the error.
I've been looking around to find an answer to this, but can't find anything. There seems to be a solution with http://code.google.com/p/jquery-jsonp/, but I can't find any examples on how to use it.
function authenticate(user, pass) {
$.ajax ({
type: "POST",
url: "url",
dataType: 'jsonp',
async: false,
//json object to sent to the authentication url
data: {"u": userid, "p": pass},
success: function (data) {
//successful authentication here
console.log(data);
},
error: function(XHR, textStatus, errorThrown) {
alert("error: " + textStatus);
alert("error: " + errorThrown);
}
})
}
If you check jQuery.ajax() documentation, you can find:
error
A function to be called if the request fails (...) Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
Because of that, you're forced to find workaround. You can specify timeout to trigger an error callback. It means that within specified time frame the request should be successfully completed. Otherwise, assume it has failed:
$.ajax({
...
timeout: 5000, // a lot of time for the request to be successfully completed
...
error: function(x, t, m) {
if(t==="timeout") {
// something went wrong (handle it)
}
}
});
Other issues in your code...
While JSONP (look here and here) can be used to overcome origin policy restriction, you can't POST using JSONP (see CORS instead) because it just doesn't work that way - it creates a element to fetch data, which has to be done via GET request. JSONP solution doesn't use XmlHttpRequest object, so it is not an AJAX request in the standard way of understanding, but the content is still accessed dynamically - no difference for the end user.
$.ajax({
url: url,
type: "GET"
dataType: "jsonp",
...
Second, you provide data incorrectly. You're pushing javascript object (created using object literals) onto the wire instead of its serialized JSON representation. Create JSON string (not manually, use e.g. JSON.stringify converter):
$.ajax({
...
data: JSON.stringify({u: userid, p: pass}),
...
Last issue, you've set async to false, while documentation says:
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation.
Two ways to handle error,
There is no error handling for cross domain JSONP requests. Use jsonp plug-in available on Github https://github.com/jaubourg/jquery-jsonp that provides support for error handling.
jQuery ajax Timeout - Timeout after a reasonable amount of time to fire the error callback because it might have failed silently. You may not know what the actual error (or error status) was but at least you get to handle the error
I've been struggling like you for a while trying to handle errors on ajax jsonp DataType requests, however I want to share you my code, hope it helps. A basic thing is to include a timeout on the ajax request, otherwise it'll never enter the error: function
$.ajax({
url: "google.com/api/doesnotexists",
dataType: "jsonp",
timeout: 5000,
success: function (parsed_json) {
console.log(parsed_json);
},
error: function (parsedjson, textStatus, errorThrown) {
console.log("parsedJson: " + JSON.stringify(parsedjson));
$('body').append(
"parsedJson status: " + parsedjson.status + '</br>' +
"errorStatus: " + textStatus + '</br>' +
"errorThrown: " + errorThrown);
}
});
jsfiddle - Handle Errors with jquery ajax call and JSONP dataType - Error 404
I'm building a fragile JS project that uses jquery-jsonp, and came up with a dual-jsonp/ajax approach that handles errors no matter which method ends up being used.
function authenticate(user, pass) {
var ajax = ($.jsonp || $.ajax)({
'url': /* your auth url */,
'data': { /* user, pass, ... */ },
'contentType': "application/javascript",
'dataType': 'jsonp',
'callbackParameter': 'callback' // $.jsonp only; $.ajax uses 'jsonpCallback'
});
ajax.done(function (data) {
// your success events
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
// $.jsonp calls this func as function (jqXHR, textStatus)
// and $.ajax calls this func with the given signature
console.error('AJAX / JSONP ' + textStatus + ': ' +
(errorThrown || jqXHR.url));
});
}
Since both jquery-jsonp and $.ajax support the jQuery Deferred specification, we can merge the two error handlers together, handling 400 and 500-series errors, as well as lookup timeouts.
Old question but I had the same problem. Here is a solution that worked for me.
If you own the domain you shoot your request at, you can set a variable in the response and check for it on the client side.
Server Side:
SERVER_RESPONSE=true; Callback(parameter1, parameter2);
Client Side:
if(typeof SERVER_RESPONSE === 'undefined'){
console.log('No Response, maybe server is down');
}
else{
console.log('Got a server response');
}

Ajax request is never entering `success:function(resp){ ...}`

My ajax request is never entering success:function(resp){ ...}
I'm getting a response status of 200 and the Json response obtained is not null.
My ajax function:
$.ajax({
url: '/url/',
type: 'GET',
data: {
pass_value: 0,
req_time_last_ack_update: 0,
},
dataType: "json",
success : function (resp) {
// Compiler is never entering here [I checked with Mozilla debugger]
},
error: function(){
....
}
});
Can anyone please help me find the reason for this failure?
(Question edited for clarification)
If you are trying to step into this directly after the call it will not work.
The Ajax request you are sending happens Asynchronously.
Only as soon as a response is received from the server (this could be several seconds later) you will see a breakpoint being hit (if you set one) inside the success method.

Explain jQuery's JSONP and the _ parameter [duplicate]

When I look at the query string from a jsonp request (client code below), there are 2 objects, a "callback" string that you need to use in the response (so the client codes directs to the success handler) and one with a key of _... what is this underscore for? I can't find any reference to this in any documentation, it appears to be a number of some kind.
I though that it might be used to direct to the error handler (either on its on, in combination with the callback, or replacing the number after the underscore in the callback string), but it doesn't appear to be.
url = 'http://localhost:11767/Handlers/MyHandler.ashx';
...
$.ajax({
url: url,
dataType: "jsonp",
error: function (jqXHR, textStatus, errorThrown) {
//...
},
success : function(d) {
//...
}
});
or
$.getJSON(url + "?callback=?", function(d) {
}).success(function(d) {
//...
}).error(function(jqXHR, textStatus, errorThrown) {
//...
}).complete(function(d) {
//...
});
Side note in case this helps anyone reading this: as this is a jsonp request, error will only be hit if the exception occurs client side, e.g. there is a timeout or a problem with the formatting of response (i.e. not using the callback), to overcome this, I always log and swallow the exceptions in the handlers, but give a standard response object (which all response are made up of) that has a state property of exception and a message property.
The number you are referring is the date time stamp of the request. Grab the number and use a your browser's JavaScript console and type: alert(new Date(/*insert number here*/))
You'll get an alert with a date/time.
EDIT:
Here's a snippet from jQuery.ajax doc regarding an ajax request:
cache
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the browser.
Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]",
to the URL.

What/when does a call to the jQuery AJAX method return?

A little background:
I am trying to implement and AJAX powered SlickGrid. There isn't much documentation so I used this example as a base.
In this example there is the following code that hits the desired web service to get the data:
req = $.jsonp({
url: url,
callbackParameter: "callback",
cache: true, // Digg doesn't accept the autogenerated cachebuster param
success: onSuccess,
error: function(){
onError(fromPage, toPage)
}
});
req.fromPage = fromPage;
req.toPage = toPage;
I'm not exactly sure what jsonp does but from what i've read it appears to be very similar to the ajax method in jQuery except it returns json and allows cross domain requests. The webservice that I happen to be calling only returns XML so I changed this chunk of code to:
req = $.ajax({
url: "/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: xmlData,
complete: onSuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert("error: " + xhr.statusText);
alert(thrownError);
},
contentType: "text/xml; charset=\"utf-8\""
});
req.fromPage = fromPage;
req.toPage = toPage;
My issue is that my page errors out at req.fromPage = fromPage; because req is null.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method? Is req just not set because my ajax call hasn't finished by the time that code is executed? How can I get around either of these issues?
If I comment out the last two lines and hard-code those values elsewhere everything runs fine.
Am I wrong to think that I can just replace my jsonp call with a call to the ajax method?
No, that should work just fine.
Is req just not set because my ajax call hasn't finished by the time that code is executed?
Yes, that is correct.
The ajax methods starts the request and returns immediately. If you want to do something after the response has arrived you should do that in the success event handler.
You might actually want to use the success event instead of the complete event, as the complete event happens even if there is an error.
You could specify async: false, in your settings to make the ajax call wait for the response, but that means that the browser freezes while it's waiting.
As Guffa stated, $.ajax() works asynchronically. Thus, you have to specify a callback that will be called when the request has returned a response, rather than to just use whatever $.ajax() returns.
There are a couple of different callback methods you can specify:
complete - runs when you recieve a response, regardless of its status.
success - runs when you recieve a response with a successful status code (usually 200).
error - runs when you recieve a response with an error code (for example 404 or 500).
To do something with the response body after a successful request, you should do something like
$.ajax({
...
success: function(body) {
alert('This is the method body:' + body);
}
});
Read up in the documentation on the different methods to see what more parameters you can use.

Jquery success function not firing using JSONP

Been doing some playing call my service which is on a different domain using jQuery. The call to the service is successfully made (my debug point gets tripped), and the correct response is returned (I sniff the traffic).
My problem is mainly that the success and failure callbacks don't get fired. I have read some other posts on SO that indicate the error event is not fired when using JSONP. Is that the case with the success event (perhaps because it is assumed that I am providing my own callback function), as well, or is there a way to fire my success callback. Thanks in advance.
$.ajax({
type: "GET",
url: urlOnDiffDomain,
async: false,
cache: false,
dataType: 'jsonp',
data: {},
success: function(data, textStatus) {
alert('success...');
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed....');
}
});
Alright. In case anyone needs to know in the future...In hindsight, the solution probably should have been more obvious than it was, but you need to have the web-response write directly to the response stream. Simply returning a string of JSON doesn't do it, you need to someone construct it and stream it back. The code in my original post will work fine if you do indeed do that.
Example of service code:
public void DoWork()
{
//it will work without this, but just to be safe
HttpContext.Current.Response.ContentType = "application/json";
string qs = HttpContext.Current.Request.QueryString["callback"];
HttpContext.Current.Response.Write(qs + "( [{ \"x\": 10, \"y\": 15}] )");
}
Just for the sake of being explicit, this is the client-side code.
function localDemo(){
$.getJSON("http://someOtherDomain.com/Service1.svc/DoWork?callback=?",
function(data){
$.each(data, function(i,item){
alert(item.x);
});
});
}
If there is a better way to do this, I am all ears. For everyone else, I know there is some concept of native support in WCF 4.0 for JSONP. Also, you may want to do a little checking for security purposes - though I have not investigated much.
The success callback method is called when the server responds. The $.ajax method sets up a function that handles the response by calling the success callback method.
The most likely reason that the success method is not called, is that the response from the server is not correct. The $.ajax method sends a value in the callback query string that the server should use as function name in the JSONP response. If the server is using a different name, the function that the $.ajax method has set up is never called.
If the server can not use the value in the callback query string to set the function name in the response, you can specify what function name the $.ajax method should expect from the server. Add the property jsonpCallback to the option object, and set the value to the name of the function that the server uses in the response.
If for example the $.ajax method is sending a request to the server using the URL http://service.mydomain.com/getdata?callback=jsonp12345, the server should respond with something looking like:
jsonp12345({...});
If the server ignores the callback query string, and instead responds with something like:
mycallback({...});
Then you will have to override the function name by adding a property to the options object:
$.ajax({
url: urlOnDiffDomain,
dataType: 'jsonp',
data: {},
success: function(data, textStatus) {
alert('success...');
},
jsonpCallback: 'mycallback'
});
Try
$.getJSON(urlOnDiffDomain, function(data, textStatus){
alert('success...');
});
Works for me, usally. You need to add &callback=? to urlOnDiffDomain, where jQuery automatically replaces the callback used in JSONP.
The error callback is not triggered, but you can use the global $.ajaxError, like this
$('.somenode').ajaxError(function(e, xhr, settings, exception) {
alert('failed');
});
This is not a complete answer to your question, but I think someone who passes by would like to know this:
When you deal with JSONP from WCF REST try to use:
[JavascriptCallbackBehavior(UrlParameterName = "$callback")]
for your service implementation; this should give you JSONP out-of-the-box.
$.ajax({
url:' <?php echo URL::site('ajax/editing?action=artistSeracher') ?>',
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
artist: request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.artist,
value: item.artist,
id: item.id
}
}));
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});

Categories