I am trying to make a function to handle my AJAX post stuffs.
I was able to get it to send the data, but am having issue receiving data back from the request.
Essentially, I have a function called ajaxPost(paramArray, target), what this does is it accepts the parameters and puts them into a string to submit to the target.
I think the issue comes from ajaxReq.onreadystatechange, I think it is skipping over that and ending the script.
I do not know if I am properly explaining what I mean, here is the script:
function ajaxPost(paramArray, target){
var param = '';
var key;
for (key in paramArray){
param = param + key + '=' + paramArray[key] + '&';
}
param = param.substring(0, param.length - 1);
var ajaxReq = new XMLHttpRequest();
ajaxReq.onreadystatechange = function(){
if(ajaxReq.readyState == 4 && ajaxReq.status == 200){
return ajaxReq.responseText;
document.write('Test?');
}
}
ajaxReq.open('POST', target, true);
ajaxReq.setRequestHeader('Content-type', "application/x-www-form-urlencoded");
ajaxReq.send(param);
}
This is the function that ‘does the work’, and here is an example of a function that calls the above function:
function submitPost(form){
var title = form.title.value;
var text = form.textBody.value;
var name = form.nameOfPoster.value;
var paramArray = new Array();
paramArray['title'] = title;
paramArray['text'] = text;
paramArray['name'] = name;
if (ajaxPost(paramArray, 'post.php')){
location.reload(true);
}
}
This essentially sends the parameters to ajaxPost(), and if it returns something it reloads the page.
As I said, I think it is ignoring that one part referenced at the beginning of this post. I am just wondering if I can halt the function until that data is received.
Please do not tell me to use jQuery, I am experimenting with javascript 🙂
Thanks.
Please do include other tips if you have them.
AJAX is asynchronouse. The way you are trying to use it will not work as
ajaxReq.onreadystatechangefunction will be executed after request is done. At the same time, script execution will not stop. So, this:will be executed before
ajaxReq.onreadystatechangeWhat you should do, is to pass a callback to your function:
and than: