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.
Related
I'm trying to attempt to generalize my ajax calls into a function as follows. I have not done this before and am not sure sure if I'm doing it correctly.
<script>
$(document).ready(function(){
var reg_no=$("#reg_no").val();
reg_no=reg_no.trim();
if(reg_no!==""){
//populate fields
data={reg_no:reg_no,func:"getSupplierDetails"};
success_function="updateFormFields";
ajax_call(data,success_function);
}
});
function ajax_call(data,success_function){
$.ajax({
type:"POST",
url:"../control/supplier-c.php",
dataType:"json",
data:data,
success:function(data){
success_function(data); //variable function works??
}
});
}
function updateFormFields(data){
//some code here to handle data array
}
</script>
What I'm trying to do here is avoid rewriting the whole ajax code by passing the data array and the function to be executed on success. What I'm not sure is the use of variable functions as i have done.
A note to be made is that the whole thing works for an ajax call if updateFormFields() code was moved into the success handler in the ajax call and the ajax_call() was not defined as a seperate function but implemented right after the comment "populate fields". I just have no experience in trying it this way and I need to know if this is possible or not.
Thank You
In Javascript, functions are first class objects, meaning you can pass them around as parameters.
function json_post(url, data, success_function, error_function) {
$.ajax({
type:"POST",
url:url,
dataType:"json",
data:data
}).then(success_function, error_function);
}
Then you can call it as
json_post("../control/supplier-c.php", { data: "data" }, function (res) {
console.log('Ajax req successful');
console.log(res);
}, function (res) {
console.log('Error in ajax req');
console.log(res);
});
In your case, you can do:
ajax_call(data, updateFormFields);
and it should work as expected.
There's no need to wrap the success function, you can just apply apply it directly.
function ajax_call(data, success_function) {
$.ajax({
...
success: success_function
});
}
An even better idea is to avoid the legacy success and error callbacks and instead return the jQuery promise. You can use standard promise methods .then() and `.
function ajax_call(data) {
return $.ajax({
...
});
}
ajax_call()
.then(function(data) {
// this runs if it succeeds
})
.fail(function(err) {
// this runs if it failed
});
Promises have a huge benefit to being chain-able, making the code flatter, avoiding the nest of "christmas tree callbacks".
I would recommend checking success_function as well as failure_function to handle server response (XHR) errors also.
function success_function(){
//code to handle success callback
}
function error_function(){
//code to handle failure callback
}
function ajax_call(data, success_function, error_function) {
if (typeof success_function === 'function' && typeof error_function === 'function') {
$.ajax({
type: "POST",
url: "../control/supplier-c.php",
dataType: "json",
data: data,
}).then(success_function).fail(error_function);
}
}
$.ajax({
type: "GET",
dataType: "jsonp",
jsonp: "jsoncallback",
data: {
//some data
},
url: "http://mydomain.com/checkRequest.php?jsoncallback=?",
success: function (result) {
if (result[0].data.NameB == "") {
alert("123");
} else {
alert("456");
}
},
error: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
}); // end of ajax
I have the above code, it works successfully if and only if there are somethings return.
However, if the PHP does not return anything, the string becomes: jQuery191025216468679718673_1364086240540([]);
and I expected it to go to else's part, which alert 456. But, it skips the whole success function. So, how should I modify the coding?
It works if I change the if clause to if (result!="")
Have a look at the console. I'm sure you get an error like
Cannot read property "data" of undefined.
If the array is empty, result[0] will return undefined and the subsequent property access will cause a run time error, which terminates the script immediately. Check first whether the arrays is empty or not:
if (result.length > 0 && result[0].data.NameB == "")
You might have to test the existence of result[0].data as well, depending on the data.
I have two javascript functions. from validateSearchStirng() i am calling checkSolrServerAvailibility(), from which i am expecting to return flag=1 if ajax request is successful otherwise flag=0. but each time checkSolrServerAvailibility() returning flag=0. Why so and what i need to do for getting correct result
function validateSearchStirng(sort,order,itemPerPage,showPage)
{
var serverflag;
serverflag=checkSolrServerAvailibility(sort,order,itemPerPage,showPage,query,solrURL);
if(serverflag==0)
{
var msg= "<hr /><font size="+size+" ><b>Solr Server Not Runing </b></font><hr /> ";
removeList();
$("#result").html(msg);
}
if(serverflag==1)
{
getSolrResponse(sort,order,itemPerPage,showPage,query,solrURL);
}
}
function checkSolrServerAvailibility(sort,order,itemPerPage,showPage,query,solrURL)
{
var start=itemPerPage*(showPage-1);
var end=itemPerPage;
var flag=0
$.ajax({
url: solrURL+"/solr/db/select/?qt=dismax&wt=json&&start="+start+"& rows="+end+"&q="+query+"&json.wrf=?",
async:true,
dataType: 'json',
success: function(json){
flag=1;
return(flag);
}
})
return(flag);
}
}
async : false
You should turn this flag to false.
Then you will get the desired results
You should probably forget about using JS functions this way and do it using callbacks. So basically instead of doing something like that:
serverflag=checkSolrServerAvailibility(...);
do something like that:
var processServerFlagCallback = function(flag){
// do something with your flag
}
checkSolrServerAvailibility(..., processServerFlagCallback);
and inside checkSolrServerAvailability, when you have information about success, invoke given callback with 1 as parameter, and in case of error - with 0 as parameter.
To see how to determine that an error occured during request, please see jQuery's .ajax() documentation on error parameter.
You need to redesign your solution to something like
function checkSolrServerAvailibility(sort,order,itemPerPage,showPage,query,solrURL, success, error){
$.ajax({
url: "",
dataType: 'json',
success: function(json){
success.apply(this, arguments);
},
error:function(){
error.apply(this, arguments);
}
})
}
function onAvailabilityCheck(json, textStatus, jqXHR){
getSolrResponse(sort,order,itemPerPage,showPage,query,solrURL);
}
function onAvailabilityCheckError(jqXHR, textStatus, errorThrown){
var msg= "<hr /><font size="+size+" ><b>Solr Server Not Runing </b></font><hr /> ";
removeList();
$("#result").html(msg);
}
function validateSearchStirng(sort,order,itemPerPage,showPage){
checkSolrServerAvailibility(sort,order,itemPerPage,showPage,query,solrURL, onAvailabilityCheck, onAvailabilityCheckError);
}
Since you are working with ajax request which by definition asynchronous in nature, your code will not work because once the client sent the ajax request to server it will not wait for the server response to comeback. It will keep executing the next lines... that means your flag will always be set to false.
To solve this problem my suggestion will be is to use callback methods to handle both success and failure cases as shown.
In the case of a successful ajax request the onAvailabilityCheck method will be called with the given parameters and if the ajax request is a failure the onAvailabilityCheckError method will be called.
All I need is a method that returns true if the Url is responding. Unfortunately, I'm new to jQuery and it's making my attempts at writing that method rather frustrating.
I've seen several examples of jQuery using .ajax, but the code is consistently failing on me. What's wrong?
var urlExists = function(url){
//When I call the function, code is still executing here.
$.ajax({
type: 'HEAD',
url: url,
success: function() {
return true;
},
error: function() {
return false;
}
});
//But not here...
}
That isn't how AJAX works. AJAX is fundamentally asynchronous (that's actually what the first 'A' stands for), which means rather than you call a function and it returns a value, instead you call a function and pass in a callback, and that callback will be called with the value.
(See http://en.wikipedia.org/wiki/Continuation_passing_style.)
What do you want to do after you know whether the URL is responding or not? If you intended to use this method like this:
//do stuff
var exists = urlExists(url);
//do more stuff based on the boolean value of exists
Then what you instead have to do is:
//do stuff
urlExists(url, function(exists){
//do more stuff based on the boolean value of exists
});
where urlExists() is:
function urlExists(url, callback){
$.ajax({
type: 'HEAD',
url: url,
success: function(){
callback(true);
},
error: function() {
callback(false);
}
});
}
urlExists() can not return because it needs wait for the request.
Either pass it a callback, or make it synchronous (not recommended, because it locks the browser).
var urlExists = function(url, callback) {
if ( ! $.isFunction(callback)) {
throw Error('Not a valid callback');
}
$.ajax({
type: 'HEAD',
url: url,
success: $.proxy(callback, this, true),
error: $.proxy(callback, this, false)
});
};
Then you can do
urlExists('/something', function(success) {
if (success) {
alert('Yay!');
} else {
alert('Oh no!');
}
});
It also worth mentioning the same origin policy.
Also, returning from an anonymous function's scope will not return in the parent function (like in your original example). It just returns that inner function. To return from an inner to a parent, set a flag and return it.
Basically, there is nothing wrong with your code. See it work here:
http://jsfiddle.net/PK76X/
My guess is that you're using it to check the availability of content on a different domain, which fails because browsers don't allow cross domain ajax-requests.
If the url is from the same domain as your page you can do it. But if it is from a different domain, for example google.com, then it will fail due to cross domain security.
In general, you should probably run your script in Firefox using the firebug plugin. It will give you the details needed to solve the issue.
The ajax and post methods are asynchronous, so you should handle the result in a callback method.
AJAX is basically asynchronous, and that's why the behavior you are describing.
I've used the following, which is free of cross origin, to get a simple true/false indication whether a URL is valid, in a synchronous manner:
function isValidURL(url) {
var encodedURL = encodeURIComponent(url);
var isValid = false;
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json",
type: "get",
async: false,
dataType: "json",
success: function(data) {
isValid = data.query.results != null;
},
error: function(){
isValid = false;
}
});
return isValid;
}
The usage is then trivial:
var isValid = isValidURL("http://www.wix.com");
alert(isValid ? "Valid URL!!!" : "Damn...");
Hope this helps
I have the following function which works great, i used JSONP to overcome cross-domain, wrote an http module to alter the content-type and didn't append a callback name in the url.
function AddSecurityCode(securityCode, token) {
var res=0;
$.ajax({ url: "http://localhost:4000/External.asmx/AddSecurityCode",
data: { securityCode: JSON.stringify(securityCode),
token: JSON.stringify(token)
},
dataType: "jsonp",
success: function(json) {
alert(json); //Alerts the result correctly
res = json;
},
error: function() {
alert("Hit error fn!");
}
});
return res; //this is return before the success function? not sure.
}
the res variable is alwayes comes undefined. and i can't use async=false with jsonp.
so how can i return the result to outside the function??
and i sure need to do that for subsequant calls.
Please advice, thanks.
The problem is i can't return the result value outside this function
You simply cannot do this.
You have to rewrite your code flow so that AddSecurityCode takes a callback parameter (i.e. a function to run) that you then invoke inside your success callback:
function AddSecurityCode(securityCode, token, callback) {
$.ajax({
....
success: function(json) {
alert(json); //Alerts the result correctly
callback(json); // HERE BE THE CHANGE
}
....
});
}
You have res declared inside the function, making it's scope local to that function. So there's a start. Declare res outside the function and see what happens.
Add async: false to the ajax request object
$.ajax({
...
async: false,
...
});
return res;
But this is not recommended since it will block the browser and will seen as not responding until the ajax call completed. Async process should use callback function like the other answer mentioning