NaN error in ajax callback - php

I am getting a NaN error in my ajax callback function and can only think it has to do with an array in PHP. I have been trying to find ways to correct it but have come up against a brick wall.
What is supposed to happen is that PHP queries the database and if there are no results send a response to ajax and issue the error message. However, all I am getting is NaN. The error stems from the success code below.
I would be grateful if someone could point out my error.
PHP code:
$duplicates = array();
foreach ($boxnumber as $val) {
if ($val != "") {
mysql_select_db($database_logistor, $logistor);
$sql = "SELECT custref FROM boxes WHERE custref='$val' and status = 'In'";
$qry = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($qry) < 1) {
$duplicates[] = '[ ' . $val . ' ]';
$flag = 1;
} else {
$duplicates[] = $val;
}
}
}
//response array with status code and message
$response_array = array();
if (!empty($duplicates)) {
if ($flag == 1) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'ERROR: ' . implode(',', $duplicates) . ' needs to be in the database to be retrived.';
}
//if no errors
} else {
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'All items retrieved successfully';
$response_array['info'] = ' You retrieved a total of: ' . $boxcount . ' boxes';
}
//send the response back
echo json_encode($response_array);
Relevant ajax:
$("#brtv-result").html(msg.message+msg.info);
jQuery code:
$(function() {
$("#BRV_brtrv").submit(function() {
var send = $(this).serialize();
$.ajax({
type: "POST",
url: "boxrtrv.php",
cache: false,
data: send,
dataType: "json",
success: function(msg) {
if( msg.status === 'error') {
$("#brtv-result").fadeIn(1000).delay(1000).fadeOut(1000);
$("#brtv-result").removeClass('error');
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message);
}
else {
$("#brtv-result").fadeIn(2000).delay(2000).fadeOut(2000);
$("#brtv-result").removeClass('error');
$("#brtv-result").addClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message+msg.info);
//location.reload(true);
//$('#brtv-result').addClass("result_msg").html("You have successfully retrieved: "+data.boxnumber).show(1000).delay(4000).fadeOut(4000);
$("#BRV-brtrv-slider").val(0).slider("refresh");
$("input[type='radio']").attr("checked",false).checkboxradio("refresh");
var myselect = $("select#BRV-brtrv-department");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
var myselect = $("select#BRV-brtrv-address");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
}
},
error:function(){
$("#brtv-result").show();
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass('error');
$("#brtv-result").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});

NaN (pronounced nan, rhymes with man) only happens when you try to do an operation which requires a number operand. For example, when you try to Number('man') you'll get this error.
What you return from your PHP file, is simply an array which contains simply data. So, the problem is in your JavaScript. You have to send more parts of your JavaScript, so that we can see it thoroughly.
However, I recommend that you use Firebug and set a breakpint at the correct place (the callback function start), and check the stack trace of the calls to diagnose the problem.

Related

Ajax sometimes fails to parse the large JSON response

I am calling a PHP service with below ajax code :
jQuery.ajax({
url: 'index.php?option=com_sheet&task=getReportsData',
timeout: 300000,
dataType: "json",
type: "GET",
data: {
'project': projectsStr,
'startweek': startweek,
'endweek': endweek
}
}).done(function(response) {
if (response.success && response.data) {
var projectData = response.data;
if (projectData.projectReportData.length > 0) {
loadDataTable(response.data);
} else {
jQuery('#projectReportData').html("<br/><h2>No Matching Results</h2>");
}
}
}).fail(function(jqXHR, textStatus) {
jQuery(".overlay")[0].style.display = '';
if (textStatus === 'timeout') {
alert('Failed from timeout');
}
alert(textStatus);
});
The php code that provides the response prints the response with :
$data = (object)array_merge(['projectReportData' => $projectReportData]);
header("Content-Type: application/json");
$post_data = json_encode($data, JSON_FORCE_OBJECT);
ob_start('ob_gzhandler');
echo new JResponseJson($data);
ob_end_flush();
jexit();
This ajax works fine sometimes and is able to parse the JSON. But most of the times gives "parsererror".
Below code fetch the data from the DB :
$db = JFactory::getDbo();
$query = "CALL getReportData('" . $startweek . "','" . $endweek . "')";
$db->setQuery($query);
$res = $db->query($query);
$returnArr = [];
$i = 0;
while( $r = $res->fetch_assoc()){
$projectReportData[$i] = $r;
$i++;
}
when i change dataType to text the pointer reaches the .done() but console.log(response) returns a blank.

e.preventDefault / return false breaks ajax script firing properly

I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me
JS:
$(document).ready(function() {
var form = $('form#edit_child_form'),
data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$('#submit_btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
it's probably something really small that I've just missed but not sure what - any ideas?
my solution:
I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions
Try the following instead.
I moved the form data inside click and enclosed the mysql queries values in single quotes.
JS:
$(document).ready(function() {
var form = $('form#edit_child_form');
$('#submit_btn').on('click', function(e) {
e.preventDefault();
var data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'get',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = '". $parent_id ."' ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = '$child_row[0]'");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
You are using an AJAX POST request so in your PHP you should be using $_POST and not $_GET.
You can just change this:
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
to this:
$descriptions = $_POST['descriptions'];
$child_id = $_POST['child_id'];
$parent_id = $_POST['parent_id'];

Why do the responses of my new plugin not save?

So below are some of the actions that my plugin is supposed to perform when submitting the survey. On my console I should get 'response saved', but I get absolutely nothing, not even 'Could not save response'. I have looked through the code, but I can't see why ajax is not performing the function of saving the response. Can anyone else see what is going on here?
// 5.3
// hint: ajax form handler for saving question responses expects: $_POST['survey_id'] and $_POST['response_id']
function ssp_ajax_save_response() {
$result = array(
'status'=>0,
'message'=>'Could not save response.',
'survey_complete'=>false
);
try {
$survey_id = (isset($_POST['survey_id'])) ? (int)$_POST['survey_id']: 0;
$response_id = (isset($_POST['response_id'])) ? (int)$_POST['response_id']: 0;
$saved = ssp_save_response($survey_id, $response_id);
if($saved) {
$survey = get_post($survey_id);
if(isset($survey->post_type) && $survey->post_type = 'ssp_survey') {
$complete = true;
$html = ssp_get_question_html($survey_id);
$result = array(
'status'=>1,
'message'=>'Response saved!',
'survey_complete'=>$complete,
'html'=>$html
);
} else {
$result['message'].='Invalid survey.';
}
}
} catch(Exception $e) {
// php error
}
ssp_return_json($result);
}
// 5.4
// hint: saves single question response
function ssp_save_response($survey_id, $response_id) {
global $wpdb;
$return_value = false;
try {
$ip_address = ssp_get_client_ip();
// get question post object
$survey = get_post($survey_id);
if($survey->post_type == 'ssp_survey'):
// get current timestamp
$now = new DateTime();
$its = $now->format('Y-m-d H:i:s');
// query sql
$sql = "INSERT INTO {$wpdb->prefix}ssp_survey_responses (ip_address, survey_id, response_id, created_at) VALUES (%s, %d, %d, %s) ON DUPLICATE KEY UPDATE survey_id = %d";
// prepare query
$sql = $wpdb->prepare($sql, $ip_address, $survey_id, $response_id, $ts, $survey_id);
// run query
$entry_id = $wpdb->query($sql);
// If response saved successfully...
if($entry_id):
// return true
$return_value = true;
endif;
endif;
} catch(Exception $e) {
// php error
ssp_debug('ssp_save_response php error', $e->getMessage());
}
return $return_value;
}
Someone made me aware that I need to add the jQuery code and so here it is and thank you in advance.
jQuery(document).ready(function($){
// do something after jQuery has loaded
ssp_debug('public js script loaded!');
// hint: displays a message and data in the console debugger
function ssp_debug(msg, data) {
try {
console.log(msg);
if(typeof data !== "undefined") {
console.log(data);
}
} catch(e) {
}
}
// setup our wp ajax URL
var wpajax_url = document.location.protocol + '//' + document.location.host + '/wp-admin/admin-ajax.php';
// bind custom function to survey form submit event
$(document).on('submit', 'ssp-survey-form', function(e){
// prevent form from submitting normally
e.preventDefault();
$form = $(this);
$survey = $form.closest('.ssp-survey');
// get selected radio button
$selected = $('input[name^="ssp_question_"]:checked', $form);
// split field name into array
var name_arr = $selected.attr('name').split('_');
// get the survey id from the last item in name array
var survey_id = name_arr[2];
// get the response id from the value of the selected item
var response_id = $selected.val();
var data = {
_wpnonce: $('[name="wp_nonce"]', $form).val(),
_wp_http_referer: $('[name="wp_http_referer"]', $form).val(),
survey_id: survey_id,
response_id: response_id
};
ssp_debug('data', data);
// get the closest dl.ssp-question element
$dl = $selected.closest('dl.ssp-question');
// submit the chosen item via ajax
$.ajax({
cache: false,
method: 'post',
url: wpajax_url + '?action=ssp_ajax_save_response',
dataType: 'json',
data: data,
success: function(response) {
// return response in console for debugging...
ssp_debug(response);
// If submission was successful...
if(response.status) {
// update the html of the current li
$dl.replaceWith(response.html);
// hide survey content message
$('.ssp-survey-footer', $survey).hide();
} else {
// If submission was unsuccessful...
// notify user
alert(response.message);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// output error information for debugging...
ssp_debug('error', jqXHR);
ssp_debug('textStatus', textStatus);
ssp_debug('errorThrown', errorThrown);
}
});
});
});

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"

After AJAX call, data is null

When I make an AJAX call from a form, it shows it is successful, but the data object is null. The code is as follows:
$.ajax(
{
url: 'shipprocess.php',
dataType: 'json',
type: 'POST',
success: function(data)
{
alert('Data is: ' + data);
alert('The AJAX request was a success.');
},
'error': function()
{
alert('An unexpected error occurred.');
}
});
return false;
The form looks like this:
<div class="processedDate">
<form action="shipprocess.php" method="POST" id="shipProcess2" name="shipProcess2">
<input type="hidden" name="empID" value="1" />
<input type="hidden" name="thisOrderID" id="thisOrderID2" value="2" />
<label>Date Shipped </label>
<input type="text" name="shipDate" id="shipDate2" class="shipDate" size="20" value="" />
<input type="submit" name="shipped" id="shipped2" class="shipped" value="Shipped!" />
</form>
</div>
After the AJAX call is made, Firebug shows the status as 200 and content length as 0. The script that processes the form is called shipprocess.php. It echos the following data when the return: false; line is commented out:
[ { "sd": "2012-09-17", "eid": "1", "oid": "2", "efn": "Johnathan", "eln": "Smith" } ]
For some reason, the script keeps alerting that data is null. A complete example can be found at http://www.yellowcas.com/ship/shipexample.php. This example shows the alert message that the data object is null when you submit the form. I also have a complete example of the data that the shipprocess.php script returns at http://www.yellowcas.com/ship/shipexample1.php. I have used AJAX before to populate the city and state input fields for a zip code that is entered by the user. The jQuery script is almost identical except for the fact that I use GET instead of POST for the zip code form.
I have tried declaring the header in PHP as JSON data, but that doesn't help either. Firebug doesn't seem to be giving me any helpful information either. I have tested the script using a different file called testjson.html. In that file, I put valid JSON data as the only line in the file with no headers at all, and it returns the data variable as an object. That example is at www.yellowcas.com/ship/shipexample2.php. I couldn't post more than 2 hyperlinks. If you would like to see the code for shipprocess.php, I will gladly post it. I just don't want to make this post too long. Any ideas would be greatly appreciated. Thank you.
I decided to post the shipprocess.php code to be sure you can see what I have done.It is as follows:
<?php
require_once('dblogin.php');
require_once('dbconnect.php');
require_once('funcs.php');
$err = array();
$datePattern = "!^(\\d\\d)[-/](\\d\\d)[-/](\\d\\d(?:\\d\\d)?)$!";
$psErr = "Shipping date is required.";
$emErr = "Employee ID is missing.";
$orErr = "Order ID is missing.";
if(isset($_POST['shipped']))
{
$postEID = clean($_POST['empID'],$emErr,$n);
$postOID = clean($_POST['thisOrderID'],$orErr,$n);
$postShipDate = clean($_POST['shipDate'],$psErr,$n);
$now = date("Y-m-d H:i:s");
if($postEID == $emErr)
{
$err[] = $postEID;
}
else
{
$query = "SELECT FK_UserID,FirstName,LastName FROM employees WHERE EmployeeID = '$postEID'";
$res = mysql_query($query);
if(mysql_num_rows($res) < 1)
{
$err[] = "Employee does not exist.";
}
else
{
while($row = mysql_fetch_assoc($res))
{
$retUserID = $row['FK_UserID'];
$retFirstName = $row['FirstName'];
$retLastName = $row['LastName'];
}
}
}
if($postOID == $orErr)
{
$err[] = $postOID;
}
if($postShipDate == $psErr)
{
$err[] = $postShipDate;
}
else
{
if (preg_match($datePattern,$postShipDate,$sMatches))
{
$sMonth = $sMatches[1];
$sDay = $sMatches[2];
$sYear = $sMatches[3];
if(checkdate($sMonth,$sDay,$sYear))
{
$shipDate = "$sYear-$sMonth-$sDay";
}
else
{
$err[] = "Invalid shipping date.";
}
}
else
{
$err[] = "Invalid Shipping Date";
}
}
if(empty($err))
// Keep processing the information if there are no errors.
{
$data[] = "$postEID,$shipDate,$postOID,$now,$retFirstName,$retLastName";
}
else
// Return the errors to the user so corrections can be made.
{
$data[] = implode(",",$err);
}
for ($i=0;$i<sizeof($data);$i++)
{
$info = explode(",",$data[$i]);
$data[$i] = $info;
}
$result = array();
for ($y=0;$y<sizeof($data);$y++)
{
if (($data[$y][0]) !== false)
{
array_push($result, array("sd"=>$data[$y][1], "eid"=>$data[$y][0], "oid" => $data[$y][2], "efn"=>$data[$y][4], "eln"=>$data[$y][5]));
}
if (count($result) > 2)
{
break;
}
}
}
echo array_to_json($result);
?>
Please try out the three example pages I have provided to see what the different results are. Thank you.
Your code lacks at least 2 things:
1: When posting with Ajax, you have to send post data. So you have to tell what data you want to send. Most of the time it will be the serialized form data, but it could be anything.
var dataString = 'name=Gr G';
$.ajax(
{
url: 'shipprocess.php',
dataType: 'json',
data: dataString,
type: 'POST',
...
2: You expect a return value, but you do not send a return value. In shipprocess.php after processing you should echo somethning like this:
...
echo 'data received and processed';
...
You are misusing the $.ajax() method, you have to specify the "data" parameter with the contents of your form.
So you should do something like :
$.ajax({
"url": 'shipprocess.php',
"dataType": 'json',
"type": 'POST',
"data": $("#myform").serialize(),
});
This is what I used to send the data.
var jqXHR = $.ajax({
type: 'POST',
url: your url,
data: { var name: 'data here'},
dataType: 'json'
});
jqXHR.done(function (your returned data) { your stuff )};

Categories