I'm trying to get the return bool from the ajax call, but when I run the function and save to a variable but the only thing i get is undefined.
function check(number, id){
$.ajax({
url: 'ai.php',
data: {
"func":"checkNumber",
"id":id,
"number":number
},
method: 'GET',
dataType: 'json'
}).done(function(jData) {
return jData['idFound'];
}).fail(function(jData) {
console.log(jData['idFound']);
});
}
var test = check(44444, 12);
console.log(test);
// true
// but i get an undefined value in the console.log
Depend ur file 'ai.php' is a format json? please check validate http://www.jsonlint.com
Confuse ur code data, its just 'post' and not 'get'.
You can try getjson or ajax, look a exemple:
$(document).ready(function() {
$.getJSON('http://beta.json-generator.com/api/json/get/NkmG8_zBZ', function(json) {
for (x=0; x<json.length; x++) {
console.log('getjson>'+json[x].nome);
}
});
$.ajax({
type: 'get',
url: 'http://beta.json-generator.com/api/json/get/NkmG8_zBZ',
dataType : 'json',
success: function(json) {
for (x=0; x<json.length; x++) {
console.log('ajax>'+json[x].cidade);
}
},
error: function(err) {
console.log(err);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Without playing with the code more, this looks like an asynchronous issue to me.
This line calls the async function:
var test = check(44444, 12);
but logging the result immediately after will be undefined because you can't guarantee a return value unless you are within the 'done' callback function.
The default JQuery AJAX behavior is asynchronous, but if you truly need it to be synchronous, you can set the option explicitly, although it is not considered good practice:
$.ajax({
async: false,
...
});
Related
Struggling to return a AJAX Result Variable back to JavaScript
Note that the $.ajax call below is synchronous (async: false).
Ajax Call
function getState(callback) {
$.ajax({
url: 'getSearchState.php',
data: { "state": callback },
type: 'GET',
async: false,
success: function(result){
alert(result);
},
error: function(result) {
alert(result);
}
});
}
Ajax PHP
<?php
// Database Setup and Query
while ($row = $xxxxx->fetch(PDO::FETCH_ASSOC)) {
$StateVal = $row['State'];
}
return $StateVal;
?>
Javascript Calling the Function
var URL = District.trim();
var StateURL = getState(URL);
It gets the URL vairable from the function just fine, but doesnt return anything.
Any help would be great!
There are problems with that code both client-side and server-side.
Client-side:
Your getState is never returning anything, so it's no surprise that you don't see anything other than undefined for StateURL.
Don't use synchronous ajax. It makes for horrible UX. But if you really, really want to keep using it, here's how you would:
function getState(state) {
var result; // <=== Where we'll put our result
$.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET',
async: false,
success: function(data) {
// Remember the result;
result = data;
},
error: function() {
result = /*...whatever you want to use to signal an error */;
}
});
// Return the result
return result;
}
Note that I changed the name of the argument to state, since it's not a callback.
But again, don't use synchronous ajax. Instead, use a callback or promises.
Promise: $.ajax already returns a promise, so just return that directly:
function getState(state) {
var result; // <=== Where we'll put our result
$.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET',
async: false,
success: function(data) {
// Remember the result;
result = data;
},
error: function() {
result = /*...whatever you want to use to signal an error */;
}
});
// Return the result
return result;
}
Note that I changed the name of the argument to state, since it's not a callback.
But again, don't use synchronous ajax. Instead, use a callback or promises.
Promise:
function getState(state) {
return $.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET'
});
}
Usage:
getState(URL)
.done(function(StateURL) {
// Use it
})
.fail(function() {
// Failed
});
Callback:
function getState(state, callback) {
$.ajax({
url: 'getSearchState.php',
data: {"state": state},
type: 'GET',
success: function(data) {
// Call the callbback with the result
callback(data);
},
error: function() {
// Call the callback with an error
callback(/*...whatever you want to use tosignal an error */);
}
});
}
Usage:
getState(URL, function(StateURL) {
// Use it, check for error
});
Server-side:
As RiggsFolly pointed out, you're returning a string from your PHP code. But that won't output it. To use it client-side, you need to output it (e.g., echo and similar). And to make it easily consumed by the JavaScript, you probably want to json_encode it to ensure that it's in a format JavaScript can understand:
echo json_encode($stateVal);
Then in your success (or done) function, use JSON.parse on it:
result = JSON.parse(data);
this is jQuery and in this case you can specify context and in success function set variables on that context.... a bit crude solution but it will works. Also take a look on arrow functions and promises from ES6, it can help you a lot and give you new perspective about whole problem.
And one main thing!! Ajax is async by default so you need somehow notify your StateURL when data will be ready (here again promise at you service)
Is there a way to make a function that converts default ajax function.
This is the ajax function i have
$.ajax({
type: "POST",
url: "http://" + document.location.host + '/userajax',
data: 'type=register&name=' + name,
beforeSend:function() {
},
success: function(response) {
}
});
This is what i want it to look like
ajax('url', {
method: 'get',
parameters: {
name: $('#name').val()
},
beforeSend: function() {
},
success: function(transport) {
}
});
Ive tried to search on the internet but did not find anything
Sure, you can create the function like this:
function ajax(url, params){
// everything is now available here
console.log( url ); // output: http://www.google.com
// you can get the data of the params object like this
console.log( params.method ); // output: get
// you can execute the beforeSend like this:
params.beforeSend();
// additionally you might want to check everything.
// maybe if the method is NOT set, you want it to always use GET
switch(arguments.length) {
case 1: url = throw new Error('Url should be set');
case 2: params.method = 'get';
case 3: break;
default: throw new Error('illegal argument count')
}
}
You would call this like:
ajax('http://www.google.com', {
method: 'get',
parameters: {
name: $('#name').val()
},
beforeSend: function() {
// some function
},
success: function(transport) {
// some function
}
});
This certainly is possible, it's just a bit of work. Some of the basics you need:
First of all, you need a good understanding of the XMLHTTPRequest API, you can find more info on that on MDN.
Next, finding out how to do a callback, that is actually quite simple, you can pass an anonymous function reference as an option or attribute for a function. That goes like this:
function doSomething(variable, callback){
variable = variable + ' something'; // just doing something with the variable
callback(variable);
}
// then call the function with a callback (anonymous function)
doSomething('doing', function(result){ alert(result); });
You should get an alert that says 'doing something'.
And finally you should know how to read an object, passed as 'options' in the ajax function. Say you have a function like this:
function foo(url, options){
console.log(url);
console.log(options.method);
console.log(options.parameters.name);
}
// call it like this
foo('https://google.com/', {
method: 'get',
parameters: {
name: 'myName'
}
});
That should log the url, method and parameters in the console.
Now from here, you should have all the pieces to put the puzzle together. Good luck!
I don't think so. but you can do this:
$(document).ready(function(){
var parameters = {
name: $("#name").val(),
desc: $("#desc").val()
};
$.ajax({
url: 'path/to/file',
data : parameters,
beforeSend: beforeSubmit,
dataType: "json",
type : 'POST',
})
.done(function(data) {
})
.fail(function() {
console.log("error");
})
})
Also note I don't set the function for the beforeSend directly in the call, I will create an externe function which gives me more freedom.
so I could do this:
function beforeSubmit(){
if(something !== 'somethingelse'){
return false; //ajax call will stop
}else{
return true; //ajax call
}
}
I am using $.when and .done to make sure that the close window happens after the data is saved. But, this doesn't seem to work as expected.
The workflow is that, user clicks on a button "Save and Close", which should save the data first, trigger print and close the window. But the save data and close window happens at the same time which makes the print fail.
I have read about when..then and deferred object. Tried to implement it here the following code, sometimes it work but most of the time it would break.
$("#btnSaveAndClose").click(function (event) {
$.when(zSaveSomeData()).done(function (value) {
zCloseMyWindow();
});
});
function zSaveSomeData() {
return zSaveMasterData(masterdata, function () {
return zSaveDetailData();
});
};
function zSaveMasterData(masterdata, fnAfterSave) {
return $.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/masterdata/',
data: JSON.stringify(masterdata),
success: function (data) {
fnAfterSave();
}
});
};
function zSaveDetailData() {
var selectedDataGroups;
// some logic here
zSaveDetails(selectedDataGroups);
};
function zSaveDetails(selectedDataGroups) {
var deferred = $.Deferred();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/detaildata/',
data: JSON.stringify(selectedDataGroups),
success: function (data) {
var printableGroupIDs = [];
$.each(data, function () {
if (this.IsPrintable)
printableGroupIDs.push(this.ID);
});
if (printableGroupIDs.length > 0) {
zPrintGroups(printableGroupIDs);
}
deferred.resolve('done');
}
});
zAuditSave();
return deferred.promise();
};
function zPrintGroups(newGroupIDs) {
// calls external program to print groups
};
function zCloseWindow() {
window.close();
};
function zAuditSave() {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/audit'
success: function (data) {
}
});
};
Only thing is that the save calls other methods inside to same master and details data. There are couple of ajax calls too. An unusual thing is that after the data is saved, there is a call to VB code that actually triggers a Print. I am so confused on why would close window fire before the other methods are executed. Any help would be appreciated.
For me the code is overly divided into functions, with some doing little more than fronting for others.
I would prefer to see the click handler as a comprehensive master routine which sequences three promise-returning functions zSaveMasterData(), zSaveDetails() and zAuditSave(), then closes the window. Thus, some of the current functions will be subsumed by the click handler.
$("#btnSaveAndClose").click(function(event) {
zSaveMasterData(masterdata).then(function() {
var selectedDataGroups;
/* some logic here */
var detailsSaved = zSaveDetails(selectedDataGroups).then(function(data) {
var printableGroupIDs = $.map(data, function (obj) {
return obj.IsPrintable ? obj.ID : null;
});
if (printableGroupIDs.length > 0) {
// calls external program to print groups
}
});
// Here, it is assumed that zSaveDetails() and zAuditSave() can be performed in parallel.
// If the calls need to be sequential, then the code will be slightly different.
return $.when(detailsSaved, zAuditSave());
}).then(function() {
window.close();
});
});
function zSaveMasterData(masterdata) {
return $.ajax({
type: 'POST',
url: '/api/masterdata/',
contentType: 'application/json',
data: JSON.stringify(masterdata),
});
};
function zSaveDetails(selectedDataGroups) {
return $.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/detaildata/',
data: JSON.stringify(selectedDataGroups)
});
};
function zAuditSave() {
return $.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/audit'
});
};
Note the returns in the three functions with ajax calls. These returns are vital to the sequencing process.
A potentially bigger issue, not addressed in the question (nor in this answer) is how to recover from errors. Presumably, the database will be inconsistent if the sequence of saves was to fail part way through. It may well be better to ditch this client-side sequencing approach in favour of a server-side transaction that the client sees as a single operation.
The problem here is your code doesn't depend on when fnAfterSave() has completed.
Short answer: don't mix success methods, callbacks, and promises - use one pattern and stick to it - and the easiest pattern to use is promises.
$("#btnSaveAndClose").click(function (event) {
zSaveSomeData().then(function() { zCloseMyWindow(); });
});
function zSaveSomeData() {
return zSaveMasterData(masterdata).then(function(data) { zSaveDetailData() });
};
function zSaveMasterData(masterdata) {
return $.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/masterdata/',
data: JSON.stringify(masterdata)
});
//remove success callback here as it breaks the chaining
};
It seems like your problem is that you are doing asynchronous things inside an ajax success callback. The promise returned by $.ajax still resolves immediately after the response is received - and executes your done callback before the asynchronous zSaveDetailData() has finished.
So, to chain asynchronous actions, always use then. Use it even for synchronous actions, it makes the sequence clear.
Don't use success callbacks when you're working with promises. You also don't need deferreds. You might want to have a look at these generic rules as well, especially that you never must forget to return promises from async functions that you want to await.
$("#btnSaveAndClose").click(function (event) {
zSaveSomeData().then(zCloseMyWindow);
});
function zSaveSomeData() {
return zSaveMasterData(masterdata).then(zSaveDetailData);
}
function zSaveMasterData(masterdata) {
return $.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/masterdata/',
data: JSON.stringify(masterdata),
});
}
function zSaveDetailData() {
var selectedDataGroups;
// some logic here
return zSaveDetails(selectedDataGroups);
// ^^^^^^
}
function zSaveOrderGroups(selectedDataGroups) {
return $.ajax({
// ^^^^^^
type: 'POST',
contentType: 'application/json',
url: '/api/detaildata/',
data: JSON.stringify(selectedDataGroups)
}).then(function(data) {
// ^^^^^^^^^^^^^^^^^^^^^^
var printableGroupIDs = [];
$.each(data, function () {
if (this.IsPrintable)
printableGroupIDs.push(this.ID);
});
if (printableGroupIDs.length > 0) {
return zPrintGroups(printableGroupIDs);
// ^^^^^^
}
}).then(zAuditSave);
// ^^^^^^^^^^^^^^^^^
}
function zPrintGroups(newGroupIDs) {
// calls external program to print groups
}
function zCloseWindow() {
window.close();
}
function zAuditSave() {
return $.ajax({
// ^^^^^^
type: 'POST',
contentType: 'application/json',
url: '/api/audit'
});
}
i have a controller action which is return a boolean result to the jquery.
[HttpGet]
public ActionResult IsVoucherValid(string voucherCode)
{
bool result = false;
var voucher = new VoucherCode(voucherCode);
if(voucher.Status==0)
{
result = true;
}
return Json(result);
}
and call this controller using ajax code
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
alert("success");
if (data) {
//if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
},
error:alert("error")
});
in the success of ajax the json result is true then want to work the css. but this is not working please help me.
result is a variable name that only exists in that action method. It will not be included in the JSON.
I'm pretty sure that your boolean value will be stored in data since you are only sending back a single value:
$.ajax({
url: '/Account/IsVoucherValid?voucherCode=' + code,
type: 'Get',
contentType: 'application/json;',
success: function (data) {
if (data) { //if result=true, want to work this
$("#person-data").css({ "display": "block" });
}
}
});
If in doubt, do console.log(data) to see what it contains. You should at least be doing minimal debugging before you bring the question to us.
Also, as #Stephen Muecke points out below, if you are retrieving this data with GET, you need to use:
return Json(result, JsonRequestBehavior.AllowGet);
I have a link:
<a class="tag" wi_id="3042" wl_id="3693" for_user_id="441" href="#a">
which triggers an ajax call
$(".tag").click(function() {
var for_user_id = $(this).attr("for_user_id");
var wl_id = $(this).attr("wl_id");
var wi_id = $(this).attr("wi_id");
$.ajax({
type: "POST",
url: "/ajax/actions/tag.php",
data: {
'for_user_id': 'for_user_id',
'wl_id': 'wl_id',
'wi_id': 'wi_id'
},
success: function(data){
$(this).text("You've tagged this");
$(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged');
$(this).closest('.gl_buttons').addClass('tagged');
}
});
return false;
});
But in the console I see the following:
TypeError: e is undefined
The ajax file gets processed but the POST data is blank, and the success actions do not happen, so it gets posted with zeros and classes are not changed
I have stared and stared... anything obvious?
this is not passed automatically to the AJAX callback function. You can use the context: parameter to tell jQuery to pass it:
$.ajax({
type: "POST",
url: "/ajax/actions/tag.php",
data: {
'for_user_id': for_user_id,
'wl_id': wl_id,
'wi_id': wi_id
},
context: this,
success: function(data){
$(this).text("You've tagged this");
$(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged');
$(this).closest('.gl_buttons').addClass('tagged');
}
});
You're sending your data wrong, don't call your variables inside single quotes.
$(".tag").click(function() {
var for_user_id = $(this).attr("for_user_id");
var wl_id = $(this).attr("wl_id");
var wi_id = $(this).attr("wi_id");
$.ajax({
type: "POST",
url: "/ajax/actions/tag.php",
data: {
'for_user_id': for_user_id,
'wl_id': wl_id,
'wi_id': wi_id
},
success: function(data){
$(this).text("You've tagged this");
$(this).closest('.gl_buttons_holder').toggleClass('gl_buttons_holder gl_buttons_holder_tagged');
$(this).closest('.gl_buttons').addClass('tagged');
}
});
return false;
});