JSON.parse: unexpected character - php

I'm trying to pass a json from php jquery, after getting into an array of sql query and get the following javascript error.
JSON.parse: unexpected character
The function to return result of sql:
public function selectassocSql($sql){
$i = 0;
$resSelect = array();
mysql_query("SET NAMES 'utf8'");
$result = mysql_query($sql);
while ( $row = mysql_fetch_assoc($result) )
{
$resSelect[$i] = $row;
$i++;
}
mysql_free_result($result);
return $resSelect;
}
After use this function in this way,
$sql = "SELECT id, code, name FROM table WHERE code LIKE '%$codcli%' ";
$v = $data->selectassocSql($sql);
echo json_encode($v, JSON_FORCE_OBJECT);
And the javascript code is this:
$('#formclientes').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url:$(this).attr('action'),
data:$(this).serialize(),
success:function(data)
{
//console.log("SUCCESS " + data);
var json_cli = $.parseJSON(data);
}
})
})
How I can correct this error and how I can read a json from jquery?

You don't need the $.parseJSON call as jQuery automatically does it because if you don't specify a dataType property jQuery tries to guess it and calls the correct function to parse the response before the data is handled to the success function
$.ajax({
type: 'POST',
url:$(this).attr('action'),
data:$(this).serialize(),
success:function(data)
{
//console.log("SUCCESS " + data);
var json_cli = data;
}
})
check out also this question Why is 'jQuery.parseJSON' not necessary?

I just ran into this in FF10.0.2 with data that looked like:
[ { "firstName": 'Joe', "lastName": 'Smith' } ]
(with multiple objects in the array - shortened for clarity)
It actually parsed OK using eval, though, instead of JSON.parse. (I'm not using jQuery here.)
The problem went away when I changed ' to " for the values:
[ { "firstName": "Joe", "lastName": "Smith" } ]
I thought the " requirement was only for property names, not data values.

Related

how can I access json data from another url inside a html page

here is my php code which would return json datatype
$sql="SELECT * FROM POST";
$result = mysqli_query($conn, $sql);
$sJSON = rJSONData($sql,$result);
echo $sJSON;
function rJSONData($sql,$result){
$sJSON=array();
while ($row = mysqli_fetch_assoc($result))
{
$sRow["id"]=$row["ID"];
$sRow["fn"]=$row["posts"];
$sRow["ln"]=$row["UsrNM"];
$strJSON[] = $sRow;
}
echo json_encode($strJSON);
}
this code would return
[{"id":"1","fn":"hi there","ln":"karan7303"},
{"id":"2","fn":"Shshhsev","ln":"karan7303"},
{"id":"3","fn":"karan is awesome","ln":"karan7303"},
{"id":"4","fn":"1","ln":"karan7303"},
{"id":"5","fn":"asdasdas","ln":"karan7303"}]
But how can I access this data in html, that is, I want particular data at particular position for example i want to show 'fn' in my div and 'ln' in another div with another id
Before trying anything else I tried this
$.ajaxSetup({
url: 'exm1.php',
type: 'get',
dataType: 'json',
success: function(data){
console.log(data);
}
});
but it shows that data is undefined I don't know what I am doing wrong
What you've got should kind-of work if you swapped $.ajaxSetup (which is a global configuration method) with $.ajax. There are some significant improvements you could make though.
For example, your PHP does some odd things around the value returned by rJSONData. Here's some fixes
function rJSONData($result) {
$sJSON = array();
while ($row = mysqli_fetch_assoc($result)) {
$sJSON[] = array(
'id' => $row['ID'],
'fn' => $row['posts'],
'ln' => $row['UsrNM']
);
}
return json_encode($sJSON);
}
and when you call it
header('Content-type: application/json');
echo rJSONData($result);
exit;
Also make sure you have not output any other data via echo / print or HTML, eg <html>, etc
In your JavaScript, you can simplify your code greatly by using
$.getJSON('exm1.php', function(data) {
console.info(data);
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error(jqXHR, textStatus, errorThrown);
});
Use $.ajax instead of $.ajaxSetup function.
Here is a detailed answer from another SO post how to keep running php part of index.php automatically?
<script>
$.ajax({
// name of file to call
url: 'fetch_latlon.php',
// method used to call server-side code, this could be GET or POST
type: 'GET'
// Optional - parameters to pass to server-side code
data: {
key1: 'value1',
key2: 'value2',
key3: 'value3'
},
// return type of response from server-side code
dataType: "json"
// executes when AJAX call succeeds
success: function(data) {
// fetch lat/lon
var lat = data.lat;
var lon = data.lon;
// show lat/lon in HTML
$('#lat').text(lat);
$('#lon').text(lon);
},
// executes when AJAX call fails
error: function() {
// TODO: do error handling here
console.log('An error has occurred while fetching lat/lon.');
}
});
</script>

JSON_ENCODE converts all array values to string in AJAX Request

I execute a simple AJAX Request, where i select some data from a mysql database. When i pass my Array back to Javascript, it always converts all Values in my Array into String, doesn't matter if its datatype was integer or boolean in my database.
EDIT:
I just found out, that MySQLi always converts datatypes to string, so I guess thats the problem. json_encode works fine.. https://stackoverflow.com/a/5323169/4720149
SQL Statement
function getAll()
{
// Get all buildings
$db = new db();
$sql = "SELECT * FROM building";
$result = $db->runQuery($sql);
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
PHP Controller File
function getBuildings(){
$bu_db = new Building_Model();
$buildings = $bu_db->getAll();
echo json_encode($buildings);
}
Javascript file
var data = {
action: "getBuildings"
};
$.ajax({
type: "POST",
dataType: "json",
url: "controller/Building.php",
data: data,
success: function(data) {
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error in AJAX Request: " + textStatus + ", " + errorThrown);
}
});
Instead of keeping the original datatypes from the database, it turns all values into Strings:
Output
[Object, Object, Object, Object, Obje...]
>0: Object
>1: Object
>2: Object
>3: Object
ActiveCost: "20"
BuildEfc: "0"
BuildSfx: "0"
BuildingEfc: "0"
BuildingID: "1"
Name: "Vogtei I"
ResidentLvLNeeded: "0"
...
Does anybody know this problem?
Thanks in Advance.
What PHP version do you use?
Try:
echo json_encode($buildings, JSON_NUMERIC_CHECK );
Javascript has dynamic data types. So there is no specific data type for int string etc. same var object can hold all the data types. It will dynamically identify the type based on the operations you do on those variables.

returning an array from ajax call

trying to get 2 values from an ajax call, cant seem to breakup the results back form the call
the ajax
$.ajax({
type:'POST',
url: 'inc/getuser.php?q='+boxnum,
success:function(data){
alert(lname);
}
});
the php
$datas = $database->select("Drivers", "*", [
"id" => $q]);
if (count($datas)>0) {
foreach($datas as $data){
$fname=$data['first_name'];
$lname=$data['last_name'];
}
$rdata = array(
'fname'=> $fname,
'lname'=> $lname
);
echo $rdata; //$datas['first_name']
} else {
echo 'no datas';
}
trying to find the lastname only.
thank in advance
Jeff
Change to this:
$.ajax({
type:'POST',
dataType: 'json', // <-- specify that your return type should be JSON
url: 'inc/getuser.php?q='+boxnum,
success:function(data){
if (data.fname && data.lname) {
var firstName = data.fname;
var lastName = data.lname;
}
}
});
when working with arrays you need to use JSON data type.
Your PHP: echo json_encode($rdata);
You can use json_encode() function in your PHP file
echo json_encode($rdata);
Use json_encode() in PHP to serialize your data first as Paramore has explained.
In javascript your success function callback has a parameter of "data", "lname" is not defined in that context so to access fname and lname you need to do like so:
data.lname
data.fname

Reading JSON from database into combobox using jQuery .each()

I need to be able to select a country in a selectbox, and then get all the states from that country.
I'm trying to do something like this: how-to-display-json-data-in-a-select-box-using-jquery
This is my controller:
foreach($this->settings_model->get_state_list() as $state)
{
echo json_encode(array($state->CODSTA, $state->STANAM));
}
and my javascript:
$.ajax({
url: 'settings/express_locale',
type: 'POST',
data: { code: location, type: typeLoc },
success: function (data) {
console.log(data);
}
});
console.log shows me something like this:
["71","SomeState0"]["72","SomeState"]["73","SomeState2"]["74","SomeState3"]
So, what i need is to append all states in a new selectbox.
But I'm trying to read this array doing this in the success callback:
$.each(data, function(key,val){
console.log(val);
});
In the result, each line is a word, like this:
[
"
7
1
"
,
"
s
....
]
Why does that happen, and what am I missing?
JSON is not made of independent blocks. So this will never do:
foreach($this->settings_model->get_state_list() as $state)
{
echo json_encode(array($state->CODSTA, $state->STANAM));
}
The output will be treated as text, and the iterator will loop the object's elements... which are the single characters.
You need to declare a list, or a dictionary. I have included some examples, depending on how you use the data in the jQuery callback. Note: PHP-side, you may also need to output the proper MIME type for JSON:
$states = array();
foreach($this->settings_model->get_state_list() as $state)
{
// Option 1: { "71": "SomeState0", "72": "Somestate2", ... }
// Simple dictionary, and the easiest way IMHO
$states[$state->CODSTA] = $state->STANAM;
// Option 2: [ [ "71", "SomeState0" ], [ "72", "SomeState2" ], ... ]
// List of tuples (well, actually 2-lists)
// $states[] = array($state->CODSTA, $state->STANAM);
// Option 3: [ { "71": "SomeState0" }, { "72": "SomeState2" }, ... ]
// List of dictionaries
// $states[] = array($state->CODSTA => $state->STANAM);
}
Header('Content-Type: application/json');
// "die" to be sure we're not outputting anything afterwards
die(json_encode($states));
In the jQuery callback, you specify the datatype and content type with charset (this will come in handy as soon as you encounter a state such as the Åland Islands, where a server sending data in ISO-8859-15 and a browser running a page in UTF8 can lead to a painful WTF moment):
$.ajax({
url: 'settings/express_locale',
type: 'POST',
data: { code: location, type: typeLoc },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#comboId").get(0).options.length = 0;
$("#comboId").get(0).options[0] = new Option("-- State --", "");
// This expects data in "option 1" format, a dictionary.
$.each(data, function (codsta, stanam){
n = $("#comboId").get(0).options.length;
$("#comboId").get(0).options[n] = new Option(codsta, stanam);
});
},
error: function () {
alert("Something went wrong");
}
have you tried using $.map() instead?
http://api.jquery.com/jQuery.map/
$.map(data, function(index, item) {
console.log(item)
})
You should use GET not POST since you are not actually creating anything new serverside.
Read a bit about REST and why using GET is the proper noun here.
I've added a JSFiddle example that you can run straight away.
http://jsfiddle.net/KJMae/26/
If this is the JSON that the PHP service returns:
{
"success":true,
"states":[
{
"id":71,
"name":"California"
},
{
"id":72,
"name":"Oregon"
}
]
}
This is our HTML code:
<select id="country">
<option value="">No country selected</option>
<option value="1">USA</option>
</select>
<select id="states">
</select>​
This is what the code to add that to the select could look like:
// Bind change function to the select
jQuery(document).ready(function() {
jQuery("#country").change(onCountryChange);
});
function onCountryChange()
{
var countryId = jQuery(this).val();
$.ajax({
url: '/echo/json/',
type: 'get',
data: {
countryId: countryId
},
success: onStatesRecieveSuccess,
error: onStatesRecieveError
});
}
function onStatesRecieveSuccess(data)
{
// Target select that we add the states to
var jSelect = jQuery("#states");
// Clear old states
jSelect.children().remove();
// Add new states
jQuery(data.states).each(function(){
jSelect.append('<option value="'+this.id+'">'+this.name+'</option>');
});
}
function onStatesRecieveError(data)
{
alert("Could not get states. Select the country again.");
}​
As for the PHP, here's a simple example that should give the same result as JSON used in example above. (Haven't tested it, from top of my head, no php here.)
$result = new stdClass;
$result->states = array();
foreach($this->settings_model->get_state_list() as $state)
{
$stateDto = new stdClass();
$stateDto->id = $state->CODSTA;
$stateDto->name = $state->STANAM;
$result->states[] = $stateDto;
}
$result->success = true;
die(json_encode($result));

Iterate over json array using jquery

There have been some post with my similar problem: How do I iterate over a JSON array using jQuery/AJAX call from PHP? but not quite the same.
I'm getting and error from jquery:
a is null
It is because of the code I've added to loop through the json data:
$(function ()
{
$.ajax({
url: 'ajax_dashboard/api.php', //the script to call to get data
data: "",
dataType: 'json',
success: function(data)
{
$.each(data, function() {
$.each(this, function(k, v) {
$('#output').append("<b>key: </b>"+k+"<b> value: </b>"+v)
.append("<hr />");
});
});
}
});
});
And here is the php file (which I did verify gives valid JSON format):
$query_camera_name = "SELECT camera_name, camera_status, camera_quality, email_notice, camera_hash, camera_type FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
echo json_encode($result_cameras);
?>
This returns this json formatted data:
[
{
"camera_name": "ffgg",
"camera_status": "DISABLED",
"camera_quality": "MEDIUM",
"email_notice": "DISABLED",
"camera_hash": "0d5a57cb75608202e64b834efd6a4667a71f6dee",
"camera_type": "WEBCAM"
},
{
"camera_name": "test",
"camera_status": "ENABLED",
"camera_quality": "HIGH",
"email_notice": "ENABLED",
"camera_hash": "6ab000ef7926b4a182f0f864a0d443fc19a29fdd",
"camera_type": "WEBCAM"
}
]
If I remove the loops the "a is null" error is gone. What am I doing wrong?
Your iteration code works just fine: http://jsfiddle.net/SuyMj/
The error is elsewhere.
Edit:
Try this to help debug.
success: function(data, textStatus, xhr) {
console.log(xhr);
...
}
xhr will contain a lot of information about the request being made. What does the responseText contain? What is the statusText?
Your code works fine:
http://jsfiddle.net/QSvNy/
So the error is not there.
I don't see that you set the Content-Type of your response from php. Possibly the mime type of your response is incorrect and so jQuery does not parse the response as json.
Try this in your php before you echo your json:
header('Content-Type: application/json');

Categories