'ajax returns page source, not the message
All the answers I saw here or elsewhere on Google were with jquery. This is not jquery.
- I send an ajax string to a php file.
- The php, among other things, formulates a message string which I echo back to the client.
- The returned string is put up in the client as an alert.
- The form is then reset.
The problem is that when I do this it puts up as much of the page source that the alert can handle. If I open developer tools to look at the return, it puts the message up correctly, not the page source. Here is the return snippet in my ajax:
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
document.getElementById("thisForm").reset();
}
}
The php file does a simple echo of a text string.
What is it about developer tools that makes this run correctly and why doesn't it print out the message in the alert when developer tools is not there?
When I run the backend php by itself, with or without developer tools, it displays the message properly.
Does anyone have any ideas?
More information: I tried to replace the alert and reset with a display.innerHTML=ajaxRequest.responseText where display is a javascript object formed from getElementById("ajaxReturn") of a "div id="ajaxReturn". It didn't work. When I tried developer tools, it showed the network response text as being the page source.
I also added && this.status == 200 to the if statement. No change.
Solution 1:[1]
The problem is solved. I am not deleting this because it might help some other poster who runs into the same problem. I launched the AJAX with an onclick to a javascript function called ajaxFunction(). The html entity containing the onclick had an href="#" in it. Removing that href solved the problem.
Solution 2:[2]
I had the exact same issue and my cause was related to having an extra slash in my URL.
Lets say my URL was: https://example.com/index.php
I had a wrong link as follows: https://example.com/index.php/
On both instances my server loads the page,
But the Ajax shows the page source as response for: https://example.com/index.php/
But works fine for: https://example.com/index.php
The ajax is essentially posting to index.php/ajaxpage.php which then responds with whats on index.php instead of whats on ajaxpage.php
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sheldon Glickler |
Solution 2 | Willie Theron |