//From other function
var check = check_abc(a,b,c);
alert (check);
function check_abc(a,b,c)
{
$.ajax({
type: "POST",
url: "abc.php",
data: { a: a,
b: b,
c: c
},
success:function(data) { //alert to get the data and make sure it was return ok.
if(data == "OK")
{
window.alert("YEA");
goOn();
}
else
{
window.alert("Testing");
noGood();
}
}
});
}
Event though it return "OK" (use alert to check before), but no matter what it never show alert("YEA"), why is it so? The data dont seem to be able to compare
That's because you're (correctly) using an asynchronous AJAX call. When you call check_abc(a,b,c), it immediately returns an undefined value, since the response from the server will come later.
Simplify your calling code to this:
//From other function
check_abc(a,b,c);
And inside the success function itself, display the dialog (which will happen when you get a response from the server):
success:function(data) { //alert to get the data and make sure it was return ok.
var displayBoolean = date === "OK";
alert(displayBoolean);
}
AJAX is asynchronous that why you can't get value
try like this
success:function(data) { //alert to get the data and make sure it was return ok.
if(data == "OK")
{catchVal("OK");return true; } //tried check == true; still cannot
else
{catchVal("Error");return false;}
}
function catchVal(val){
alert(val);
}
$.ajax({
type: "POST",
dataType: "text",
url: "abc.php",
data: { a: a,
b: b,
c: c
},
success:function(data) {
var result = $.trim(data);
if(result == "OK")
{
window.alert("YEA");
goOn();
}
else
{
window.alert("Testing");
noGood();
}
Related
I am working with APIs. My logic is 1st add a grade (POST), 2nd get the gradeID (GET), 3rd add grades to students (PUT). My problem is that I have to use the gradeID in the API call to add the grades.
How do I do using AJAX to get the result from one call and then pass to another call?
here is my ajax:
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) {
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
$("#responseFieldLabel").removeClass('hidden');
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
Is there a way tho have an ajax inside of other?
I am making a chain of AJAX calls like in the example below, which I found at http://www.dotnetcurry.com/jquery/1022/jquery-ajax-deferred-promises.
How can I adjust the code to prevent that function B gets called if the response from the AJAX call in function A is an empty JSON object array (i.e. "[ ]")? Ideally I would like to not only abort the chain of AJAX calls, but also inform the user that no result was found.
Thanks!
function A() {
writeMessage("Calling Function A");
return $.ajax({
url: "/scripts/S9/1.json",
type: "GET",
dataType: "json"
});
}
function B(resultFromA) {
writeMessage("In Function B. Result From A = " + resultFromA.data);
return $.ajax({
url: "/scripts/S9/2.json",
type: "GET",
dataType: "json"
});
}
function C(resultFromB) {
writeMessage("In Function C. Result From B = " + resultFromB.data);
return $.ajax({
url: "/scripts/S9/3.json",
type: "GET",
dataType: "json"
});
}
function D(resultFromC) {
writeMessage("In Function D. Result From C = " + resultFromC.data);
}
A().then(B).then(C).then(D);
function writeMessage(msg) {
$("#para").append(msg + "<br>");
}
Generically, you could make every one of your worker functions A, B, C, D return an object that contains the response data and whether you want to continue calling the next function in the chain, whatever that may be. Something like this:
function A(input) {
return $.get("/scripts/S9/1.json").then(function (response) {
return {
continue: response.data && response.data.length,
data: response
};
});
}
Now you can make a promise chain by reducing an array of worker functions, and deciding in every step whether you want to continue (in which case you execute the next worker) or not (in which you simply keep returning the last valid result for the rest of the chain). I've wrapped this logic into a function breakableChain, for lack of a better name.
function maybe() { return Math.random() > 0.25; }
function A(input) { console.log('in A:', input.data); return {continue: maybe(), data: 'result from A'}; }
function B(input) { console.log('in B:', input.data); return {continue: maybe(), data: 'result from B'}; }
function C(input) { console.log('in C:', input.data); return {continue: maybe(), data: 'result from C'}; }
function D(input) { console.log('in D:', input.data); return {continue: maybe(), data: 'result from D'}; }
function breakableChain(workers, init) {
return workers.reduce(function (current, next) {
return current.then(function (result) {
return result.continue ? next(result) : result;
});
}, $.Deferred().resolve({continue: true, data: init}));
}
breakableChain([A, B, C, D], 'initial data').then(function (result) {
console.log('overall:', result.data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Of course you can make a non-generic version of this that doesn't need a continue flag, but instead hard-codes the assumptions about each result directly into the if statement inside .reduce(). That would be shorter, but not re-usable.
The whole {continue: true, data: result} thing is just a convention. Your convention could also be "if the previous call returned anything, then continue, otherwise stop", the approach would be the same, but it would become impossible to return an overall result.
I have a function with Ajax call. If it returns true, another function with another Ajax should be run. But in my case first function returns true but the second function doesn't run. How to do that?
If I remove this: if(checkIfCompleted()) { from the second function, it's working. But I have to check if first function returns true.
My code is:
function checkIfCompleted() {
$.ajax(
{
url: Base_URL + "/offers/" + 'checkIfQuoteIsComplete',
type: "POST",
data: {
"offer_id": offer_id
},
success: function (data) {
if(data === 'notcompleted') {
$("#NotCompleteQuotes").modal();
return false;
} else {
return true;
}
},
error: function (data) {
MessageBoxError('Error');
}
});
}
Second function that should run after first function returns true is:
function saveOrEditQuote(status, id) {
if(checkIfCompleted()) {
//my code here - it's long
return false;
}
}
Javascript is asynchronous, try using callbacks like this
function checkIfCompleted(callback) {
$.ajax(
{
url: Base_URL + "/offers/" + 'checkIfQuoteIsComplete',
type: "POST",
data: {
"offer_id": offer_id
},
success: function (data) {
if(data === 'notcompleted') {
$("#NotCompleteQuotes").modal();
} else {
callback();
}
},
error: function (data) {
MessageBoxError('Error');
}
});
}
then
function saveOrEditQuote(status, id) {
checkIfCompleted(function(){
// will be done only on success
//my code here - it's long
return false;
})
}
Explanation:
A callback is simply another argument, the difference is that it is a function, not for example an integer. By using them you can make sure some block of code is called only after something. They're really helpful for actions that take some time (like requests, jquery animations, timeouts).
All you have to do is pass in the second callback function saveOrEditQuote() into the body of the success callback. You'll need be careful to declare that function in the right scope, because the success callback will be a different scope than checkIfCompleted.
Also, often the success argument data will be an array of objects and strings so data === 'notcompleted' may be comparing an array to a string.
function checkIfCompleted (){
var success = saveOrEditQuote;
$.ajax({ ... }).success(function(data){ success(true); })
}
function saveOrEditQuote(isCompleted){...};
i've a HTML.ActionLink on view. what i'm doing is i'm making call to $.ajax() function which checks for return true or false from an anction. it hitting the action, returning the desired result true/false. but the problem is when it returns false. i need to show an alert and redirect should be only in case if its return true..
ActionLink:
<%: Html.ActionLink("Add Race", "AddRace",
new {eventId = Model.EventId, fleetId=Model.SelectedFleet.ID},
new{onclick="return checkFleetAddedandScroing()"}) %>
Function:
function checkFleetAddedandScroing() {
debugger;
$.ajax({
type: "GET",
url: '<%=Url.Action("CheckFleetExists", new {eventId=Model.EventId})%>',
dataType: "json",
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
alert('Ok button clicked');
return true;
}
else {
alert("Cannot delete this fleet becasue either you have already added races to this event or the fleet has used for boat registration.");
return false;
}
}, //success
error: function (req) {
}
});
}
it redirects always..whether it returns true/false..it should redirect only if it returns true....
Please correct me where i'm doing wrong..
You're returning false from the AJAX callback.
That has nothing to do with the return value from the outer function; the AJAX callback won't even start running until later.
you must wait for your request to receive the result, and for doing this set async parameter of ajax function to false.
EDIT: you are lucky with your scenario. you can always return false and in case of successful delete call a function named DoRedirect.
this is the way to go :
function checkFleetAddedandScroing() {
debugger;
$.ajax({
type: "GET",
url: '<%=Url.Action("CheckFleetExists", new {eventId=Model.EventId})%>',
dataType: "json",
timeout: 30000,
cache: false,
success: function (data, textStatus) {
data = eval("(" + data + ")");
if (data == true) {
alert('Ok button clicked');
DoRedirect();
}
else {
alert("Cannot delete this fleet becasue either you have already added races to this event or the fleet has used for boat registration.");
}
}, //success
error: function (req) {
}
});
return false;
}
function DoRedirect(){
//code for do redirect
}
cheers!
I want to make a if loop according to what returns html(data), so how can I get in my ajax script a var returned by "form_treatment.php" ? I want to close the colorbox (a lightbox) containing myForm only if "form_treatment.php" returns a var PHP with a "true" value.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
$('#message').html(data);
// Make a if loop according to what returns html(data)
}
});
return false;
});
form.php :
<form method="post" action="form_treatment.php" >
<input type="text" name="user_name" value="Your name..." />
<button type="submit" >OK</button>
</form>
form_treatment.php :
if ( empty($_POST['user_name']) ){
$a = false;
$b = "Name already used.";
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
$a = false;
$b = "Name already used.";
} else {
$a = true;
$b = "Verification is OK";
}
}
Try adding dataType : 'json' inside your $.ajax() call, and then, in your php file, respond with nothing but a json object such as:
{ "success" : true, "msg" : 'Verification is OK' }
Then, inside your $.json() success function, you can access anything from the server's response like so:
if (data.success) {
alert(data.msg);
}
I know you said you want to loop, but that's just an example. Note that PHP has a great little function called json_encode() that can turn an array into a json object that your JavaScript will pick up just fine.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
// if data is a variable like '$a="Verification is OK"':
eval(data);
if ($a == 'Verification is OK')
$("#colorBox").close() // or whatever the close method is for your plugin
else
$('#message').html($a);
}
});
return false;
});
The var "data" is the response being passed back from your PHP file. Therefore, you can do something like:
...success: function (data) {
if (data == 'Verification is OK') {
// Make a if loop according to what returns html(data)
}
}
You just have to make a simple comparison in your success function in the ajax request, like this:
success: function (data) {
$('#message').html(data);
if(data == 'Verification is OK')
{
// make the lightbox show
}
}