ajax data isn't the same in chrome vs firefox - javascript

Some reason I can return data fine from a POST in Chrome. The data returned looks like this when using Chrome:
{"email":"account#bytestand.com","customer_id":20413,"credit_amount":50.0,"currency_symbol":"$"}
But then when the same POST is completed on FireFox I get the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
Somehow the data isn't being handled the same and I don't know why.
Here is the code that generates the ajax request
function getCustomerAndCredit() {
console.log("getCustomerAndCredit");
$(function() {
$("form[action='" + shopAddress + "/account/login']").submit(function(event){
console.log("this is past the submit event in Firefox");
var custEmail = $("form[action='" + shopAddress + "/account/login'] input[type=email]").val();
var pass = $("form[action='" + shopAddress + "/account/login'] input[type=password]").val();
sessionStorage.setItem('custEmail', custEmail);
sessionStorage.setItem('pass', pass);
sessionStorage.setItem('loggedIn', true);
debugger;
$.ajax({
url: "/apps/proxy/return_customer",
data: {email: custEmail},
type: "POST",
dataType: "js",
complete: function(data) {
debugger;
if(noCustomerInDB(data)){
if(data.responseJSON == undefined){
sessionStorage.setItem('customer_id', JSON.parse(data.responseText).customer_id);
sessionStorage.setItem('creditAmount', JSON.parse(data.responseText).credit_amount);
sessionStorage.setItem('currency', JSON.parse(data.responseText).currency_symbol);
}
else {
sessionStorage.setItem('customer_id', data.responseJSON.customer_id);
sessionStorage.setItem('creditAmount', data.responseJSON.credit_amount);
sessionStorage.setItem('currency', data.responseJSON.currency_symbol);
}
}
// console.log("What is the credit_amount here in getCustomerAndCredit " + sessionStorage.getItem('creditAmount'));
},
});
});
});
}
And then this is where the data is going:
function noCustomerInDB(data){
console.log("this is the todd variable " + data);
console.log("stringify data " + JSON.stringify(data));
console.log("what about just data?? " + JSON.parse(data));
console.log("this is the response down here in the no customer function" + data.responseText);
if(data.responseText == ""){
return false;
}
else{
if (JSON.parse(data.responseText).customer_id == "no_customer"){
sessionStorage.setItem('creditAmount', "null");
return false;
}
else{
return true;
}
}
}
I did some more digging and now its looking like the ajax isn't being called on FireFox. Because the data returned from the POST looks like this:
{"readyState":0,"status":0,"statusText":"error"}

This cannot be - dataType: "js"
Use dataType: "json" instead. Also make sure that "/apps/proxy/return_customer" has the proper header configured to deploy JSON:
"Content-Type: application/json"

Related

AJAX call fails with SyntaxError: Unexpected end of JSON input

Sorry for making a post with a generic error but I just can't figure this out! I have an ajax call that for now sends an empty object and just returns json_encode(array('status' => 'success')); while I'm debugging. The ajax call is failing with Error in ajax call. Error: SyntaxError: Unexpected end of JSON input
I've tried sending just data['pid']='csv' in case the json needed to have something in it, but still get the same error.
AJAX call
function runDataDownload() {
var data = {};
// data['rawFiles'] = $('#projectIDs').val();
// data['metadata'] = $('#getData').val();
// data['type']= $('#submitType').val();
// data['pid']='csv';
// data['command']='data/qcTest';
console.log(data);
console.log(typeof data)
var qcRunId="csv" + Date.now();
var posturl = baseURL + "manage/ajax_runBg/csv/" + qcRunId;
$.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})
.done(function(result) {
console.log(result);
if (result.status==='success'){
// begin checking on progress
checkRunStatus(qcRunId, loopIndex);
}
else if (result.status==='failed'){
$('#' + errorId + ' > li').remove();
$.each(result.errors, function(key, value) {
$('#' + errorId).append( "<li>" + value + "</li>" );
});
$('#' + statusId).hide();
$('#' + errorId).show();
}
else {
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( "<li>Invalid return from ajax call</li>" );
$('#' + errorId).show();
// PTODO - may not be needed
// make sure it is visible
$('#' + errorId).get(0).scrollIntoView();
}
})
.fail(function(jqXHR, status, err) {
console.log(jqXHR + status + err);
$('#' + errorId + ' > li').remove();
$('#' + errorId).append( `<li>Error in ajax call. Error: ${status} (${err.name}: ${err.message})</li>`);
$('#' + errorId).show();
});
}
And my php code:
public function ajax_runBg($qcName, $runId) {
echo json_encode(array('status' => 'success'));
}
Thank you!
Making my comment an answer in case someone else runs into this-
The reason the code was working in my controller was that my colleague's controller had authentication checks in the constructor! So there must have been an authentication error returned, that was not JSON formatted, hence the error..
Something seems to clear the PHP output buffer after ajax_runBg has been called. Check this by adding ob_flush(); flush(); to ajax_runBg after the echo statement.
Sorry for making an answer, when i don't have a full one, I don't have enough reputation to comment.
I ran this code (i removed variables that i don't have) and did not get an error (nothing wrong with "echo json_encode(array('status' => 'success'));").
Here are some possible reasons why it fails:
Your problem could be that the php does not echo anything.
I once got this problem and fixed it by first making a variable out of json_encode("stuff to encode") and then doing echo on that variable.
Is there more to the php file that you did not show? There could be a problem if there are other things being echoed.
If i remember right, than you have to specify the key and the value in data attr. .
var data = {};
data['rawFiles'] =$('#projectIDs').val();
data['metadata'] = $('#getData').val();
data['type']= $('#submitType').val();
data['pid']='csv';
data['command']='data/qcTest'
... Ajax...
Data: {dataKey: data}
....
And in the API you can catch it with dataKey name.
When sending json you must first encode it as json, so:
$.ajax({type: "POST", url: posturl, data: JSON.stringify(data), dataType: 'json'})
JSON.stringify

Identifying AJAX request

I am triggering multiple AJAX requests in a loop. They run in parallel and it is not clear which one will respond first.
If the response is successful, I can identify the request by analyzing the response.
for (kk = 0; kk < $('#style').val().length; kk++){
$.ajax({
type: "POST",
url: "/single",
data: {style: [$('#style').val()[kk]]},
success: function (results) {
if (results.status == 'success'){
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append(results.payload)
}
});
}
else{
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append('<b>' + results.style + ':</b> ' + results.payload)
}
});
}
},
error: function (error) {
console.log(error);
}
});
}
However, once in a while, the request fails and an error is triggered.
For a proper error handling, I would like to know to which of the (previously triggered) requests the error belongs.
Is there a clean method how a specific AJAX request can be identified?
I would recommend to pass in a identifier via context to the AJAX call which you can use inside the success or error methods:
for (kk = 0; kk < $('#style').val().length; kk++){
$.ajax({
type: "POST",
url: "/single",
data: {style: [$('#style').val()[kk]]},
// data inside "context" will be available as part of "this" in the success/error case.
context: {
"kk": kk
},
success: function (results) {
if (results.status == 'success'){
console.log("Element " + this.kk + " finished successfully.");
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append(results.payload)
}
});
}
else{
$('#results').find('div').each(function(){
if ($(this).attr('id') == results.style){
$(this).empty().append('<b>' + results.style + ':</b> ' + results.payload)
}
});
}
},
error: function (error) {
console.log("Element " + this.kk + "failed.");
console.log(error);
}
});
}
More information regarding context can be found in the jQuery documentation.
Regarding your comment about checking how many calls failed / succeeded: here is a JsFiddle demonstrating how to keep track of the call statistics.

