How to make wait the 1 method to finish other in Javascript - javascript

In asp.net website, i need to submit the some fields to insert into database. OnclientClick event i have javascript method to validate the input, it method return false in case validation failed and true in case validation success. If it return true then server side event process ahead to insert the data.
My problem is in javascript main validation method it call server side method through ajax to get some data in order to validate the form. Main javascript method dont wait of server side call and it process move ahead, that means i am not able to validate that method and it go ahead and make postback.
function ValidateInput()
{
if(1 == 2)
{
return false;
}
// other logic to validate
ServiceSideCalltoValidate();
// It dont wait of above method and make the postback
}
In other words i need to implement the logic so that 1 javascript method should wait to finish the call of another javascript.

Your javascript function calls AJAX to validate the data and every AJAX call complete then it will return value. So what you need to do it, return some value from AJAX call and if its true then after you can call server size click event.

Related

Ajax sending response back to php after ajax call

Suppose I have a page called form.php. I then clicked a button called "add button". This button triggers an event that got detected by a jquery function. The jquery function makes an ajax call to add.php.
Inside add.php, there is code that checks if a particular record exist in the database. If it does find that the record exists, I want to do the following.
Send a response string "exist" to ajax.
The ajax, inside the .done() function, will execute a prompt that says "This record already exist, do you wish to overright"?
If the user canceled the prompt, nothing more should happened and the ajax call should be done.
If the user clicks "ok", I would like the php script to be notified of this and execute an update statement using the data from form.php.
I suspect this is impossible because after receiving a response from php, AFAIK there is no way for ajax to respond back to the php script that is currently executing.
Am I correct or there is a way to do this?
You have to add a parameter to your ajax request, like override with true and false. By default/first request you set it to false. Then the add.php does it's default and returns exists.
The the user makes his decision. If he want to override, you send the ajax request again with the override parameter to true. Your add.php will notice the parameter and does whatever it has to do.
Wrap your ajax handler in an own function with a done callback. So you can reuse the request as often as you want. Pretty easy, no double code needed as well ...
The .done() function of your first ajax call executes when the ajax call has finished successfully, so when your php script has finished completely.
If you want to do something else, you would need to make a new ajax request. That could be to the same or another script, sending in different / new / additional parameters.
Note that you have to make sure that the second script cannot be called without the first one finishing, for example by setting and checking an expiring session variable.
you can do something like this.
$.post('add.php',$(this).serialize())
.done(function(result){
var r = confirm("This record already exist, do you wish to overright");
if(result == 'exist'){
if (r == true) {
$.post('update.php',$(this).serialize()).done(function(r){
console.log(r);
});
} else {
return false;
}
}else{
console.log(result)
}
});

What is the proper way to submit HTML form after asynchronous data load?

Silly that I can't find this so I apologize in advance if I have duplicated, but I have looked through search engines and SO without finding what I need.
What is the proper way to submit an HTML form upon user click but only after I have asynchronously loaded data from a 3rd party API to fill in for some of the form's hidden fields?
I tried this structure, which has not worked:
form onclick = function1()
function1() calls function apicall that retrieves info from 3rd party api and in its completion handler then calls function2
function2 checks all form fields and returns true if form should be submitted, false if it should not
With this structure, my form is always submitted, although both the 3rd party api function completion handler and function2 are working properly on their own. function2 can return false all day long but the form still submits. What can I do about this? The asychronous timing seems alright but somehow the return false is not getting back to the FORM element.
Thank you for any tips or code samples.
Asynchronous functions can't return anything -- the caller isn't waiting for them to finish. So the form's onsubmit handler should return false to prevent the form from submitting.
Then in function2(), if the form validation succeeds, it can call
document.getElementById('formID').submit();
to perform the actual form submission.

Synchronization in JavaScript

