javascript ajax on submit - javascript

i am using a google map api to get location. i have used the below function onchange of address field. it is working properly onchange. i have used same function on submit in the same form to checking the function once again while submitting using a onsubmit attribute. but while submitting i cant able to get answer from this ajax because of the that return by using this return true the form submit with pout getting answer.
please any one find a solution for this
function validatePlaceForm(){
var frm = document.frmOncampus;
var oncampusAddress = frm.oncampusAddress.value;
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//document.getElementById("my_div").innerHTML=''
var result =xmlhttp.responseText;
//alert(result);
var both =result.split("|");
frm.oncampusLatitude.value=both[0];
frm.oncampusLongtitude.value=both[1];
}
}
var url='latlog.php?address='+oncampusAddress;
xmlhttp.open("GET",url,true);
xmlhttp.send();
return true;
}

Unfortunately this will never work because the way you're using the XHR there is asynchronous:
xmlhttp.open("GET",url,true); // true means asynchronous
As the call is asynchronous the result of the function will have no result on the running of the Ajax request.
If you want to continue with using this function just change this last parameter to false, i.e.
xmlhttp.open("GET", url, false); // will now be synchronous
You also won't need a onreadystatechange handler now. Bear in mind that this will obviously make the XHR call synchronous on your onchange event too; maybe customise the function to accept a flag for is_synchronous or something.
You might also want to consider adding a timestamp onto your requests so that the browser does not cache the response.

Change the return value from true to false and call this function like this:
onsubmit="return validatePlaceForm();"
This should do the trick.

Check for the response coming from AJAX. If response is blank then return false, otherwise return true.

Related

AJAX mysql command not immediately executed?

So I have some code, which checks for whether a one time use discount code exists, and if so, it applies it and then marks it as used in the database. The problem is, it ends up being useable more than once if you spam click it, and then some time maybe 15-20 seconds later it stops being useable.
The relevant javascript component:
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
discountAmount += parseFloat(xmlhttp.responseText);
modifyCartOrder();
}
}
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
xmlhttp.send();
This is processed over in the php file, and when a match is found we echo that amount and then delete the entry
$mysqli->query("DELETE FROM discounts_available WHERE `index`=$index");
The php file is indeed doing what its supposed to. When you click apply code, it is immediately deleted from the database. The problem is, even with the code no longer in the db, you can still apply the code over and over for some amount of time before the js file finally realises there is no entry in the db. Why is this?
You should first check if it exists in DB then only you should proceed with request, it should be very first statement.
If it does not exists you can send response saying code already applied.
You most likely need to lock the table ASAP so no other instances can modify the table concurrently.
http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html
I did not get your problem, exactly I am assuming lost of things, so..
//this is triggered on some click, right?
//TODO:- check if button is disabled? you can have some js variable or check button attribute disbled
//TODO:-if its not disaled->{so first disable the button when it is clicked } else do nothing
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
discountAmount += parseFloat(xmlhttp.responseText);
// if succefull keep button disabled
// else renable it, so that it can be clicked again.
modifyCartOrder();
}
}
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
xmlhttp.send();
thers's no syntax problem here in your code its logical,
ajax call is asynchronous call, it does not happen in sequence
1) You clicked
2) Request Sent
3) Request Processed
4) JS is informed : your modifyCartOrder function executed
what I am trying to say here is that, there is no 3 immediately after 2, 3 will take time to start, js has no control over it, whenever php is done it will reply there's no guarantee. so you can repeat 1 again and again, and 2 will keep repeating... and so 3 will...
I hope I understood your problem, and you understood what I am trying to say :)
Problem is : You are sending asynchronous ajax calls from following code :
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
Solution : as defined , for opening an ajax call , method is :
xmlhttp.open(method,url,async)
So, You have to modify above line as:
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,false);

Function delivers value, before ajax request changed it

I am running an ajax request to retrieve a value of either 0,1, or 2 based upon some mysql code in the "check_answer_status.php" file. For test purposes, I have included the alert to check whether the general ajax and mysql request works fine and it does, hence the value contained within "Questiions.answerStatus" at the time of the alert is correct. However, my problem is that the function "checkAnswerStatus" has already executed and did not change the inital value of "answerStatus" (which I set to 50 for test purposes).
Context: sometime later in the code I want to execute code dependent on the value of the variable "answerStatus".
I believe I need to somehow include something like an "oncomplete" or something comparable, but I do not know how to do that. Can anyone help me out? Many thanks!
var = Questions = {
answerStatus:50,
checkAnswerStatus : function(question){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
test = xmlhttp.responseText;
Questions.answerStatus = test;
alert(Questions.answerStatus);
}
}
xmlhttp.open("POST","../../include/check_answer_status.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+question);
},
The request you make is asynchronus (the third parameter of the xmlhttp.open function). If you changed it to:
xmlhttp.open("POST","../../include/check_answer_status.php",false);
it should work.
Another options is to pass a callback to your checkAnswerStatus function, and call the callback when the request finishes. Example:
checkAnswerStatus : function(question, callback){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
test = xmlhttp.responseText;
Questions.answerStatus = test;
callback(Questions.answerStatus); //call the function
}
}
xmlhttp.open("POST","../../include/check_answer_status.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+question);
}
and then you will call the function like this:
Questions.checkAnswerStatus("bla bla", function(answerStatus) {
alert(answerStatus);
});
in addition to Nemos answer I would recommend you read following resources from MDN:
More technical API documentation for a brief overview of all the possibilities:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
More real life usecases:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Hope this helps

