Returning JSON not working properly - php

I am trying to return data from a database and convert it into json and send it back to my javascript. However its not working as planned, it returns as an array on the javascript.
Javascript
function getData(id) {
$.ajax({
url: 'some url',
crossDomain: true,
type: 'post',
data: {
id: id
},
success: function (data) {
var json = jQuery.parseJSON(data);
alert(data);
},
});
};
PHP
<?php
header("access-control-allow-origin: *");
$dbhost = 'you dont need this info';
$dbuser = 'you dont need this info';
$dbpass = 'you dont need this info';
$db = 'you dont need this info';
$dbserver = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db) or die("Unable to select database: " . mysql_error());
if (isset($_POST['id'])) {
$ID = $_POST['id'];
}
echo $ID;
$result = mysql_query('SELECT * FROM clubmember WHERE clubID = "' . $ID . '"');
$row = mysql_fetch_assoc($result);
$name = $row['name'];
$clubID = $row['clubID'];
$lID = $row['lID'];
$sName = $row['sName'];
$desc = $row['description'];
$json = json_encode(array(
'name' => $name,
'clubID' => $clubID,
'lID' => $lID,
'sName' => $sName,
'description' => $desc
));
echo $json;
?>
The javascript alerts in the form of [object Object], [object Object] ...
Which shouldn't be the case...

Don't echo $ID in your PHP. Use jQuery's ajax dataType property and set it to json. Use default javascript json parser.

try alerting json rather than data?

Javascript returns an object because you are in fact alerting an object. Try alert(data.name);
or alert(data.clubID);, it will work.

You should specify the data type that the ajax call is requesting, otherwise jQuery will "intelligently" detect based on the MIME type. If the ajax call receives json data, it will use it as a JavaScript object, which is why you are getting that alert.

That is right.
The JSON is an object. a.k.a Javascript Object Notation. That should be in case.
It should contain your data. Try data.*.
By the way, if you don't clear the data coming from your users before using it with any SQL Query, that will cause trouble.
See it in action with a basic example:
// $_POST['id'] = '" OR 1"'
$result = mysql_query('SELECT * FROM clubmember WHERE clubID = "'.$ID.'"');
Your query is now
SELECT * FROM clubmember WHERE clubID ="" OR 1 ""
Because 1 is always true, I am now able to take all of your clubmember table. Cheers.

Even if parseJSON returns an object, doing a console.log should show [Object, Object, ...] which is an array of object

The .ajax() call will, if the dataType parameter is not given, "intelligently guess" what the requested page returns. In the case of JSON, it will pass a JavaScript object to the success function.
After reviewing your question(s), I believe I get what you mean.
What you're expecting is a single object (looked up with SQL, as mentioned in a very insecure way) with 5 properties, name, clubID, lID, sName and description.
However, it seems that what you're getting back are multiple rows with only two properties?
What you're saying is that while the php script echo's the right values (one row) but JSON is receiving multiple values(/rows). Are you sure the PHP is receiving the right ID from the AJAX call?

Related

Give autonumber Id MySQL back with an AJAX call? [duplicate]

