Form submit using Ajax - javascript

I need to submit the a form using Ajax with POST method.The code is as follows,
function persistPage(divID,url,method){
var scriptId = "inlineScript_" + divID;
var xmlRequest = getXMLHttpRequest();
xmlRequest.open("POST",url,true);
xmlRequest.onreadystatechange = function(){
alert(xmlRequest.readyState + " :" + xmlRequest.status);
if (xmlRequest.readyState ==4 || xmlRequest.status == 200)
document.getElementById(divID).innerHTML=xmlRequest.responseText;
};
xmlRequest.open("POST", url, false);
alert(xmlRequest.readyState);
xmlRequest.send(null);
}
but the form is not submitting(request is not executed or no data posted).How to submit the form using Ajax.
Thanks

There's a few reasons why your code doesn't work. Allow me to break it down and go over the issues one by one. I'll start of with the last (but biggest) problem:
xmlRequest.send(null);
My guess is, you've based your code on a GET example, where the send method is called with null, or even undefined as a parameter (xhr.send()). This is because the url contains the data in a GET request (.php?param1=val1&param2=val2...). When using post, you're going to have to pass the data to the send method.
But Let's not get ahead of ourselves:
function persistPage(divID,url,method)
{
var scriptId = "inlineScript_" + divID;
var xmlRequest = getXMLHttpRequest();//be advised, older IE's don't support this
xmlRequest.open("POST",url,true);
//Set additional headers:
xmlRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');//marks ajax request
xmlRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencode');//sending form
The first of the two headers is not always a necessity, but it's better to be safe than sorry, IMO. Now, onward:
xmlRequest.onreadystatechange = function()
{
alert(xmlRequest.readyState + " :" + xmlRequest.status);
if (xmlRequest.readyState ==4 || xmlRequest.status == 200)
document.getElementById(divID).innerHTML=xmlRequest.responseText;
};
This code has a number of issues. You're assigning a method to an object, so there's no need to refer to your object using xmlRequest, though technically valid here, this will break once you move the callback function outside the persistPage function. The xmlRequest variable is local to the function's scope, and cannot be accessed outside it. Besides, as I said before, it's a method: this points to the object directlyYour if statement is a bit weird, too: the readystate must be 4, and status == 200, not or. So:
xmlRequest.onreadystatechange = function()
{
alert(this.readyState + " :" + this.status);
if (this.readyState === 4 && this.status === 200)
{
document.getElementById(divID).innerHTML=this.responseText;
}
};
xmlRequest.open("POST", url, false);
alert(xmlRequest.readyState);//pointless --> ajax is async, so it will alert 0, I think
xmlRequest.send(data);//<-- data goes here
}
How you fill the data is up to you, but make sure the format matches the header: in this case 'content type','x-www-form-urlencode'. Here's a full example of just such a request, it's not exactly a world beater, since I was in the process of ditching jQ in favour of pure JS at the time, but it's serviceable and you might pick up a thing or two. Especially take a closer look at function ajax() definition. In it you'll see a X-browser way to create an xhr-object, and there's a function in there to stringify forms, too
POINTLESS UPDATE:
Just for completeness sake, I'll add a full example:
function getXhr()
{
try
{
return XMLHttpRequest();
}
catch (error)
{
try
{
return new ActiveXObject('Msxml2.XMLHTTP');
}
catch(error)
{
try
{
return new ActiveXObject('Microsoft.XMLHTTP');
}
catch(error)
{
//throw new Error('no Ajax support?');
alert('You have a hopelessly outdated browser');
location.href = 'http://www.mozilla.org/en-US/firefox/';
}
}
}
}
function formalizeObject(form)
{//we'll use this to create our send-data
recursion = recursion || false;
if (typeof form !== 'object')
{
throw new Error('no object provided');
}
var ret = '';
form = form.elements || form;//double check for elements node-list
for (var i=0;i<form.length;i++)
{
if (form[i].type === 'checkbox' || form[i].type === 'radio')
{
if (form[i].checked)
{
ret += (ret.length ? '&' : '') + form[i].name + '=' + form[i].value;
}
continue;
}
ret += (ret.length ? '&' : '') + form[i].name +'='+ form[i].value;
}
return encodeURI(ret);
}
function persistPage(divID,url,method)
{
var scriptId = "inlineScript_" + divID;
var xmlRequest = getXhr();
xmlRequest.open("POST",url,true);
xmlRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencode');
xmlRequest.onreadystatechange = function()
{
alert(this.readyState + " :" + this.status);
if (this.readyState === 4 && this.status === 200)
{
document.getElementById(divID).innerHTML=this.responseText;
}
};
xmlRequest.open("POST", url, false);
alert(xmlRequest.readyState);
xmlRequest.send(formalizeObject(document.getElementById('formId').elements));
}
Just for fun: this code, untested, but should work allright. Though, on each request the persistPage will create a new function object and assign it to the onreadystate event of xmlRequest. You could write this code so that you'll only need to create 1 function. I'm not going into my beloved closures right now (I think you have enough on your plate with this), but it's important to know that functions are objects, and have properties, just like everything else:Replace:
xmlRequest.onreadystatechange = function()
{
alert(this.readyState + " :" + this.status);
if (this.readyState === 4 && this.status === 200)
{
document.getElementById(divID).innerHTML=this.responseText;
}
};
With this:
//inside persistPage function:
xmlRequest.onreadystatechange = formSubmitSuccess;
formSubmitSuccess.divID = divID;//<== assign property to function
//global scope
function formSubmitSuccess()
{
if (this.readyState === 4 && this.status === 200)
{
console.log(this.responseText);
document.getElementById(formSubmitSuccess.divID).innerHTML = this.responseText;
//^^ uses property, set in persistPAge function
}
}
Don't use this though, as async calls could still be running while you're reassigning the property, causing mayhem. If the id is always going to be the same, you can, though (but closures would be even better, then).
Ok, I'll leave it at that