I have a use case like this:
When user clicks on a radio button I make an ajax call to get some information dependant on the user selection. When user clicks on a link I use the information form AJAX call to display an alert.
I need:
to ensure the result of the ajax calls are written in the correct
order
If the user to open the alert, before then the AJAX call is finished I want to display him a waiting icon, otherwise display him
the alert
If the response from AJAX doesn't comein 2s I will display the alert anyway
I am not really asking how to do this specific use case in JS, since I can figure out how to combine timer, jQuery ajax callbacks and so on.
I see the problem in a more generic way:
we have three events (AJAX success, user click, timeout) and I wanto to associate some code to be triggered by some conditions on the events. Is there any framework that allows to associate actions to a combination of events?
Or am I just using the wrong approach?
1 - If the response order is important, it's not useful to allow multiple parallel requests, which means when the user will select a radio button, you should queue the operations. That's very easy to achieve with promises.
E.g.
var promiseQueue;
function processRequest(radioValue) {
return $.ajax({ ... }).done(/*handle request*/);
}
function onRadioClicked() {
var radioValue = this.value; //assuming this is your radio element
//if the queue was initialized, queue our next operation using "then",
//otherwise process the request directly and initialize the queue with the
//returned promise.
promiseQueue = promiseQueue?
promiseQueue.then(processRequest.bind(null, radioValue)) :
processRequest(radioValue);
}
2 - Do not use alert as it will block your UI. You can use jQuery UI's Dialog plugin or anything similar. Everytime a response is processed, you can check promiseQueue.state() to see if there are other requests to be processed or they all have been processed.
3 - You can pass a timeout configuration to $.ajax to allow a maximum time for the request to complete. Have a look at https://api.jquery.com/jQuery.ajax/

WCF Service methods + Synchronous calls from javascript

I have written a WCF service and am trying to call the service methods in a script in my ASPX page.
Eg:
<script language="javascript" type="text/javascript">
<!--
function Test() {
**// The following call is an Async call.
tempuri.org.IService.GetData(1,OnRequestComplete, OnError, "");**
}
function OnRequestComplete(result, state) {
var textBox = $get("txtInput");
textBox.value = result;
}
function OnError(result) {
var textBox = $get("txtInput");
textBox.value = result;
}
//-->
</script>
What I want is to be able to call the service method "synchronously"
eg: var result = tempuri.org.IService.GetData(1);
Is this possible?
I believe there's no ability to do synchronous calls in Javascript - the AJAX libraries will always return while waiting for a remote response.
Can you explain why you want to do this?
Edit:
In answer, you should use this method:
In the onclick event handler for your form submit button: Make the webservice validation call, and immediately return false (so the form does not submit). It would be a good idea to display to the user a 'Validating' type message, so they know what is happening here.
If you get a valid response, then use document.form.submit(); to submit the form to the server.
If you get an invalid response, or a server error, then display to the user a message to that effect.
If you use regular AJAX you can make your call synchronous.
See: http://www.w3schools.com/Ajax/ajax_xmlhttprequest_send.asp
and scroll down to the part "Asynchronous - True or False?"
Here I use AJAX but sometimes it hangs
www.DomainGuarder.com

Requesting something via ajax - how to stop other requests until this one is done

I have a php script that outputs json data. For the purposes of testing, i've put sleep(2) at the start.
I have a html page that requests that data when you click a button, and does $('.dataarea').append(data.html)
(php script returns a json encoded array. data.html has the html that i want to put at the end of <div class="dataarea">...HERE</div>.
The trouble is, if i click the button too fast (ie. more than once within two seconds (due to the sleep(2) in the php script)), it requests the php file again.
how can i make it only do one request at a time?
i've tried this (edited down to show the important parts):
amibusy=false;
$('#next').click('get_next');
function get_next() {
if (amibusy) {
alert('requesting already');
}
else {
amibusy=true;
// do the request, then do the append()
amibusy=false;
}
}
but this doesn't seem to work. i've even tried replacing the amibusy=true|false, with set_busy(), and set_not_busy(). (and made a function am_i_busy() { return amibusy; })
but none of this seems to work. what am i missing?
If you're in jQuery the amibusy would be jQuery.active which contains a count of currently active AJAX requests, like this:
if(jQuery.active > 0) { //or $.active
alert('Request in Progress');
}
Keep in mind that in jQuery 1.4.3 this becomes jQuery.ajax.active.
Disable the button in the click event and enable it again when the request is finished. Note that the request is asynchronous (i.e. "send request" returns immediately), so you must register a function that is called when the answer comes in.
In jQuery, see the load() function and the success method plus the various AJAX events which you can tap into with ajax().
I'm wondering about your "do request" logic. Whenever I've done calls like this they've always been asynchronous meaning I fire the request off and then when the response comes another function handles that. In this case it would finish going through that function after setting the callback handler and set your value of amibusy back to false again before the request actually comes back. You'd need to set that variable in the handler for your post callback.
Could you use the async variable?
http://api.jquery.com/jQuery.ajax/
asyncBoolean Default: true
By default, all requests are sent
asynchronous (i.e. this is set to true
by default). If you need synchronous
requests, set this option to false.
Cross-domain requests and dataType:
"jsonp" requests do not support
synchronous operation. Note that
synchronous requests may temporarily
lock the browser, disabling any
actions while the request is active.

Categories

Resources