Show Save-As window from JSP

I need to write a String in a file on the client side, however as the Internet protocol does not allow that for Security concerns, this is the workaround I did: I have an AJAX request which invokes a JSP that queries a Database to get a String. I need to show the users a "Save-As" dialog and write this String to the local path they specify.
My JavaScript function:
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
alert("result obtained");
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
In the JSP, I have something like this:
response.setHeader("Content-Disposition", "attachment;filename=report.xml");
out.println(stringObtainedFromDatabase);
I do not see a Save As dialog while I get the alert saying result obtained. This is the first time I am doing this, could you please tell me if I am doing something wrong?
But, is there a way in JavaScript to show users a Save-As dialog and write the content of "div" tag in a file on the Client system?
Use a regular HTTP request, not an AJAX (XMLHttpRequest) one.
function openReport(id)
{
var url = "../reports/reportsHandler.jsp?id=" + id;
window.location = url;
}
This will send an HTTP GET, not a POST, though it looks like GET is the correct HTTP method to use here anyway, since you're retrieving data and not actually altering anything on the server.

why is .innerHTML changed before xmlhttp.open() and .send()?

I am learning to use xmlhttprequest/AJAX. In this sample code from w3schools, I do not understand why this line:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
precedes this:
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
The way I'm thinking about it, you should send the GET request before you have any responseText to do anything with. Where is the error in my understanding?
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
The line in question is inside of xmlhttp.onreadystatechange, which is a function. Note how it is used:
xmlhttp.onreadystatechange = function ()
{
...
}
In this case, it is a callback function - it is called when the ajax request (aka xmlhttp.send()) completes.
You might want to brush up on your javascript before you dive into ajax.
You have just discovered the asynchronous part of the AJAX word :-)
Even though the .send() method is called later, the innerHTML call is made earlier.
How come that works?!
Because an AJAX call is asynchronous. Thus, it's not like making a database call in PHP: you make your call, waits for the result, and work with it. Nope.
In JS, for AJAX calls, you define a callback function. It is a function that will be called once the response has arrived.
For the XMLHttpRequest object, it is the onreadystatechange event that is fired when the response comes back. If you register a function in this event, this function will be called when the response will come back.
P.S.: the function in onreadystatechange won't exactly be fired once the response comes back, but this was for the sake of the explanation. To know when this event is fired, take a look at the different states.
It doesn't. Consider this code:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
It doesn't execute the code inside the function, it only creates the function and assigns it to a property. The function will be executes by the XMLHTTP object when the state changes, and it will catch the state change that means that the response has arrived.

XMLHttpRequest status 0 on second load

I am experiencing an interesting issue when I am trying to load some data in .txt format from the same domain using XMLHttpRequest.
I am trying to load the data, parse it and then store it in localStorage
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var temp;
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
temp = xmlhttp.responseText;
}else{
alert("readyState: " + xmlhttp.readyState + "status: " + xmlhttp.status);
}
}
xmlhttp.open("GET","data/somedata.txt", false);
xmlhttp.send();
This code only works if I clean the history and cache; however, on second click of the same link, I would received "Readystate: 4, status 0" for some reason.
Does this has anything to do with localStorage?
if (!localStorage.somedata || localStorage.somedata.count(':') !== somedata.count(':')) {
localStorage.somedata = temp;
}
window.somedata = JSON.parse(localStorage.somedata);
There are two causes of status code of zero.
Making calls from the file protocol.
The page is refreshing/navigating away as the request is being made.
In your case I would assume it is #2. If you are using a button or a link to make the Ajax call, make sure to cancel the click action with either preventDefault or return false.
Sounds like a caching issue. Try either switching to a POST method, or appending a timestamp to the GET request querystring and see if that prevents the caching.
xmlhttp.open("POST", "data/somedata.txt", false);
or:
xmlhttp.open("GET", "data/somedata.txt?" + new Date().valueOf(), false);
Edit: If those don't work, modify your server configuration to send appropriate response headers for that file or type to not cache the response. Ie: Cache-Control: no-cache
Try xmlhttp.abort() before opening a new request.
It's a long shot but worth the try.

Categories

Resources