Some code that i don't understand of the ajax - ajax

The variable xmlhttp=new XMLHttpRequest() is initialed. the following code :
function makerequest(serverPage,objID){
var obj=document.getElementById(objID);
xmlhttp.open("GET",serverPage);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status ==200){
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
i am sorry i am a new learner of ajax, in the if condition, why it add xmlhttp.readyState == 4. at the function's end there is using xmlhttp.send(null); could i delete them. thank you.

Well, you want to send the ajax request that you generate, so since you're using get, null is an acceptable argument. If you use post, you should pass the querystring in the send method. More here.
If you delete the readyState condition then you could end up with the ajax returning nothing since the page would not yet be ready. See more here.
EDIT: Sample argument for POST send method:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");

Related

AJAX response returns current page

I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s

304 not modified, Ajax is not working?

<script>
var xmlHttp =new XMLHttpRequest();
var url= "summary.txt";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var myArr = JSON.parse(xmlHttp.responseText);
myFunction(myArr);
}
xmlHttp.open("GET", url , true);
xmlHttp.send();
} function myFunction(arr)
var output="";
var i;
for(i=0;i<arr.length;i++){
output+='<p>'+arr[i].title+arr[i].image+arr[i].price+'</p>';
}
document.getElementById("proTab").innerHTML = output;
}
</script>
I stored all both the HTML and JSON in the htdocs folder, did xampp start and made sure Apache and mysql were running on the control panel. I then typed the link to the html using the "localhost/" to get to the html but the page was blank. Sorry for all the details.
Console says 304 Not modified. What should I do?
My guess is that you are using IE, which caches AJAX GET requests aggressively. I would suggest changing to using POST for the AJAX request.
Another alternative if you must use GET requests. You can add a unique querystring value to each GET request like this:
var url = 'summary.txt' + '?' + Math.random()*Math.random();
I used this for jQuery AJAX:
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
I think you can find how to use this for JS without jQuery. So the idea is to clear cache before sending the request, because server responds that nothing changed and sends 304 NOT MODIFIED instead of 200 OK. Namely, your summary.txt hasn't changed (not modified), so that's what server telling you.

Variable code in AJAX coding

i found a code fore an ajax tutorial,and am not familiar with some part of the code there
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "pay.php", true);
ajaxRequest.send(null);
can someone please tell me what the above code means,are there any variables,etc?
I am aware that pay.php is the php file it reffers to,but what does the first three line of coding mean?
The XMLHttpRequest object has a property called readyState. This is where the status of your server's response is stored. The response can be processing, downloading or completed. Each time the readyState changes then our onreadystatechange function executes.
When the property readyState is 4 that means the response is complete and you can get your data.
The function refers to a textbox named time,in a form named myform"The value is taken from the code in pay.php file.

Cakephp - Proper way to return AJAX Success response?

I have been using the trick below to return success response with AJAX:
//In controller
echo 'success';
//In Javascript
if(response == 'success'){
//redirect
window.location.href = '/users/profile/';
}
It works fine on localhost. But in web server, I got the error below everytime I want to redirect the page after success:
Cannot modify header information - headers already sent by (output started at ...
So yeah, I know it is caused by the echo before redirecting.
So, Is there proper way to return the success response? No need to be a message, just true or false is enough.
[EDIT]
By using exit('success'), it works fine, but is this the best way?
Thanks.
It is better to redirect from javascript.
//In controller
echo 'success'; exit;
//In Javascript
if(response == 'success'){
window.location = 'your-controller-action';
}
EDIT
You may have space before/after php Opening/Closing tags in controller and models. Remove all the closing tags from all controllers and models and any whitespace before opening tags. Then check the result.

AJAX POST and PHP

I have a AJAX script which sends a POST request to PHP with some values. When I try to retrieve the values in PHP, am not able to get anything.
The AJAX script is
xmlhttp.open("POST","handle_data.php",true);
xmlhttp.setRequestHeader("Content-type","text/plain");
var cmdStr="cmd1=Commanda&cmd2=Command2";
xmlhttp.send(cmdStr);
alert(xmlhttp.responseText);
The PHP script is
<?php
echo $_POST['cmd1'];
?>
The output is just a plain empty alert box. Is there any mistake in the code?
xmlhttp.onreadystatechange = function()
{
if(this.readyState == 4 && this.status == 200)
{
if(this.responseText != null)
{
alert(this.responseText);
}
};
}
You need to wait for the data to be received, use the onreadystatechange to delegate a callback.
http://www.w3.org/TR/XMLHttpRequest/
I don't know if it is required, but might you want to use application/x-www-form-urlencoded as the request header.
You should not be grabbing the response immediately after sending the request. The reason is because the A in Ajax stands for Asynchronous, and that means the browser won't wait for your XMLHttpRequest to complete before it continues to execute your JavaScript code.
Instead you should write a callback that only runs when the response is fully ready. Just before your xmlhttp.send(cmdStr); call, add this:
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
// This line is from your example's alert output
alert(this.responseText);
}
}

Resources