Here's my PHP code called during jQuery AJAX call:
<?php
include '../code_files/conn.php';
$conn = new Connection();
$query = 'SELECT Address_1, Address_2, City, State, OfficePhone1, OfficePhone2, Fax1, Fax2, Email_1, Email_2
FROM clients WHERE ID = ?';
$conn->mysqli->stmt_init();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('s', $_POST['ID']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo json_encode($row);
?>
And the client-side code is:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
// Result
}
);
The AJAX call is successfully completed. I get the value of Result as
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road",.....and so on
What I want is to be able to use the values returned like Result.Address_1, Result.Address_2 and so on. But I can't do it using the above code. I tried using $row = $result->fetch_object() and $row = $result->fetch_array(), but no use.
And I know that this can be done by this code on the server side:
$row = $result->fetch_assoc();
$retVal = array("Address_1"=>$row['Address_1'], "Address_2"=>$row['Address_2'].......);
echo json_encode($retVal);
or
$row = $result->fetch_object();
$retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......);
echo json_encode($retVal);
Is there a way to send the $row directly to the client side JavaScript and ready to be used as JSON object, without manually creating an array first?
The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSON in your callback function:
$.ajax({
url : url,//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
type : 'post',
success : function(Result){
var myObj = $.parseJSON(Result);
//you can now access data like this:
//myObj.Address_1
}
}
);
You can let jQuery do this for you by setting the dataType property for your AJAX call to json:
$.ajax({
url : url//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
dataType : 'json',
type : 'post',
success : function(Result){
//you can now access data like this:
//Result.Address_1
}
}
);
The above examples expect that the response from the server to be in this format (from your question):
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
In your $.post call, the last argument could be the data-type: json:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
alert(Result.Address_1);
},'json'
);
Everything should work then, as it looks like you are doing everything right.
json_encode accepts objects, so there's no need to do that automatic array-building.:
$row = $result->fetch_object();
echo json_encode($row);
It's as simple as that!

Jquery - parsererror - Unexpected end of JSON input

I'm trying to retrieve info from my database and display the information in a table generated by JQuery. I had done this before, and with using the exact same code it doesn't work anymore. I've looked up several other questions about this, but none of them has given me an answer.
This is the situation: An user select a value from the select menu, by selecting a value, that value gets sent and used to retrieve the right key for the right data. Then, by pressing a button the data should appear in a table. In order to accomplish this, I am using 3 ajax calls, one for populating the select box, one to send the right value, and another one to retrieve the needed data. The first two work perfectly, but not the last one.
My browser receives the data (see below) but the table does not appear and I'm getting a 'Unexpected end of JSON input' error. Can anyone help me out with this?
HTML/Jquery of the Ajax with the error:
function BekijkGegevens() {
$.ajax({
type: 'GET'
, data: {}
, dataType: 'json'
, url: "https://projectmi3.000webhostapp.com/webservices/bekijk.php"
, success: function (rows) {
$('#output').append("<table><tr><th> datum</th><th>stand</th></tr>")
for (var i in rows) {
var row = rows[i];
var datum = row[1];
var stand = row[0];
$('#output').append("<tr><td>" + datum + "</td><td>" + stand + "</td></tr>");
}
$('#output').append("</table>");
}
, error: function (JQXHR, TextStatus, ErrorThrow) {
console.log(JQXHR);
console.log(TextStatus);
console.log(ErrorThrow);
}
})
}
PHP:
<?php
include_once('confi.php');
error_reporting(E_ALL);
if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);
$sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";
$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);
$data2=array();
while ($row = mysqli_fetch_row($result))
{
$data2[]=$row;
}
echo "{data:" .json_encode($data2). "}" ;
}
?>
Thanks for any help that you can provide.
EDIT: Forgot to put my browser network, here it is.
http://puu.sh/uzI4f/a9ed1e0be5.png
EDIT2: I've split the PHP script into two seperate files, and tries to use a session variable to pass the needed key as suggested in the comments. Yet I am still getting the same error. Hereby the two new PHP files:
This one is used to send the key from Jquery to PHP:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_POST['teller']))
{
$teller = mysqli_real_escape_string($conn,$_POST['teller']);
$_SESSION['teller'] = $teller;
}
?>
This one is used to get the needed information:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_SESSION['teller']))
{
$sql2='SELECT sta_stand,sta_datum FROM stand WHERE teller_id ="' .$_SESSION['teller'].'"' ;
$result = $conn -> query($sql2);
//$query2 = mysql_query($sql2) or trigger_error(mysql_error()." ".$sql2);
$data2=array();
while ($row = $result-> fetch_row())
{
$data2[]=$row;
}
echo json_encode($data2);
}
?>
First, some warnings (in accordance with this link):
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Don't believe it?
You should test against the session variable in your second script, which should look like this:
<?php
include_once('confi.php');
error_reporting(E_ALL);
session_start();
if (isset($_SESSION['teller']))
{
$teller = $_SESSION['teller'];
$sql2="SELECT sta_stand,sta_datum FROM stand WHERE teller_id = '$teller'";
$result = $conn -> query($sql2);
$data2=array();
while ($row = mysqli_fetch_row($result))
{
$data2[]=$row;
}
echo json_encode(['data'=> $data2]);
}
?>
Please note that I am also appending the 'data' properly to the JSON instead of just trying to "glue" (as said by Denis Matafonov) the JSON string together.
Dont try to glue data to string, like this:
echo "{data:" .json_encode($data2). "}" ;
Use simple
echo json_encode(['data'=> $data2]);
It should produce the same result if everything goes right, but wouldnt break up json if your $data2 is null
Declare your $data2 in the begginng, before if statement:
$data2 = [];
if (isset($_POST['teller'])) {
//do stuff and redefine $data2 or fill it;
}
//always echo valid json, event if no $POST["teller"] has arrived
echo json_encode(['data' => $data2]);

