I am using the following get getJSON
$.getJSON("js/production-data.json").done(function(response) {
console.log(response);
console.log('hello');
});
I can see in Firebug that the data is being retrieved, but there is no console.log for the response which would be the entire data. I can't even see hello either.
Try specifying the callback inline, like:
var jqxhr = $.getJSON( "example.json", function() {
console.log( "success" );
});
As another step, add an always handler, rather than only done.
$.getJSON("data.json", function(d) {
}).done(function(d) {
console.log("success");
}).fail(function(d) {
console.log("error");
}).always(function(d) {
console.log("complete");
});
Also get the JSON verified at JSONLint
Related
I'm dealing with this piece of code and I'm going crazy since I can not find where my error is:
$.post($form.attr('action'), $form.serialize(), function (result) {
console.log(result);
if (result.success === false) {
console.log("no success");
} else {
console.log("success");
}
}, 'json')
This what console.log(result) outputs: Object {success: true, errors: "", redirect_to: "/app_dev.php/login"} but the conditional is not going through no success either success, why? Where I'm making the mistake?
From jQuery.post() | jQuery API Documentation:
success
Type: Function( Object data, String textStatus, jqXHR jqXHR )
A callback function that is executed if the request succeeds. Required
if dataType is provided, but can be null in that case.
Try adjusting your callback function definition from function (result) { to:
function( data, result ){
Then use the result string to run your conditional.
Without seeing more of what's going on behind the scenes with your $form object, I'd guess that something else there may be interrupting execution. Try NOT running the console.log() until after your conditional.
$("#container").on("change", "#control1", function() {
if ($("#checkData").val()) {
$.get("/Controller/CheckData/" + $("#control2").val(), function(data1) {
if(!data1.Success) {
alert("Unable to do POST.");
return;
});
};
formData = $("#form").serialize();
$.post("/Controller/PostData", formData, function(data2) {
// Do something...
});
}
If checkData is false, the form should post. If checkData is true, the form should only post if the get returns true.
This doesn't seem to work because the form gets posted while the alert dialog is still open. I think it may be due to the asynchronous nature of AJAX. Is this correct?
Yes. When you call the $.get() method, the code continues executing. That means that it immediately goes to the declaration and $.post() call that follow. If you want to wait to execute those until after the $.get() call completes, you'll need to put them in the callback function.
yes, the post will always happen because you haven't done anything to prevent it. If you want the post to be sent or not sent based on the outcome of the $.get, you'll need to move it to the get callback fn.
Additionally, your code was riddled with syntax errors, though I suspect many of them were copy paste errors otherwise you wouldn't have even been getting the alert.
$("#container").on("change", "#control1", function () {
if ($("#checkData").val()) {
$.get("/Controller/CheckData/" + $("#control2").val(), function (data1) {
if (!data1.Success) {
alert("Unable to do POST.");
} else {
var formData = $("#form").serialize();
$.post("/Controller/PostData", formData, function (data2) {
// Do something...
});
}
});
}
});
Yes, you'll allways get to $.post...
Yes. And you cannot return from a callback. You will need to do
$("#container").on("change", "#control1", function () {
if ($("#checkData").val()) {
var formData = $("#form").serialize();
$.get("/Controller/CheckData/" + $("#control2").val(), function (data1) {
if (!data1.Success)
alert("Unable to do POST.");
else
$.post("/Controller/PostData", formData, function (data2) {
// Do something...
});
});
}
});
Btw, it might be unsafe to rely on a client-side check of the data (even if by ajaxing /CheckData/) before "allowing" a POST request. If you want a two-step process, you should return a "safety" token from the GET request.
Please note that these two lines are reversed in your code (and therefore don't match up):
$("#container").on("change", "#control1", function() {
if ($("#checkData").val()) {
var c2 = $("#control2").val();
$.get("/Controller/CheckData/" + c2, function(data1) {
if(!data1.Success) {
alert("Unable to do POST.");
return;
} <=== HERE
}); <=== HERE
};
formData = $("#form").serialize();
$.post("/Controller/PostData", formData, function(data2) {
// Do something...
});
}
I extracted var c2 from the $.get line only to see the braces more easily, not for any other reason.
I am using the following code to do the cross domain AJAX request with YQL :
function requestCrossDomain( site, callback ) {
function cbFunc(data) {
// If we have something to work with...
alert("inside call back");
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
// If no url was passed, exit.
if ( !site ) {
alert('No site was passed.');
return false;
}
// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=cbFunc';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, cbFunc );
console.log("outside call back");
}
and calling the above as follow :
requestCrossDomain('http://www.cnn.com', function(results) {
alert(results);
});
When i am running the above code in firefox, although response (in firebug console) is showing the content of website inside callback function (cbFunc) yet it is showing nothing as alert.Also the result of console.log("inside call back") at line 5 is not printing in firebug console.
can anyone suggest me where things are going wrong or any explanation for above ?
btw i have already gone through :
http://tek-insight.blogspot.in/2010/05/cross-domain-ajax-request-proxy-json.html
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-cross-domain-ajax-request-with-yql-and-jquery/
Possible explanation in related stackoverflow questions.
$.getJSON accepts as callback function for 'success' response. But if error were returned (404, 500, etc) then it will not call this function.
You need to add extra functions in order to catch other scenarios of responses:
$.getJSON( yql, cbFunc)
.done(function() { console.log( "second success" ); })
.fail(function(jqxhr, textStatus, error) { console.log( "error", textStatus, error ); })
.always(function() { console.log( "complete" ); });
According to my previous post I am trying to get back some information from a RESTful interface using JSON. I am working on JQuery 1.5.
The problem I face is that I get back as a result undefined values. I am not able to use firebug because my application is developed using PhoneGap and the app is running on the iPhone's simulator.
If I visit the RESTful interface (I type the "example.json" url in a browser - where example is a valid url created by another developer) returns me results with the following format:
[{"person":{"created_at":"2011-07-18T17:51:33Z","id":1,"name":"John","age":60,"surname":"Smith","car_id":1,"updated_at":"2011-07-18T17:51:33Z"}},{"person":{"created_at":"2011-07-18T17:51:35Z","id":1,"name":"Johnny","age":50,"surname":"Deep","car_id":2,"updated_at":"2011-07-18T17:51:35Z"}}]
I need to get the information id, name, age and store them in an array (not an html table). Just to see if the connection returns any values I use the code:
var jqxhr = $.getJSON("example.json", function(person) {
$.each(person, function(i, person) {
alert(person.name);
alert(person.age);
});
})
.success(function() { alert("second success"); })
.error(function() { alert("Cannot connect to the SWT's maps. Please try again later!"); })
.complete(function() { alert("complete"); });
So, why do I get by the alert undefined as values?
This code should work:
var jqxhr = $.getJSON("example.json", function(person) {
$.each(person, function(i, item) {
alert(item.person.name);
alert(item.person.age);
});
})
.success(function() { alert("second success"); })
.error(function() { alert("Cannot connect to the SWT's maps. Please try again later!"); })
.complete(function() { alert("complete"); });
are you sure of your code ? try:
var jqxhr = $.getJSON("example.json", function(data) {
$.each(data, function(i, item) {
alert(item.name);
alert(item.age);
});
}
Hope this helps
I am writing a generic function that will be reused in multiple places in my script.
The function uses ajax (using jQuery library) so I want to somehow pass in a function (or lines of code) into this function to execute when ajax is complete.
I believe this needs to be a callback function, but after reading through a few callback answers I'm still a bit confused about how I would implement in my case.
My current function is:
function getNewENumber(parentENumber){
$.ajax({
type: "POST",
url: "get_new_e_number.php",
data: {project_number: projectNumber, parent_number: parentENumber},
success: function(returnValue){
console.log(returnValue);
return returnValue; //with return value excecute code
},
error: function(request,error) {
alert('An error occurred attempting to get new e-number');
// console.log(request, error);
}
});
}
With this function I want to be able to do something in the same way other jQuery functions work ie;
var parentENumber = E1-3;
getNewENumber(parentENumber, function(){
alert(//the number that is returned by getNewENumber);
});
Just give getNewENumber another parameter for the function, then use that as the callback.
// receive a function -----------------v
function getNewENumber( parentENumber, cb_func ){
$.ajax({
type: "POST",
url: "get_new_e_number.php",
data: {project_number: projectNumber, parent_number: parentENumber},
// ------v-------use it as the callback function
success: cb_func,
error: function(request,error) {
alert('An error occurred attempting to get new e-number');
// console.log(request, error);
}
});
}
var parentENumber = E1-3;
getNewENumber(parentENumber, function( returnValue ){
alert( returnValue );
});
#patrick dw's anwser is correct. But if you want to keep calling the console.log (or any other actions) always, no matter what the caller code function does, then you can add the callback (your new parameter) inside the success function you already have:
function getNewENumber(parentENumber, cb_func /* <--new param is here*/){
$.ajax({
type: "POST",
url: "get_new_e_number.php",
data: {project_number: projectNumber, parent_number: parentENumber},
success: function(returnValue){
console.log(returnValue);
cb_func(returnValue); // cb_func is called when returnValue is ready.
},
error: function(request,error) {
alert('An error occurred attempting to get new e-number');
// console.log(request, error);
}
});
}
And the calling code remains the same as yours except that the function will receive the returnValue by parameter:
var parentENumber = E1-3;
getNewENumber(parentENumber, function(val /* <--new param is here*/){
alert(val);
});
This would be better done with jQuery's Deferred Objects. Have your AJAX call return the jqXHR object.
function getNewENumber(parentENumber) {
return $.ajax( { ... } );
}
getNewENumber(E1 - 3).then(success_callback, error_callback);
If you want to keep the error callback within that function you can register that there instead:
function getNewENumber(parentENumber) {
var jqXHR = $.ajax( { ... } );
jqXHR.fail( ... );
return jqXHR;
}
getNewENumber(E1 - 3).done(success_callback);