undefined error with ajaxcall to receive json data - php

my problem is that I
can not solve this problem
If I call the php script, all I get is an undefined error
this is the code I use for testing AND
this is the original code from the creator that is giving me a headache
function startJsonSession(){
$.ajax({ url: "jsontest.php?action=startjson",
cache: false,
dataType: "json",
complete: function(data) {
username = data.username;
alert(username);
}
});
}
//phpscript
if ($_GET['action'] == "startjson") { startJson(); }
function startJson() {
header('Content-type: application/json');
$items = '';
echo json_encode(array(
"username" => "bob",
"items" => array( "item1" => "sandwich",
"item2" => "applejuice"
)
));
}
thanks, Richard
edited my question because:
this function returns the json data in a different way
and therefore the solution presented below, does not have the same outcome.
function startChatSession() {
$items = '';
if (!empty($_SESSION['openChatBoxes'])) {
foreach ($_SESSION['openChatBoxes'] as $chatbox => $void) {
$items .= chatBoxSession($chatbox);
}
}
if ($items != '') {
$items = substr($items, 0, -1);
}
header('Content-type: application/json');
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}
<?php
exit(0);
}

I recreated with your code and figured it out. The object being returned is of type XMLHttpRequest. Its got a property called responseText holding a json string with the data.
so this works..
var decodedData = eval("(" + data.responseText + ")");
username = decodedData.username;
alert(username);
A bit messy but it does the trick :-)
p.s If it helps, I figured it out using firebug in firefox and sticking a breakpoint in the js code
Edited below:
Without wanting to do the eval, you could use this and it works:
$.getJSON("json.php?action=startjson",
function(data) {
username = data.username;
alert(username);
}
);
Edited to show what I did with the success function:
$.ajax({
url: "json.php?action=startjson",
cache: false,
dataType: "json",
success: function(data) {
username = data.username;
alert(username);
}
});

Is username a global variable?
If not you should prepend the "var" keyword.
username = data.username -> var username = data.username;

At the end I got it working.
I installed firebug and saw that the php script was returning html headers instead off json.
All off the sudden it started working, I really would like to know what the problem was, but I can't tell you.
Anyway, thanks for sticking so long, David

also what I don't understand is that it breaks out off php mode, instead of echoing it back like it's done with xml
?>
{
"username": "<?php echo $_SESSION['username'];?>",
"items": [
<?php echo $items;?>
]
}
<?php
is this the same as above (object array containing literal array)?
echo json_encode(array(
"username" => "bob",
"items" => $items
)
));
}

Related

Undefined Variable in Ajax from PHP

I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}

AJAX it's not receiving the data back from the php file

I'm trying to send some values ​​through ajax and after being treated in the test.php, send the data back to be used.
The database part is correct. My problem is in the re-sending of the data:
The Json coding part does not give error, but when I try to check the data, many of them do not appear.
I think this can be caused by:
The way I am resending the data;
The way I encode Json.
My code.
ajax main.php:
$('#filtro_limit1').val(num_Limite_rows);
$.ajax({
url: teste.php,
type:'post',
data:
{
limite: num_Limite_rows,
tipologia: tipologia_val,
ordenar_por: ordenar_por_val
},
success: function(data, num_rows, num_actual_rows, mensagem_erro)
{
}
});
PHP teste.php:
if(pg_num_rows($result1) > 0)
{
$data = array[];
$data = $result1;
$out = array_values($data);
echo json_encode($out);
echo pg_num_rows($result1);
echo $filtro_limit;
echo "Não existem erros";
}
else
{
$data = array[];
echo json_encode($data);
$numero_rows = 0;
echo $total_rows;
echo $filtro_limit;
echo "Não existem valores a serem mostrados";
}
Please some help needed. Thank you for the future help.
Your success function is wrong. The parameter data will contain all the output of your php script. You can't automatically split the output by using different parameters in the function definition.
function success(data, textStatus, jgXHR) {
console.log(data);
}
Check your console and you'll see your data.
You'll probably want to change your php code:
$result = [
'out' => json_encode($out),
'result1' => pg_num_rows($result1),
'filtro_limit' => $filtro_limit,
'message' => "Não existem erros",
]
echo json_encode($result);
exit;
and
$result = [
'total_rows' => $total_rows,
'filtro_limit' => $filtro_limit,
'message' => "Não existem valores a serem mostrados",
];
echo json_encode($result);
exit;
That way, you'll have a much easier time to parse the data in JavaScript. For example:
function success(data, textStatus, jgXHR) {
var message = data.message;
}
you have to return all data in one statement in php like this :
echo json_encode(array(
'out'=>$out,
'num_rows'=>pg_num_rows($result1),
'filtro_limit'=>$filtro_limit,
'msg'=>"Não existem valores a serem mostrados"
));
and ajax code like this:
$('#filtro_limit1').val(num_Limite_rows);
$.ajax({
url: 'teste.php',
type:'post',
dataType: 'json',
data:
{
limite: num_Limite_rows,
tipologia: tipologia_val,
ordenar_por: ordenar_por_val
},
success: function(data)
{
$num_rows=data['num_rows'];
}
});

