I am trying to do something very simple, a user clicks a link and a mini-form with a file upload input appears somewhere below it.
However, my ajax code is not cooperating. Instead, it loads the entire current (i think) page. I had this issue again some time ago and i managed to fix it, however for the life of me i can't remember how i did it.
Now the really strange thing is that when i try it on my local computer it works fine, but on the actual web server it doesn't.
Code:
function ajaxRequest(targetUri, parameters, cbFunction){
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}else{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = cbFunction;
request.open("POST", targetUri, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(parameters);
}
function addImage(){
parameters = "action=ajaxRequest";
ajaxRequest("http://www.mysite.com/gallery/addImage.php", parameters, function(){
if((request.readyState == 4) && (request.status == 200)){
document.getElementById("formContainer").innerHTML = request.responseText;
}
});
}
And my PHP file:
function addImage(){
echo '
<div class="mainBlockBody">
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="galleryAction" value="addImage" />
<input type="file" name="upFile" />
<input type="submit" value="Submit" />
</form>
</div>
';
}
if($_POST['action'] == 'ajaxRequest'){
addImage();
}
Link & placeholder:
<a href="javascript:addImage()">Add Image</a>
<div id="formContainer"></div>
Any help is much appreciated!
EDIT:
I think i have narrowed down the problem to the... path. In this page http://bit.ly/dXrGY6 it all works fine, using a relative path. Replacing it with an absolute path like "http://www..." or "../test/....." makes it malfunction again. I am using absolute paths in another section of my site and it works fine: http://bit.ly/fCmmjy . I dont know why it doesn't work here...
I can't figure out what is wrong. Any ideas?
are you sure your php code is not spitting out anymore html? try adding a die
if($_POST['action'] == 'ajaxRequest'){
addImage();
die();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.