wordpress ajax returning zero instead of string message

My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);

PHP headers always give error Undefined Index even using $_SERVER global

I am performing an ajax request cross domain. I have been trying to use functions that return the headers in an array only to find that I get Undefined Index even though I can return their values in my ajax request and print them the screen.
I have found some posts on SO that said I should be using $_SERVER globals. So I switched to that method only to get the same results.
Here is my jQuery:
setTimeout(function() {
jQuery.ajax({
url: 'http://something.com',
type:"POST",
dataType:"json",
crossDomain:true,
contentType:"application/json",
data: jsonData,
processData:false,
cache:false,
beforeSend: function( xhr ) {
xhr.setRequestHeader("Authorization",api_key[index]);
xhr.setRequestHeader("Action","PUSH");
},
success: function(data) {
alert(data.action);
alert(data.platform + ' : ' + data.message + ' : ' + data.app_name );
if(data.message == 'success')
{
jQuery('#hollmanPNs_send_push div#hollmanPNs_progressbar' + index).progressbar("value",100);
//add message to the paragraph for app name
jQuery('#hollmanPNs_send_push p#hollmanPNs_paragraph' + index).append(': Complete');
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert( 'We had an error: ' + textStatus + errorThrown );
}
}).fail(function() {
alert( 'We had a failed AJAX call.');
});//end ajax
}, index * 5000);//end timeout function
And here is what I am using for PHP:
if($_SERVER['HTTP_ACTION'] != '')
{
//Do Something
}
I have tried switching to:
xhr.setRequestHeader("X-Action","PUSH");
and
$_SERVER['HTTP_X_ACTION']
with the same results. Only I was not able to return them to my ajax request.
I am using PHP 5.3.3.
I am also using this function which I change depending on the different headers I am trying at the time:
header('Access-Control-Allow-Headers: Action, Authorization, Content-Type');
You'll want to get the headers a different way like so:
$headers = getallheaders();
if(array_key_exists('Action', $headers) && $headers['Action'] != '')
{
//Do Something
}

jquery ajax always results in 'error' even when it works

I have the below JQuery ajax function which is used to update a PHP Session variable.
I POST two variables, which the PHP page collects and sets the relevant Session variable.
Occasionally though it doesn't work, even though the correct values are being Posted across.
So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax.
But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.
Am I missing something here. Do I need to create a response or should that be automatic?
My Javascript is:
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function()
{
alert('success');
},
error: function()
{
alert('failure');
}
});
console.log(p + " " + x + " selected");
return false;
}
The setSession . php is:
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
}
?>
Try this way
//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
echo "success";
}
?>
//ajax call
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function(data)
{
console.log(data);
},
error: function(jqxhr)
{
//it will be errors: 324, 500, 404 or anythings else
console.lgo(jqxhr.responseText);
}
});
return false;
}

Categories