This code can let you understand. The function SendRequest send the request and build the xmlRequest through the GetXMLHttpRequest function
function SendRequest() {
var xmlRequest = GetXMLHttpRequest(),
if(xmlRequest) {
xmlRequest.open("POST", '/urlToPost', true)
xmlRequest.setRequestHeader("connection", "close");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.status == 200) {
// Success
}
else {
// Some errors occured
}
};
xmlRequest.send(null);
}
}
function GetXMLHttpRequest() {
if (navigator.userAgent.indexOf("MSIE") != (-1)) {
var theClass = "Msxml2.XMLHTTP";
if (navigator.appVersion.indexOf("MSIE 5.5") != (-1)) {
theClass = "Microsoft.XMLHTTP";
}
try {
objectXMLHTTP = new ActivexObject(theClass);
return objectXMLHTTP;
}
catch (e) {
alert("Errore: the Activex will not be executed!");
}
}
else if (navigator.userAgent.indexOf("Mozilla") != (-1)) {
objectXMLHTTP = new XMLHttpRequest();
return objectXMLHTTP;
}
else {
alert("!Browser not supported!");
}
}

take a look at this page. In this line: req.send(postData); post data is an array with values that should be posted to server. You have null there. so nothing is posted. You just call request and send no data. In your case you must collect all values from your form, as XMLHTTPRequest is not something that can simply submit form. You must pass all values with JS:
var postData = {};
postData.value1 = document.getElementById("value1id").value;
...
xmlRequest.send(postData);
Where value1 will be available on server like $_POST['value'] (in PHP)
Also there might be a problem with URL or how you are calling persistPage. persistPage code looks ok to me, but maybe I'm missing something. Also you can take a look if you have no errors in console. Press F12 in any browser and find console tab. In FF you may need to install Firebug extention. Also there you will have Network tab with all requests. Open Firebug/Web Inspector(Chrome)/Developer Toolbar(IE) and check if new request is registered in its network tab after you call persistPage.

I found you've invoked the
xmlRequest.open()
method twice, one with async param as true and the other as false. What exactly do you intend to do?
xmlRequest.open("POST", url, true);
...
xmlRequest.open("POST", url, false);
If you want to send asynchronous request, pls pass the param as true.
And also, to use 'POST' method, you'd better send the request header as suggested by Elias,
xmlRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencode');
Otherwise, you may still get unexpected issues.
If you want a synchronous request, actually you may handle the response directly right after you send the request, just like:
xmlRequest.open("POST", url, false);
xmlRequest.send(postData);
// handle response here
document.getElementById(scriptId).innerHTML = xmlRequest.responseText;
Hope this helps.

Related

Why if and else both condition executing at same time in JavaScript | If and Else Condition

Why If and else condition work both in JavaScript. if (xhr.readyState == 4 && xhr.status == 200)
I am working on php MVC project.
I created a profile edit page in background JavaScript If and Else both code executing. profile edit Successfully but else code work and it's show error "Sorry, this content isn't available right now".
why this else condition work??
same This code work in login and registration page.
save in local file and run than it work :-
online code
Code
document.querySelector("#Profile_Save").addEventListener("click", () => {
if (document.querySelector("#Profile_Edit_Email").value.match(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/)) {
document.querySelector("#Profile_Edit_Msg").classList.remove("active_success");
document.querySelector("#Profile_Edit_Msg").classList.remove("active_denger");
document.querySelector("#Profile_Save").innerHTML = "Loading...";
document.querySelector("#Profile_Save").classList.remove("active");
document.querySelector("#Profile_Save").disabled = true;
document.querySelector("#Profile_Edit_F_Name").disabled = true;
document.querySelector("#Profile_Edit_L_Name").disabled = true;
document.querySelector("#Profile_Edit_Email").disabled = true;
var f_name = document.querySelector("#Profile_Edit_F_Name").value,
l_name = document.querySelector("#Profile_Edit_L_Name").value,
email = document.querySelector("#Profile_Edit_Email").value;
var xhr = new XMLHttpRequest();
xhr.open("POST", "Api/ProfileEdit", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) { // this one if executing
var json = JSON.parse(xhr.responseText);
if (json.Status == "Ok") {
window.location.href = "Profile"; // it also work
} else {
document.querySelector("#Profile_Edit_Msg").classList.remove("active_success");
document.querySelector("#Profile_Edit_Msg").classList.add("active_denger");
document.querySelector("#Profile_Edit_Msg").innerHTML = json.Message;
}
} else { // this one else executing
document.querySelector("#Profile_Edit_Msg").classList.add("active_denger");
document.querySelector("#Profile_Edit_Msg").innerHTML = "Sorry, this content isn't available right now"; // this message show
}
}
xhr.send("F_Name=" + f_name + "&L_Name=" + l_name + "&Email=" + email);
document.querySelector("#Profile_Save").innerHTML = "Register";
document.querySelector("#Profile_Save").classList.add("active");
document.querySelector("#Profile_Save").disabled = false;
document.querySelector("#Profile_Edit_F_Name").disabled = false;
document.querySelector("#Profile_Edit_L_Name").disabled = false;
document.querySelector("#Profile_Edit_Email").disabled = false;
} else {
document.querySelector("#Profile_Edit_Msg").classList.add("active_denger");
document.querySelector("#Profile_Edit_Msg").innerHTML = "Invalid Email Address!";
}
});
return JSON
{"Status":"Ok","Message":"Profile Edit Successfully!"}
Output
open profile page and
error message:- "Sorry, this content isn't available right now"
help me!
Thank you!!
The readystatechange event fires multiple times.
Value State Description
0 UNSENT Client has been created. open() not called yet.
1 OPENED open() has been called.
2 HEADERS_RECEIVED send() has been called, and headers and status are available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.
Your
if (xhr.readyState == 4 && xhr.status == 200) {
branch will only be entered into at the end of a request, if the request was successful. But earlier, while the request is still ongoing, other state changes will occur, and the else branch will be entered into.
Instead, only do anything if the readyState is 4 - and, when it is 4, you can parse the response, or populate the #Profile_Edit_Msg to say there was a problem.
Other improvements:
Save the Profile_Edit_Msg in a variable instead of repetitively selecting it over and over again
Use strict equality, not sloppy equality
Use .textContent when assigning text to an element - only use .innerHTML when inserting HTML markup
JSON is a particular format of a string that can be deserialized into an object or other value. JSON.parse does not return JSON - JSON.parse is called with a JSON-formatted string and returns an object. Call your json variable something else.
denger looks misspelled - did you mean danger? (Typos are a common problem in programming - better to fix them earlier than later)
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
const profile = document.querySelector("#Profile_Edit_Msg");
if (xhr.status === 200) {
const result = JSON.parse(xhr.responseText);
if (result.Status === "Ok") {
window.location.href = "Profile";
} else {
profile.classList.remove("active_success");
profile.classList.add("active_denger");
profile.innerHTML = json.Message;
}
} else {
profile.classList.add("active_denger");
profile.textContent = "Sorry, this content isn't available right now";
}
};
You could also consider using the fetch API instead of XMLHttpRequest - fetch is a bit nicer to work with and has been supported in all modern browsers for ages.

Return result from AJAX

I want to return response data when XMLHttpRequest transaction completes successfully.
upon calling my function trashAnswer() to a variable I expect to assign the value returned to the variable and do something with it like below:
I can see resData is always undefined when i try to access data from it.
Please how can I solve this?
var resData = trashAnswer({answerid:58,answererid:65,questionid:458});
This is the code:
//This function will trash answer object
function trashAnswer(param){
if (typeof param !== 'object' || param == null ) {
throw "trashAnswer(): Strictly expect valid object.";
}
var param = $.extend({answerid:0,answererid:0},param),
fd = new FormData();
fd.append('answerData',JSON.stringify(param));
fd.append('trash-answer',true);
var req = AJAX_REQEUST_OB();
req.open(bigPipe.formMethod.a,ajax.ac,true);
req.onload = function(){
if (req.readyState === req.DONE && req.status === 200) {
//ParseJSON is a custom function to check if response is a valid JSON...if its valid then then function will return response Data else return false
var Data = ParseJSON(req.responseText);
//process data...
var EvalData = !Data ? function(){
throw "Invalid JSON";
}:function(Data){
//do something...
return Data;
};
//call EvalData ****method
EvalData(Data);
}
}
//send request.
req.send(fd);
}
This is an asynchronous call. When you do trashAnswer({...}); you are triggering the request and your code continues to execute. At some point in the future your request may work. Here the "may" part is important: your request may fail for several reasons, but you are only checking the HTTP status 200, that is an "OK" response).
An easy solution:
var resData;
trashAnswer({answerid:58,answererid:65,questionid:458});
//This function will trash answer object
function trashAnswer(param){
// ...
req.onload = function(){
if (req.readyState === req.DONE && req.status === 200) {
// ...
// in your "//do something...":
resData = // your result here. If you do not have a local variable,
// it will change the global one (not recommended, see comment below)
}
}
// ...
}
Your solution is even better if you avoid using a global variable (See here why). But I believe this is a good starting point for you to understand how async calls work.
You can also use promises (including the async/await syntax). A good start reading about how this works is https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

Simultaneous ajax calls

I'm trying to make 2 (or more) ajax calls simultaneously. I don't want to use jQuery, only pure JavaScript.
Most of the time, it works. data1 will output data from sample.com/ajax1 and data2 will output data from sample.com/ajax2, but sometimes (1 from 10) the second AJAX call will display result from the first one.
Why is this happening? Both AJAX requests are requesting data from the same domain, but from different URLs. Is there any way how to prevent this behavior?
Here is the script:
// First AJAX
var xmlhttp1;
// Second AJAX
var xmlhttp2;
if (window.XMLHttpRequest) {
xmlhttp1 = new XMLHttpRequest();
} else {
xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange = function() {
if (xmlhttp1.readyState == 4 && xmlhttp1.status == 200) {
data = JSON.parse(xmlhttp1.responseText);
console.log('data1: ' + data);
}
}
xmlhttp1.open("GET", "http://sample.com/ajax1", true);
xmlhttp1.send();
if (window.XMLHttpRequest) {
xmlhttp2 = new XMLHttpRequest();
} else {
xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
data = JSON.parse(xmlhttp2.responseText);
console.log('data2: ' + data);
}
}
xmlhttp2.open("GET", "http://sample.com/ajax2", true);
xmlhttp2.send();
First of all, I recomment wrapping your xmlHttpRequest generation/handling in a function, so you don't duplicate code that much.
The problem you have there is that the data variable is global, so both ajax callbacks are using the same variable. You can fix it using the var keyword in both calls.
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
var data = JSON.parse(xmlhttp2.responseText);
console.log('data2: ' + data);
}
}
Because you're not properly encapsulating data. The way you have it written, data is a global object, so it's available to be modified by either ajax call. Since ajax calls are asynchronous, this will lead to unpredictable values for data.
The problem is probably because you forgot to define data inside your function
anyway with this function you can create multiple requests and have more control over them..
var req={};
function ajax(a){
var i=Date.now()+((Math.random()*1000)>>0);
req[i]=new XMLHttpRequest;
req[i].i=i;
req[i].open('GET',a);
req[i].onload=LOG;
req[i].send();
}
function LOG(){
console.log(this.i,this.response);
delete req[this.i];//clear
}
window.onload=function(){
ajax('1.html');
ajax('2.html');
ajax('3.html');
}
uses xhr2... you need to modify the code to make it work with older browsers.

