Ajax interrupt current function without using async - javascript

i have a custom jQuery function with callbacks, in one of them i want to do a server-side check before some event is triggered.
Something like this:
var object = $('#object').customFunction({
onSomeEvent: function (someData) {
$.ajax({
...
...
success: function(data) {
if (data == ok) {
return true;
} else {
return false; *****
}
}
})
},
})
**** I want this "return false;" to be the return of "onSomeEvent".
I know i can make the ajax call async false, save the response data in a variable, check it after the ajax and return the false then, but i really would like to avoid the async false.
I really dont know what to try, everything i google is putting the ajax async on false.
Thanks in advance for your help!

to avoid setting async to false, im using this..
my_request = $.ajax({
...
...
})
my_request.done(function(data)){
//you can set the data to global
});

Related

ajax and javascript - function return my null but when i console.dir i see the data

why when i try to return value from function i get undefined?
i know i use void function but what happen if i want get value form function like that?
thanks!
var t = getdata();
console.dir("test:" + t); -- > undefined
function getdata() {
var list = "";
$.ajax("api/publish",
{ method: "get" })
.then(function (response) {
console.dir(response); --> print the response
});
return list;
}
javascript is an asynchronous programming language and you are doing an ajax call so on ajax call by default async will be true so you have to try with async : false on ajax call. Just give try may be it will give luck

Collect html form data and send as a json payload to an api [duplicate]

I got following code :
$.ajax({
type: "POST",
async: false,
url: "CheckIdExist",
data: param,
success: function(result) {
if (result == true){
return false;
}
},
error: function(error) {
alert(error);
return false;
}
});
if ajax return value is true, form needs to stop submit.
but it does not stopping submit form.
any help please.
I assume you have something like:
form.submit(function(event) {
$.ajax(...);
});
You want to return false (or call event.preventDefault()) in the event handling function itself, and not in the AJAX call, such as:
form.submit(function(event) {
event.preventDefault();
$.ajax(...);
});
A slight variation of this question is:
I want to use jquery and ajax to present an error message to a user,
but then to do normal processing if there is no error.
Suppose method "check" returns a response that is empty if there is no error, and has the error(s) in it if there are any.
Then you can do something like this in your ready function:
$("#theform").submit(function() {
var data = { ... }
$.get('/check', data,
function(resp) {
if (resp.length > 0) {
$("#error").html(resp);
} else {
$("#theform").unbind('submit');
$("#theform").submit();
}
});
event.preventDefault();
});
So, how does it work? When the outer submit function is triggered, it builds the data needed for the AJAX call (here the higher level function get). The call is scheduled, and the main thread of operation immediately continues, but the submit is unconditionally stopped, so nothing apparent happens.
Some time passes, and the AJAX call returns the result of the request. If non-empty, the result is shown to the user.
If the response is empty, however, the submit function is unbound. This prevents the ssytem from making an extra call through the outer submit function. The inner submit function is called. This triggers an actual form submission to the form's target, and life goes on as expected.
You need to do a callback.
This entry in the FAQ helped me a lot when I had this exact problem.
getUrlStatus('getStatus.php', function(status) {
alert(status);
});
function getUrlStatus(url, callback) {
$.ajax({
url: url,
complete: function(xhr) {
callback(xhr.status);
}
});
}
The reason for that is that you can not return in an AJAX function.
The code above does not work as desired due to the nature of asynchronous programming. The provided success handler is not invoked immediately, but rather at some time in the future when the response is received from the server. So when we use the 'status' variable immediately after the $.ajax call, its value is still undefined.
You can't put this code in a function or in the onsubmit of a form, the success function returns it's result returning to the jQuery ajax context, NOT the form submit context.
In this case you need to perform a synchronous http request, i.e. you have to set the async option to false.
In your version the httpxmlrequest is asynchronous. It might be finished long after your onsubmit handler has returned and the onsuccess callback is invoked out of context of the onsubmit handler.
The "return false" will be the return value of the anonymous function function(result) {... } and not the return value of the onsubmit handler.
I had this problem also but solved it by changing the input type="submit" to type="button" and then just do your ajax request
$("input#submitbutton")
{
$.ajax(
{ type: "POST",
async: false,
url: "CheckIdExist",
data: param,
success: function(result) {
if (result == true){
//TODO: do you magic
}
else
$("form").submit();
},
error: function(error) {
alert(error);
return false;
}
});
});

More compact way to write ajax queries

