jquery ajax same data for all http codes - javascript

I have the following ajax, and it works fine when I get a 200, but when I get a 400 I get all sorts of extra data, is there a way to get the same data as the success for errors?
$.ajax({
type: "get",
url: getHost() + "/leaderboard/score?gameId=" + $("#gameId").val() + "&scoreId=" + $("#scoreId").val(),
dataType: "json",
success: function(data){
showOutput(data);
},
error: function(data){
showOutput(data);
}
});
function showOutput(data){
$("pre code").text(JSON.stringify(data, null, 4));
$('pre code').each(function(i, block){
hljs.highlightBlock(block);
});
}

The problem you face is that those callbacks take different parameters, for example to use complete it would be
complete: function(jqXHR, textStatus ){
showOutput(JSON.parse(jqXHR.responseText));
}
the responseText is parsed since showOutput expects an object and not a JSON string.

You need jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
Ref: http://api.jquery.com/jquery.ajax/
$.ajax({
type: "get",
url: getHost() + "/leaderboard/score?gameId=" + $("#gameId").val() + "&scoreId=" + $("#scoreId").val(),
dataType: "json",
success: function(data){
// showOutput(data);
},
error: function(data){
// showOutput(data);
}
}).always(function(data) {
showOutput(data);
});
function showOutput(data){
$("pre code").text(JSON.stringify(data, null, 4));
$('pre code').each(function(i, block){
hljs.highlightBlock(block);
});
}
Note that data may not always be available (on error, you will get back a jqXHR), so you'll need to sanitize the code otherwise the JSON.stringify could throw an exception.

Related

Handle undefined data in ajax request

I have the below ajax call and sometimes the request stops the page from loading as the data being passed is undefined.
I there a way to put a condition to handle the request if it has values that are undefined?
Can it be wrapped with a if condition?
newuser is not defined
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
Simplest way would be to use a pipe:
$.ajax({url: 'sample.aspx',
data: newuser || {},//continue here...
If your variable was not initialized, empty object will be sent instead.
That's if and only if you can handle empty "newuser" for some reason.
I'm assuming that not closed URL is just a mistake in copy-paste, and not actually part of your code.
how about
if(newuser)
{
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
}
If you are unable to handle an empty newuser you can try something like this:
if (newuser) {
$.ajax({
url: 'sample.aspx',
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data) {
...
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}

jQuery jsonp not firing the success handler even with the valid json format

$.ajax({
url: url,
dataType: 'jsonp',
success: function(data) { //not firing at all
console.log('success');
console.log(data);
}
error: function() { //always firing even with status 200 & valid JSON response.
console.log('error');
}
});
$.ajax({
url: url,
dataType: 'jsonp',
success: function(data) { //not firing at all
console.log('success');
console.log(data);
}, //You have missed a comma here..
error: function() { //always firing even with status 200 & valid JSON response.
console.log('error');
}
});
You have missed a comma.
Just check the comment

Where I should place return statement

I use Backbone.js and jQuery 1.7 in my application and I have some problems in building collection. In collection I have the method, which should return some object. I do "return" in $.ajax(...) success() function.
In this case i receive "undefined" instead of expected object. I understand, that the problem is in the "return" - it make success() function return some value. But I need getDomainZones() method do a return. How can I do it?
window.DmnList = Backbone.Collection.extend({
model: DmnItem,
localStorage: new Store("hosting.WhoIs"),
destroyAll: function (options) {
while (this.models.length > 0) {
this.models[0].destroy(options);
}
},
getDomainZones: function(){
$.ajax({
url: 'http://hosting/rest/getDomains',
type: 'GET',
dataType: 'json',
cache: 'false',
timeout: 5000,
success: function(data) {
console.log(data);
return data;//problem here
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[getDomainZones]: " + textStatus);
console.log(jqXHR);
},
});
}
});
"Where I should place return statement"
Nowhere. You can't return the result of an asynchronous AJAX request.
Any code that relies on the data, must be called inside the success callback.
One possibility is to have your getDomainZones method receive a function that will be called when the response is received.
getDomainZones: function( callback ){
$.ajax({
url: 'http://hosting/rest/getDomains',
type: 'GET',
dataType: 'json',
cache: 'false',
timeout: 5000,
// success: callback, // alternative if there's no other work to do.
success: function(data) {
console.log(data);
callback( data ); // invoke the function received
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[getDomainZones]: " + textStatus);
console.log(jqXHR);
},
});
}
So then you'd pass a function to getDomainZones, and when the response is received, getDomainZones will invoke the function you passed, passing it the data.
getDomainZones( function( d ) {
// do something with the data
console.log( d );
});

Receive serialized in php data by using ajax

I have a php script, which return serialized in php data. And I try to receive this data by using $.ajax() method from jQuery 1.7. Here is the example.
$.ajax({
url: 'http://input.name/get.php?do=lookup' + '&domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
type: 'GET',
dataType: 'text',
cache: 'false',
complete: function(res) {
alert('COMPLETE() done');
console.log(res);
}
});
In console I see only
Object { readyState=0, status=0, statusText="error"}
So, what I do wrong? Could you help me please?
UPD
Interesting notice: if I use JSONP dataType request can receive data, but can't process it.
Here is an example.
$.ajax({
url: 'http://input.name/get.php?do=lookup',
data: 'domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
dataType: 'jsonp',
cache: false,
success: function(data) {
alert("Data: "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: "+textStatus);
console.log(jqXHR);
}
});
Instead of complete: use success: then res will be the returned data from your ajax request.
Remember to use error: as well incase there is an error with you call, as it seems that there might be in your console output.
Code:
$.ajax({
url: 'http://input.name/get.php?do=lookup',
data: 'domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
cache: false,
success: function(data) {
alert("Data: "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: "+textStatus);
console.log(jqXHR);
}
});
Your code is probably fine, but you're trying to violate the same origin policy. Basically, if your site is http://aaa.com/, you cannot make AJAX called to http://bbb.com/.
There are a few ways around it:
Getting around same origin policy in javascript without server side scripts
But most of them require that both sides play nice.
The response is the second parameter of complete function:
$.ajax({
url: 'http://input.name/get.php?do=lookup' + '&domain=twittorama&tlds=.ru,.com,.net,.comf.ru',
type: 'GET',
dataType: 'text',
cache: 'false',
complete: function(res,response) {
alert('COMPLETE() done');
console.log(response);
}
});
More info: http://api.jquery.com/jQuery.ajax/
You should also consider using JSON, not php serialized data

IE not displaying ajax call results from database

question says it all... code:
$(document).ready(function() {
dataToLoad = 'showresults=true';
$.ajax({
type: 'post',
url: 'submit.php',
datatype: 'html',
data: dataToLoad,
async: true,
success: function(data){
$('#results').html(data);
},
});
});
You should use
dataType: 'html'
instead of
datatype: 'html'
and remove the trailing comma at the end (IE<=7 will throw error)
If the problem persists, add an error callback to see if there's an error
error: function(xhr, status, errorThrown){
alert("Error:\n" + status);
}
Hope this helps.
Cheers

Categories