I have been working on creating a function to manage my AJAX post requests. While I have successfully sent the data, I am encountering difficulties with receiving the response.
The function in question is named ajaxPost(paramArray, target)
. It takes parameters and forms a string to send to the specified target
.
I suspect that the problem lies within ajaxReq.onreadystatechange
, as it seems to be skipping over this portion and terminating the script prematurely.
Here is the script for reference:
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 function performs the necessary actions. Below is an example of another function that utilizes the above one:
function submitPost(form){
var title = form.title.value;
var text = form.textBody.value;
var name = form.nameOfPoster.value;
var paramArray = {};
paramArray['title'] = title;
paramArray['text'] = text;
paramArray['name'] = name;
if (ajaxPost(paramArray, 'post.php')){
location.reload(true);
}
}
The parameters are passed to ajaxPost()
. If a response is received, the page reloads.
It appears that there might be a delay in retrieving the data mentioned earlier. I am exploring JavaScript without using jQuery, so any suggestions or tips are welcome.
Thank you! Feel free to provide additional advice if you have any.