Is there a way to change a global variable on the document in the call back xmlHttpReq.onreadystatechange?

I am pretty new to the AJAX thing, but now I want to set some value to a global variable on the document based on status changed in the call back function xmlHttpReq.onreadystatechange, I used something like
function checkFile(fileUrl) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
if(self.xmlHttpReq == null){
alert("Your browser does not support XMLHTTPReq")
}
self.xmlHttpReq.open('HEAD', fileUrl, true);
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
if (self.xmlHttpReq.status == 200) {
window.rett = 1;
//alert(window.rett);
} else if (self.xmlHttpReq.status == 404) {
window.rett = 0;
//alert(window.rett);
}
}
}
self.xmlHttpReq.send();
}
and I use the checkFile in a jquery template like this:
<script id="resultTemplate" type="text/x-jquery-tmpl">
<li> ${checkFile(link)} <b> {{if window.rett == 1 }} ${link} {{/if}}</b> </li>
</script>
but when I access the window.rett in a Jquery template, it says undefined...
The reason I want to get the global value is that I want to generate different GUI based on the global value.
Maybe this is not a good practice of using global variable? Any suggestion is appreciated.
Most likely because by the time you tried accessing it, the AJAX request has not completed yet (has not reached state 4), thus your global hasn't been declared (or if it was, it still contains the value of the previous result)
I suggest you use your template from within the callback. That way, by the time your template checks for the value, the value is already there:
function yourAjaxFunction(arg1, arg2,...,callback){
//all AJAX setup codes here
if (self.xmlHttpReq.readyState === 4) {
if (self.xmlHttpReq.status === 200) {
//sending the callback a 1
callback(1);
} else if (self.xmlHttpReq.status === 404) {
//sending the callback a 1
callback(0);
}
}
//AJAX send codes
}
//how you should use it
yourAjaxFunction(arg1,arg2,...,function(rett){
//use rett here
//parse template here
});

Strange javascript behavior - multiple active XMLHttpRequests at once? Long running scripts?

I'm attempting to issue two concurrent AJAX requests.
The first call (/ajax_test1.php) takes a very long time to execute (5 seconds or so).
The second call (/ajax_test2.php) takes a very short time to execute.
The behavior I'm seeing is that I /ajax_test2.php returns and the handler gets called (updateTwo()) with the contents from /ajax_test2.php.
Then, 5 seconds later, /ajax_test1.php returns and the handler gets called (updateOne()) with the contents from /ajax_test2.php still!!!
Why is this happening?
Code is here: http://208.81.124.11/~consolibyte/tmp/ajax.html
This line:-
req = new XMLHttpRequest();
should be:-
var req = new XMLHttpRequest();
As AnthonyWJones stated, your javascript is declaring the second AJAX object which first overwrites the req variable (which is assumed global since there is no var) and you are also overwriting the ajax variable.
You should separate your code i.e:
function doOnChange()
{
var ajax1 = new AJAX('ajax_test1.php', 'one', updateOne);
var ajax2 = new AJAX('ajax_test2.php', 'two', updateTwo);
}
function AJAX(url, action, handler)
{
if (typeof XMLHttpRequest == "undefined")
{
XMLHttpRequest = function()
{
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
throw new Error( "This browser does not support XMLHttpRequest." )
};
}
url = url + '?action=' + action + '&rand=' + Math.random()
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4)
{
if (req.status == 200)
{
alert('' + handler.name + '("' + req.responseText + '") ')
handler(req.responseText)
}
}
}
req.open("GET", url, true);
req.send(null);
}
Regards
Gavin
Diodeus and Mike Robinson:
You guys didn't read my post fully. I know that one of the pages takes longer to execute than the other. That is the expected behavior of each page.
HOWEVER if you read my original post, the problem is that the callback for both pages ends up getting called with the HTML contents of the first page only.
AnthonyWJones and Gavin:
Thanks guys! That works like a charm! I guess I need to brush up on my Javascript!

Categories

Resources