Retrieve data from MySQL database after jQuery autocomplete

I have implemented on my site the jQuery autocomplete function which works well. However, I would like to use the result from the autocomplete to retrieve the selected person's telephone number from the database.
The database structure is this;
id | name | type | tel | mobile | email | level
===============================================
1 | John Smith | judge | 01234 567890 | 07812 345678 | jsmith#example.com | BS Two Star
Here is my updated code so far
Autocomplete function
<script>
jQuery(document).ready(function($) {
$('#inputChiefJudge').autocomplete({
source:'lookups/shows-sj-searchforjudge.php',
change: function (event, ui) {
$.ajax({
type: POST,
url: 'lookups/shows-sj-findtel.php',
data: 'id='+ id,
success: function(data) {
details = $.parseJSON(data);
$('#inputChiefJudge').text("hello");
$('#chiefjudgetel').text(details);
},
});
},
minLength:2});
});
</script>
lookups/shows-sj-findtel.php
<?php
include("config.php");
mysql_connect ($DbHost, $DbUser, $DbPass);
mysql_select_db ("equilive_manager");
$id = $POST["id"];
$result = mysql_query("SELECT tel, mob FROM officials WHERE id='{$id}'");
$judgerow = mysql_fetch_array($result, MYSQL_ASSOC);
$contactdetails[] = array(
'tel' => $row['tel'],
'mob' => $row['mob'],
);
echo json_encode($data);
flush();
?>
lookups/shows-sj-searchforjudge.php
<?php
// if the 'term' variable is not sent with the request, exit
if ( !isset($_REQUEST['term']) ) exit;
// connect to the database server and select the appropriate database for use
include("../config.php");
mysql_connect ($DbHost, $DbUser, $DbPass) or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("equilive_manager");
// query the database table for name that match 'term'
$term = mysql_real_escape_string($_REQUEST['term']);
$rs = mysql_query("SELECT id, name, level FROM officials WHERE name LIKE '%{$term}%' ORDER BY name LIMIT 0,10");
// loop through each name returned and format the response for jQuery
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['name'] .', '. $row['level'],
'value' => $row['name'],
'id' => $row['id'],
);
}
}
// jQuery wants JSON data
echo json_encode($data);
flush();
Thanks in advance,
Craig
You have one issue at least in the code, which is that in getChiefJudgeContactDetails() you're mixing javascript with php. Mixing the two works fine if it's the first time you output a page and the code is on a PHP page. But if you're expecting the javascript to run PHP code every time a change event is triggered from the auto-complete, then that won't work.
Use the select event as others have stated, inside that, make a ajax request to a similar end point as your autocomplete but send it the value of your option (e.g. the ID value 2). Then use SQL in a PHP script to fetch the row for that id and return it as a json object. Parse the result and update UI in the jquery ajax call result handler.
update:
Change your autocomplete to look like this
<script>
jQuery(document).ready(function($) {
$('#inputChiefJudge').autocomplete({
source:'lookups/shows-sj-searchforjudge.php',
select: function (event, ui) {
$.ajax({
type: POST,
url: 'lookups/shows-sj-findtel.php',
data: {id:id},
success: function(data) {
details = $.parseJSON(data);
$('#inputChiefJudge').text("hello");
$('#chiefjudgetel').text(details);
},
});
},
minLength:2});
});
</script>
Instead of using the change option of the autocomplete, use select (as stated by other answers to your question). Also, instead of using a string ("id="+id) as your data, use a js object ({id:id}). jquery will handle serializing it correctly before sending to the server, the result being that it actually shows up as a post variable in your php script.
Also, as more of a side note, I would suggest looking into using the PDO driver (http://www.php.net/manual/en/pdo.prepare.php) to access your database instead of using the mysql_* commands. It's object oriented and also automatically provides safety features that are not available in the old commands, such as prevention of SQL injection attacks.
You can do it in select option of autoComplete.
All you need to do is send new ajax request to get selected person number.
select: function (event, ui)
{
//make $.ajax request and send selected value.
//you can send selected value using => ui.item.value
}
You should use the "select" event of the autocomplete:
http://api.jqueryui.com/autocomplete/#event-select

Returning a JSON object from PHP in AJAX call?

Here's my PHP code called during jQuery AJAX call:
<?php
include '../code_files/conn.php';
$conn = new Connection();
$query = 'SELECT Address_1, Address_2, City, State, OfficePhone1, OfficePhone2, Fax1, Fax2, Email_1, Email_2
FROM clients WHERE ID = ?';
$conn->mysqli->stmt_init();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('s', $_POST['ID']);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo json_encode($row);
?>
And the client-side code is:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
// Result
}
);
The AJAX call is successfully completed. I get the value of Result as
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road",.....and so on
What I want is to be able to use the values returned like Result.Address_1, Result.Address_2 and so on. But I can't do it using the above code. I tried using $row = $result->fetch_object() and $row = $result->fetch_array(), but no use.
And I know that this can be done by this code on the server side:
$row = $result->fetch_assoc();
$retVal = array("Address_1"=>$row['Address_1'], "Address_2"=>$row['Address_2'].......);
echo json_encode($retVal);
or
$row = $result->fetch_object();
$retVal = array("Address_1"=>$row->Address_1, "Address_2"=>$row->Address_2.......);
echo json_encode($retVal);
Is there a way to send the $row directly to the client side JavaScript and ready to be used as JSON object, without manually creating an array first?
The response you are getting from your PHP script is in plain text. You can however parse that string into an object using $.parseJSON in your callback function:
$.ajax({
url : url,//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
type : 'post',
success : function(Result){
var myObj = $.parseJSON(Result);
//you can now access data like this:
//myObj.Address_1
}
}
);
You can let jQuery do this for you by setting the dataType property for your AJAX call to json:
$.ajax({
url : url//note that this is setting the `url` property to the value of the `url` variable
data : {ID:$('#ddlClients').val()},
dataType : 'json',
type : 'post',
success : function(Result){
//you can now access data like this:
//Result.Address_1
}
}
);
The above examples expect that the response from the server to be in this format (from your question):
"{"Address_1":"Divisional Office 1","Address_2":"The XYZ Road"}
In your $.post call, the last argument could be the data-type: json:
$.post(url, {ID:$('#ddlClients').val()},
function(Result){
alert(Result.Address_1);
},'json'
);
Everything should work then, as it looks like you are doing everything right.
json_encode accepts objects, so there's no need to do that automatic array-building.:
$row = $result->fetch_object();
echo json_encode($row);
It's as simple as that!