I have been writing many web apps with php & mysql & jquery & bootstrap and now it's time address this problem. How to write shorter ajax queries(posting) ?
If I want to write code that works and takes care of many problems, it's too long for every ajax call.
Is there a better way or some library / wrapper that makes the code SHORTER and FASTER to write, but does atleast all these stuff
I looked popular axios, but it seems even worse
//JUST an example code, too complicated
var $btnStatusElem = $("#passwordreset").button('loading');
$.ajax({
type: "POST",
cache: false,
url: "pwreset.php",
data: postdata
success: function(data) {
$btnStatusElem.button('reset');
try {
var datajson = JSON.parse(data);
}
catch (e) {
alert('Unexpected server error');
return false;
};
if (datajson['success'] == true) {
//do the OK stuff
} else {
//show the error code, and stuff
return false;
}
},//success
error: function(msg) {
alert('ERROR');
$('#passwordreset_result').html(msg);
}
});
For my code, ajax query, i want it to do these steps:
1. Disable the submit button while posting (re-enable also after 15 seconds and not just leave it disabled until page refresh)
2. It sends json, expects json to return
3. If server has some error, it DOES NOT return json but error. Then the code will halt all js execution if i dont use try...catch. This is pain to write each time
4. If server returns validation error or some other expected error, i have to detect this and show to the user
5. If all ok, do the stuff
As with any refactoring, identify and isolate the repetitive code and pass in the unique bits. In this case, for example, you could isolate the ajax call and json parsing into a function and pass in the url, data, etc.
That function could return a promise that resolves/rejects as appropriate.
Given the doRequest function below (pseudocode, untested and would probably need a bit of tweaking for real-world use), you could then use it all over the place with fewer keystrokes:
doRequest('pwreset.php', postdata, button)
.then(result => {
// do something with the result
})
.catch(error => {
// deal with the error
});
or
try {
const result = await doRequest('pwreset.php', postdata);
// do something with result
}
catch (e) {
// handle error
}
All of the boilerplate stuff is isolated in doRequest.
async function doRequest(url, data, button, type = "POST") {
return new Promise((fulfill, reject) => {
$.ajax({
type,
url,
data,
cache: false,
success: function(data) {
$btnStatusElem.button('reset');
try {
const datajson = JSON.parse(data);
} catch (e) {
return reject(e);
};
return datajson['success'] == true ?
fulfill(datajson) :
reject(datajson);
}, //success
error: function(msg) {
return reject(msg);
}
});
})
}
As #mister-jojo says, you might also want to consider using the [fetch api] instead of jQuery, but the same principle applies.

how to use if statment inside $.ajax( and check for string response?

I am trying to do this simple compare inside ajax post request. I just want to check the post response for different string values but it never works. The popup function never get called even i know for sure that php response is string "mango"could you guys tell me what i am doing wrong here ?
$.ajax(
{
type: 'POST',
url: './doit1.php',
data: {
title: 'test',
},
success: function (good)
{
//handle success
if($(good) =='mango')
{
popitup('./doit1.php?action=stop')
//alert(good)
else if ($(good) =='orange')
{
//do something
}
else
{
//default action
}
},
failure: function (bad)
{
//handle any errors
alert(bad)
}
});
function popitup(url) {
newwindow=window.open(url,'name','height=200,width=150');
if (window.focus) {newwindow.focus()}
return false;
}
You are trying to wrap a jQuery wrapper around your returned data here:
if($(good) =='mango')
That is incorrect, as good would need to be a DOM element in that case for this to have any meaning.
If good is just a string value that is returned, you should just be doing this:
if(good == 'mango')
Without knowing what good is it's hard to say. However, $() always returns a jQuery collection object that is no good for comparisons of any kind. You probably just want to use good == 'mango' or a switch. Perhaps it's good.fruit == 'mango'.
You're wrapping good in jQuery when it should just be put in as a string.
Replace the success function with.
success: function (good){
//handle success
if(good==="mango"){
popitup('./doit1.php?action=stop')
}else if(good==="orange"){
//Do something
}else{
//Default Action
}
}

jQuery submit form calls a function with ajax

jQuery(document).ready(function(jQuery) {
function checkEmail(email){
jQuery.post('someroute.php',
{email:eamil},
function(data){
if(data==error){
return false;
}
);
return true;
}
jQuery('#myform').submit(function(){
// como code and at the momment this
var result true;
//then I check email
var email = ('#myemail').val();
result = checkEmail(email);
return result;
});
The problem is this, a checkEmail function, first return true, and then return value jQuery.post function. Why?
I checked and in submit, first return true, and if you stop submit then you release that post return the value. Post works fine, but I don't understand why function checkEmail does not wait until post returns the value and goes on until the end to return true.
Because the jQuery.post() function is an AJAX request, and the first A in AJAX stands for asynchronous. That's exactly what asynchronous is, it doesn't stop code execution while it waits for a response. It fires the request and then immediately moves on to any code after the line making the request, in this case your return true statement.
Like Anthony Grist said. .post is an asynchronous call which means it doesn't wait to finish.
I've looked up the .post method (http://api.jquery.com/jQuery.post/).
It's basicly a shortcut for .ajax. You're missing the fail method in here so I would say use the .ajax call.
var value = 1;
var handlerUrl = "someroute.php";
//Do the Ajax Call
jQuery.ajax(
{
url: handlerUrl,
data: { email:eamil },
type: 'POST',
success: function (data)
{
return true;
},
error: function (jxhr, msg, err)
{
return false;
}
});
#user1727336 : Hi! You might want to edit your code and add the missing } and });. Here's a fix:
// enter code here
jQuery(document).ready(function(jQuery) {
function checkEmail(email){
jQuery.post('someroute.php', {email:eamil},
function(data){
if(data==error){
return false;
}
});
return true;
}
});

Categories

Resources