AJAX POST and PHP - ajax

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);
}
}

Related

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.

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.

Codeigniter controller detecting ajax file upload

I have set up my Codeigniter application so that I can upload files via Ajax. I followed this tutorial http://net.tutsplus.com/tutorials/javascript-ajax/how-to-upload-files-with-codeigniter-and-ajax/
My original form checked to see if an ajax request had been called, if not then I had the fallback CI form validation / error messages showing instead.
I checked this using - $this->input->is_ajax_request()
My code looked like this:
if($this->input->is_ajax_request()){
// process ajax form data
} else {
if($this->form_validation->run() == FALSE) {
$data['success'] = 0;
$data['errors'] = validation_errors();
} else {
$data['success'] = 1;
}
$this->load->view('form', $data);
}
After doing some investigation I discovered that I couldn't apply the same technique because it isn't actually an ajax request, therefore I am not sure how I can use this approach. If anyone can point me in the right direction that would be great. I don't like it being totally dependent on ajax, I like having a fallback option. I noticed in the comments that someone has set up a CSFR cookie in their ajaxfileupload.js but to be honest I'm not too hot with js so I wouldn't know where to begin. Thanks in advance.
In your AJAX request along with everything else you could post key/value:
ajax : 1
Then in your controller:
if( $this->input->post('ajax') == 1 ) {
// process ajax form data
}
else
{
// form validation
}
Hope this helps.

Validate $.getJSON before its being sent to the server in JQmobile

I'm trying to Validate my form before it's being sent to the server. I tried couple of J/S plugins for regular validation and none of them seem to work.
I tried looking for getJSON validation method with jquerymobile but haven't seen anything related. Is using $.getJSON the right approach?
Here is a fiddle http://jsfiddle.net/Kimbley/kMsXK/2/
Thanks :D
Code Here:
function mAddBusiness() {
$.getJSON("API.php", {
command: "addBusiness",
bsnName: $("#mBsnName").attr("value"),
bsnCity: $("#mBsnCity").attr("value"),
bsnAddress: $("#mBsnAddress").attr("value"),
bsnMenu: $("#mBsnMenu").attr("value"),
bsnLat: bsnLat,
bsnLong: bsnLong
},
function () {
$("#mBsnName").attr("value", "");
$("#mBsnCity").attr("value", "");
$("#mBsnAddress").attr("value", "");
$("#mBsnMenu").attr("value", "");
alert("Business was added successfully ");
}
);
}
Inside your mAddBusiness() function you can just do your validation before sending the AJAX request. Something like:
function mAddBusiness() {
if ($("#mBsnName").val() !== '') {
$.getJSON("API.php", {
command: "addBusiness",
bsnName: $("#mBsnName").val(),
bsnCity: $("#mBsnCity").val(),
bsnAddress: $("#mBsnAddress").val(),
bsnMenu: $("#mBsnMenu").val(),
bsnLat: bsnLat,
bsnLong: bsnLong
},
function () {
$("#mBsnName").val("");
$("#mBsnCity").val("");
$("#mBsnAddress").val("");
$("#mBsnMenu").val("");
alert("Business was added successfully ");
}
);
} else {
alert('Please enter a business name.');
}
}
Note that you will have to add the data-ajax="false" attribute to the <form> tag in question so that jQuery Mobile does not attempt to submit the form itself.
Also, note that $('input').attr('value') will not return the current value of an input, it will return the initial value before the user had a chance to input anything. To get the current value of a form input, use .val(): http://api.jquery.com/val

Some code that i don't understand of the 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");

Resources