Get JSON data FROM a PHP/MySQL query into a html tag using jquery

Hi guys I´m new at stackoverflow and also new at Jquery
Well hope I can make myself understandable. Here is what I want: I have made a query to my MySQL db, using a class with PHP
public function User($id) {
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$arr[]=array(
'id'=>$values['idUsers'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
'lname2'=>$values['lname2'],
'email'=>$values['email'],
'phone'=>$values['phone'],
'address'=>$values['address'],
'bday'=>$values['bday'],
'password'=>$values['password']
);
}
echo '{"user":'.json_encode($arr).'}';
}
Then I have a php code where I call this function
$name = $user->User($id);
I think this works ok (if I´m wrong please help). Now what I´m really trying to do is getting the values from the JSON array into specific divs, example:
$.getJSON("user.php",function(data){
$.each(data.user, function(i,user){
name = user.name;
$(name).appendTo('#getname');
});
});
And inside my HML i Have a <p id="getname"></p>wich is the tag I want the value to be displayed
But no value is displayed, why?, what am I doing wrong?
Thanks for the help I apreciate it
Your JSON is malformed. You are appending a bunch of objects {.1.}{.2.}{.3.}. Instead, try {"users":[{.1.},{.2.},{.3.}]}.
In PHP you'll do something like this (note that I've changed the response type to JSON-P rather than JSON by adding a callback parameter):
public function User($id) {
$users = array();
$this->connect_db_web($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='".$id."'");
while ($values = mysql_fetch_array($sql)) {
$users[] = array(
'id'=>$values['idUsers'],
'name'=>$values['name']
// etc.
);
}
$obj['users'] = $users;
$callback = (empty($_GET["callback"])) ? 'callback' : $_GET["callback"];
echo $callback . '(' . json_encode($obj) . ');';
}
Then you'll be able to do:
$.getJSON("user.php?callback=",function(data){
$.each(data.users, function(i,user){
$('#getname').append(user.name);
});
});
probably safer to do like this:
echo json_encode(array("user" => $arr));
on the other end you would receive an object which, I would suggest iterating like this:
var k;
for (k in data.user){
$("#getname").append($("<span></span>").html(data.user[k].name));
}
Given that you are fetching information for one user only, following I would suggest
$id = (int) $_GET["id"]; // or wherever you get it from.
if ($r = $db->mysql_fetch_assoc()){
$response = array(
"name" => $r["name"];
);
echo json_encode($response);
} else {
echo json_encode(array("error" => "Could not get name for user " . $id));
}
Then, on front-end, all you need to do is:
if (typeof(data.name) != "undefined"){
$("#getname").html(data.name);
} else if (typeof(data.error) != "undefined"){
$("#getname").html(data.error); //or handle otherwise
}
You've misinterpreted your JSON structure. You're appending your DB rows to an array, and embedding that inside an object. If you'd do a console.log(user) inside your .getJSON call, you'd see you'll have to do:
user[0].name
instead. As well, your code assumes that the user ID exists, and returns data regardless of how many, or how few, rows there actually are in the result set. At minimum your JS code code should check users.length to see if there ARE are any rows to begin with. Beyond that, unless you're doing it in another section of code somewhere, that $id value is probably coming from the web page, which means your query is vulnerable to SQL injection attacks.
OK got it,
was a php code error and JSON structre as marc said, here I´m gonna post what finally I had
PHP Class
public function User() {
$users = array();
$this->connect($conn);
$sql = mysql_query("SELECT * FROM users WHERE id='1'");
$values = mysql_fetch_array($sql);
$users[] = array(
'id'=>$values['id'],
'name'=>$values['name'],
'name2'=>$values['name2'],
'lname'=>$values['lname'],
...//rest of values
);
echo json_encode($users);
}
PHP module to get class
include"class.php";
$user = new Users();
$user->User();
Now how did I got the values using JQuery
$.getJSON('user.php', function(data){
$('wherever_you_want_to_point_at').text(data[0].name);
});
Hope it helps someone,
Thanks again guys, very very helpful
Take care you all

Categories