ajax php javascript : error when using POST method - php

I searched on google, and there are so much question about this topic on stackoverflow. Such as 'data not being sent on post method', etc.
But seem not asnwer my question
The case is almost the same with other questions. These are the error msg:
Firefox (v21) :
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
Chrome (v27) :
Uncaught Error: InvalidStateError: DOM Exception 11
When the request is sent by GET, there is no error. And all GET data received well.
But when sent by POST + setRequestHeader, itu occurs error like above. When setRequestHeader removed, the error is gone. No error, but the POST data is not received. i print_r($_POST); then the array is empty
Question Updated. Here is the caller:
goServer({
url : 'users/sign-in.php',
method : 'POST',
data : 'randomId=' + randomId + '&name=' + name + '&password=' + password,
done : function(response) {
alert(response);
},
fail : function(response) {
alert(response);
}
});
And here is the functions (sorry, long lines ):
function randomString() {
var str = new Date().getTime(),
str2 = Math.random();
str = str.toString();
str2 = str2.toString();
str2 = str2.substring(2,7);
str += str2;
return str;
}
function goServer(opts) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = requestComplete;
function requestComplete() {
if ( xhr.readyState === 4 ) {
if ( xhr.status === 200 ) {
opts.done(xhr.responseText);
} else {
opts.fail(xhr.responseText);
}
}
}
if ( !opts.method || opts.method === undefined ) {
opts.method = "GET";
}
if ( !opts.cache || opts.cache === undefined ) {
opts.cache = false;
}
if ( opts.cache === false ) {
opts.url += '?nocache=' + randomString();
} else {
opts.url += '?nocache=false';
}
if ( opts.method === "GET" ) {
if ( opts.data !== '' && opts.data !== undefined ) {
opts.url += '&' + opts.data;
}
opts.data = '';
} else {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
xhr.open(opts.method, opts.url, true);
xhr.send(opts.data);
}
Note, the data parameter (opts.data) is set to the url when it sent by GET. When sent by POST, the paramater is set to the xhr.send(opts.data);
Question : How to get the POST data correctly?
Thank you

Call xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); after you call xhr.open
Also opts.data should be a string containing key/value pairs. e.g. key=value&method=post

Related

XHR and php Progress bar, working on local, not on remote