Ajax request to php failing?

I am trying to do an ajax request to my php, but for some unknown reason it seems to fail as i don't get to the success part where I have a console.log
Can anyone please give me some hint what might be wron with this, I am stuck for too long now??
Here is how my jQuery looks :
getPending();
function getPending(){
var usernameLS = localStorage.getItem('userNameLS');
var userTypeLS = localStorage.getItem('isAdminLS');
if (userTypeLS!=1) {
console.log("inside");//i am getting here
$.ajax({
type: "POST",
dataType: 'json',
url: 'get-pending.php',
data: {
data: usernameLS //this is a string, "user2" for instance
},
success: function(data) {
console.log("Thanks!!!",data);//i never got here
},
failure: function() {
console.log("Error!");
alert(' Fail');
}
});
}
And here is my php :
<?php
$string = file_get_contents("appointments.json");
$usernameAjax = $_POST['data'];
var_dump($usernameAjax);
$json_a = json_decode($string, true);
$isPending;
foreach ($json_a as &$json_r) {
if ($usernameAjax==$json_r['userName'] && $json_r['status'] = "Pending") {
$isPending = 1;
}
else{
$isPending = 0;
}
}
var_dump($isPending);
echo $isPending; //i tried with a hardcodede 1 or 0 zero. Didn't work.
?>
Seems like your output is not correct JSON format, so client-side cant understand what was recieved.
First - remove var_dump, it breaks json format anyway;
Second - jou just output 1 or 0 - that is not correct json too; use json_encode to format reply properly;
Third - php files often contains trailing symbols after ?>, that are appends to output too and could break output format. Dont close php with ?> at all; additionally you could use die($output) instead of echo($output) to avoid any output after your data was written

jquery ajax not parsing json data from php

I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.

json stringify to php

I want to pass the key values into php page.
At php page, I will start to read value by matching ajaxcallid.
But it not working.
It gotta do with syntax/way I am passing in causing error.
parse error
invalid json: ajax call id is missing
JavaScript/AJAX:
var person = {
"Address" : "123 Anywhere St.",
"City" : "Springfield",
"PostalCode" : 99999
};
alert(person);
person= JSON.stringify(person);
alert(person);
$.ajax({
url: 'ROOT_URL/admin/ajaxtest.php',
type: "POST",
dataType: 'json',
data: {ajaxcallid: '26', jsarr: person},
timeout: 5000,
success: function(output) {
alert(output.Address);
},
});
PHP:
<?php
if (isset($_REQUEST['ajaxcallid']))
{
if($_REQUEST['ajaxcallid']==26)
{
//example, I want to read value of person.Address, person.City,
//person.PostalCode
//what is the easiest way
$phparr= json_decode($_REQUEST['jsarr']);
//do all other operation
$output= json_encode($phparr);
}
}
else
{
$output= "ajax call id is missing";
}
echo $output;
?>
If you are not using dataType : 'json', you might need to do stripslashes
$.post(window.data.baseUrl, {posts : JSON.stringify(posts)});
And in php:
$posts = json_decode(stripslashes($_POST['posts']));
This helped me:
data = json_decode($this->request->data['jsarr'], true);
in your php code for accessing the record
Hope it will help someone!
I'm going to take a guess and say that you SHOULDN'T stringify anything. I believe JQuery will do that for you. Namely, no person = JSON.stringify(person). Give that a try.
This is what your $.ajax call and the PHP side should look like:
JQuery
$.ajax({
url: "/admin/ajaxtest.php",
method: "POST",
data: {
ajaxcallid: "26",
person: JSON.stringify({
"Address" : "123 Anywhere St.",
"City" : "Springfield",
"PostalCode" : "99999"
})
}
}).done(function(data) {
if (!data) {
// generic error message here
} else if (data == 'invalid') {
alert('no ajaxcallid received');
} else {
var result = $.parseJSON(data); // if you pass back the object
alert(result.Address);
}
});
PHP
if (isset($_REQUEST['ajaxcallid'])) {
if ((int) $_REQUEST['ajaxcallid'] == 26) {
$personData = json_decode($_REQUEST['person']);
$address = $personData->Address;
$postalCode = $personData->PostalCode;
$returnData = json_encode($personData);
echo $personData;
die();
}
} else {
echo 'invalid';
die();
}
$data_array = json_decode($json_string);
If you want objects to be converted into associative arrays, then add true into function:
$data_array = json_decode($json_string, true);
I have not worked with PHP but from my experience with ASP.net following may help you.
Add contentType key to ajax settigns:
type: "POST",
contentType:'application/json',
dataType: 'json',
also I think you need to stringify whole value you are assigning to data like this:
var person = {
"Address" : "123 Anywhere St.",
"City" : "Springfield",
"PostalCode" : 99999
};
var d= {ajaxcallid: '26', jsarr: person};
var dat=JSON.stringify(d);
......
data: dat,
......

Categories