More explanation here :
Im importing products to my DB, and everytime a product is imported I display the percent calculated earlier:
//Progress bar
set_time_limit(0);
ob_implicit_flush(true);
ob_end_flush();
sleep(1);
$p = ($i/$count_product)*100; //Progress
$response = array( 'success' => true , 'message' => $p . '% ','progress' => $p);
$i++;
echo json_encode($response);
On my local everything is working fine :
Every time php echo json_encode() I get on XHR a new state 3, and display the response.
Code below:
var xhr = new XMLHttpRequest();
xhr.previous_text = '';
$param = 'id='+$(this).find('input').val();
xhr.onerror = function() {console.log(xhr.responseText) };
xhr.onreadystatechange = function() {
//try{
console.log(xhr.readyState);
console.log(xhr);
console.log(new_response);
if (xhr.readyState == 4){
var new_response = xhr.responseText.substring(xhr.previous_text.length);
var result = JSON.parse( new_response );
if (result['message'] == '100' ) {
$('.progress_bar').html('<div><?=$this->translate->_("Imported succefully")?></div>');
$.when($('.full_screen_layer').fadeOut(2000)).done(function() {
location.reload();
});
}else{
$('.progress_bar').html('<div style="color:red">'+result['message']+'</div>');
setTimeout(function(){
$.when($('.full_screen_layer').fadeOut(2000)).done(function() {
location.reload();
});
}, 2000);
// alert('<?=$this->translate->_("Please try again")?>');
}
}
else if (xhr.readyState > 2){
var new_response = xhr.responseText.substring(xhr.previous_text.length);
var result = JSON.parse( new_response );
if (result['success'] && result['end'] == undefined) {
$('.progress_bar').html('<div>'+result['message']+'</div>');
xhr.previous_text = xhr.responseText;
}else{
$('.progress_bar').html('<div style="color:red">'+result['message']+'</div>');
}
}
//}
// catch (e){
// alert("[XHR STATECHANGE] Exception: " + e);
// }
};
xhr.open("POST", action, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send($param);
But I'm trying to understand why it's not working on the server ( XHR state 3 is fired only once, at the end of the request ( so the json is malformed )
Here are the headers:
This just break my mind, if someone have an idea, even a bad one xD
(Btw there is a proxy on the server : VIA:1.1 Alproxy ) it could stop the response untill it end and then send it alltogether ?

http.responseText empty

I have a problem with my http.responseText (is always empty). I post my code:
function bCheckName ()
{
// It checks if the browser can allow a http request
if ( window.XMLHttpRequest )
{
xhttp = new XMLHttpRequest();
}
else
{
// for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// It takes the name from the form
var firstName = document.getElementById("firstName").value;
var datastring = "firstName=" + firstName;
var datastring_escaped = encodeURIComponent ( datastring );
// It opens the request to thye server
xhttp.open ( "POST", "../form/formValidation.php", true );
// It sets the header
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// It sends the data to the server
xhttp.send( datastring_escaped );
// It takes the responde from the server
xhttp.onreadystatechange = function()
{
if ( xhttp.readyState == 4 && xhttp.status == 200 )
{
var string = xhttp.responseText.substr ( 0, 2 );
var response = xhttp.responseText.substr ( 5 );
if ( string == "OK")
{
document.getElementById("nameResponse").innerHTML = '<img src = "../img/pages/contact/true.png" alt = "correct answer" >';
document.getElementById("response").innerHTML = response;
}
else
{
document.getElementById("nameResponse").innerHTML = '<img src = "../img/pages/contact/error.png" alt = "wrong answer">';
document.getElementById("response").innerHTML = response;
}
}
}
return false;}
If I replace "xhttp.send( datastring_escaped );" with "xhttp.send( datastring );", everything will work as expected. How can I fix the problem. I post also the php code:
if ( isset( $_POST['firstName'] ))
{
echo( "OK - ".urldecode ( $_POST['firstName']) );
}
How can I solve the problem?
Thanks in advance!!!
Francesco
encodeURIComponent is only used for a part (component) of the URI.
encodeURIComponent("firstName=foobar")
will give you "firstName%3Dfoobar". There will be no firstName request parameter and you can't read it from $_POST['firstName'].
If you really need to encode it, then only encode the firstName variable:
var datastring_escaped = "firstName=" + encodeURIComponent(firstName);

Return value from php to ajax success and error

I am working on User authentication using Jquery mobile & php by referring a tutorial. But the tutorial back end is mongoDB. I want my application connected to PHP & mysql.
I have made some change to the tutorial code, i am confused with php return on error or success.
AJAX code
$.ajax({
type: 'POST',
url: BookIt.Settings.signUpUrl,
data:"submitted=" + "1" + "&mobile=" + mobileNumber + "&firstName=" + firstName + "&lastName=" + lastName + "&password=" + password,
dataType: "json",
success: function (resp) {
alert(resp);
console.log("success");
if (resp.success === true) {
$.mobile.navigate("signup-succeeded.html");
return;
}
if (resp.extras.msg) {
switch (resp.extras.msg) {
case BookIt.ApiMessages.DB_ERROR:
case BookIt.ApiMessages.COULD_NOT_CREATE_USER:
// TODO: Use a friendlier error message below.
$ctnErr.html("<p>Oops! BookIt had a problem and could not 2 register you. Please try again in a few minutes.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
break;
case BookIt.ApiMessages.MOBILENUMBER_ALREADY_EXISTS:
$ctnErr.html("<p>The mobile number that you provided is already registered.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
$txtMobileNumber.addClass(invalidInputStyle);
break;
}
}
},
error: function (e) {
console.log(e.message);
// TODO: Use a friendlier error message below.
$ctnErr.html("<p>Oops! BookIt had a problem and could not register you. Please try again in a few minutes.</p>");
$ctnErr.addClass("bi-ctn-err").slideDown();
}
});
MY PHP return JSON encode output
echo json_encode("success");
API Message
var BookIt = BookIt || {};
BookIt.ApiMessages = BookIt.ApiMessages || {};
BookIt.ApiMessages.EMAIL_NOT_FOUND = 0;
BookIt.ApiMessages.INVALID_PWD = 1;
BookIt.ApiMessages.DB_ERROR = 2;
BookIt.ApiMessages.NOT_FOUND = 3;
BookIt.ApiMessages.EMAIL_ALREADY_EXISTS = 4;
BookIt.ApiMessages.COULD_NOT_CREATE_USER = 5;
BookIt.ApiMessages.PASSWORD_RESET_EXPIRED = 6;
BookIt.ApiMessages.PASSWORD_RESET_HASH_MISMATCH = 7;
BookIt.ApiMessages.PASSWORD_RESET_EMAIL_MISMATCH = 8;
BookIt.ApiMessages.COULD_NOT_RESET_PASSWORD = 9;
BookIt.ApiMessages.PASSWORD_CONFIRM_MISMATCH = 10;
BookIt.ApiMessages.MOBILENUMBER_ALREADY_EXISTS=11;
BookIt.ApiMessages.USERNAME_ALREADY_EXISTS=12;
how i can return error/success to this ajax, so it work fine
Tutorial am referring
You're checking
if (resp.success === true)
which means that the json data must be formatted like this:
{"success":true}
which is produced by:
echo json_encode( ['success'=>true] ); // or array() instead of [] for PHP < 5.4
Similarly, for errors (if (resp.extras.msg)),
echo json_encode( [ 'extras' => ['msg' => $errorcode] ] );
produces this JSON (with $errorcode = 2 (BookIt.ApiMessages.DB_ERROR))
{"extras":{"msg":2}}

Jquery ajax parsing error for json

I am trying to send some data using php and jquery ajax using json datatype method.
Here is my code:
$("#username").on("keyup change keypress", function () {
var username = $("#username").val();
$.ajax
({
type: "POST", // method send from ajax to server
url: window.location.protocol + '//' + window.location.host + '/' + "admin/admins/user_exists",
data: {
username: username
},// Specifies data to be sent to the server
cache: false, // A Boolean value indicating whether the browser should cache the requested pages. Default is true
contentType: "application/json",
dataType: 'json', // The data type expected of the server response.
success: function (response_data_from_server) {
for (var key in response_data_from_server)
var result = response_data_from_server[key] + ""; // JSON parser
if (result == 'true') {
console.log("---------------- in true");
$("#username_alert").text("ERROR");
$('#username_alert').removeClass("alert-success");
$("#username_alert").css("visibility", "visible");
}
else {
if (result == 'false') {
console.log("---------------- in false");
$("#username_alert").text("NO ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').addClass("alert-success");
}
else {
if (result == 'empty') {
console.log("---------------- in empty");
$("#username_alert").text("ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').removeClass("alert-success");
}
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
and it always goes to an error function. The error that I receive is the following:
parsererror SyntaxError: Unexpected token  {}
My url location is correct and is indeed returning the correct json format. Here is my php code:
public function user_exists()
{
$username = $this->input->post("username");
$is_exists = "false";
$this->load->database();
if ($username != "")
{
$rows = $this->db->query("
SELECT * FROM `admins` WHERE `username` = '" . $username . "'
")->num_rows();
if ($rows > 0)
{
$is_exists = "true";
}
else
{
$is_exists = "false";
}
}
else
{
$is_exists = "empty";
}
$arr = array ('result' => $is_exists );
$response = json_encode($arr);
echo $response;
}
I've debugged it million times, the firebug sees the response as correct and expected json, however the client side seems to refuse to get it as a json respone, for what I believe.
Will appreciate any help!
...
header('Content-type: application/json');
echo $response;
Maybe you could use "header('Content-type: application/json');" before "echo"

jquery ajax php json return not working

Baffled... I have a file "api.php" shown below. This is called in the jquery ajax call. When I run it from the command line I get a response that appears correct (ie not empty). When I run it in the ajax call it appears to come back empty. NOW... when I comment out the "if( $td < $lessthan )" and the two braces it all works correctly (i.e., the ajax success gets correct data.
Here is my "api.php" function:
$basedir = "calls/";
$now = time();
$lessthan = 20 * 60;
$ret = array();
$dir = opendir( $basedir );
while(($currentFile = readdir($dir)) !== false)
{
if ( preg_match( '/(.*).txt/', $currentFile, $match) )
{
$tt = #file_get_contents($basedir.$currentFile);
$td = ($now - #strtotime( $tt ));
if( $td < $lessthan )
{
$ret[] = $match[1];
}
}
}
closedir($dir);
echo json_encode(implode(',', $ret));
?>
Here is my jquery ajax call:
$.ajax({
url: 'api.php',
data: "",
dataType: "json",
type: "POST",
success: function(data, textStatus, jqXHR)
{
console.log(data + ':' + previous + ' ' + textStatus );
if( data != null && data != previous && data != "" )
{ previous = data;
$('#other').hide(); //Set output element html
$('#loaddiv').fadeOut('fast').load('reload.php?q='+data).fadeIn("fast"); //Set output element html
}
if( (data == null || data == "" ) && previous != null ) {
//$('#loaddiv').fadeOut('fast').html('No Active Calls').fadeIn("fast"); //Set output element html
$('#loaddiv').fadeOut('fast'); //Set output element html
$('#other').show();
$('#other').fadeOut('fast').load('default.php').fadeIn("fast");
previous = null;
}
},
error: function(m) { alert('error'); }
});
Any ideas on why the commenting out the "if" statement in the api.php makes the whole thing work? Or better yet, how can I leave the if statement in and for it to work.

Categories