I'm getting a JSON array from server :
mysql_select_db('******') or die("Error connecting to db.");
$res = mysql_query("SELECT DISTINCT(valeur) as val FROM *****") or die(mysql_error());
while($r = mysql_fetch_assoc($res)){
$tab[] = $r['val'];
} echo json_encode($tab);
unset($tab);
And :
$.getJSON("autocomp.php?id=valeur", function(data){
$("#other-valeur").autocomplete({delay: 100, source: data, dataType: 'json'});
});
The server returns me a correct json array :
["UMTS","RAN","Swap","Regions","Brasseur",...]
But when i start typing something in the input, i get this message in firebug:
c is null
In the jquery code...
What i dont understand is that i'm doing the exact same thing for another input on the same page, and it work perfectly, the json array look the same, the code is the same...
It will not work because autocomplete need the property "id" and "value" in your json. this is not the case here.
Try to return the json like that :
[{"id":"1","value":"UMTS","comment":"umts comment"},
{"id":"2","value":"RAN","comment":"ran comment"},
{"id":"3","value":"Swap","comment":"swap comment"}]
in your php, also return a content type of : application/json
Related
How can I extract value from response?
Output of alert is [{"maturitydays":"120"}]
I only want value!!
$("#selectCrop").change(function(){ //this ajax will bring default configured crop data
var cropid = $("#selectCrop option:selected").val();
var url = "<?php echo base_url();?>index.php/user/cropConfig/getData";
$.ajax({
data : {'cropid':cropid},
type : 'post',
url : url,
success :function(response) {
alert(response);
}
})
});
It appears your response is inside an array due to the square brackets, this means you need to get the value through:
response[0]['maturitydays']
So your code will look like:
$("#selectCrop").change(function(){ //this ajax will bring default configured crop data
var cropid = $("#selectCrop option:selected").val();
var url = "<?php echo base_url();?>index.php/user/cropConfig/getData";
$.ajax({
data : {'cropid':cropid},
type : 'post',
url : url,
success :function(response) {
alert(response[0]['maturitydays']);
}
})
});
It's json.
Use json_decode to make it array then grab the value from the array (if you must).
$array = json_decode('{"maturitydays":"120"}',true);
$value=$array["maturitydays"];
Echo $value;
https://3v4l.org/Uc51m
The data that you get as response is a JSON array with a number of JSON objects. JSON (JavaScript object notation) can be used as a JavaScript object right away (as long as its not in string form, in which case it has to be parsed with JSON.parse).
When you receive the response you can access it as you would with a normal JavaScript array (in case you are sure its ALWAYS only 1 object, you can select the first index right away):
let obj = response[0];
When you got the object, just access the value you want as you would with a normal JavaScript object:
let val = obj.maturitydays;
i have an error in JSON.parse(), i have .php file which contain method to retrieve data from database and .js file for autoComplete function, my .php file return data as string and i need to convert it to object by using JSON.parse().
this is my php file
<?php
include_once("database_conn.php");
function request($conn)
{
$eventstArray = array();
$events = "SELECT *
FROM te_events,te_category,te_venue
WHERE te_events.venueID = te_venue.venueID
AND te_events.catID = te_category_catID
ORDER BY 1
";
$eventsQuery1 = mysqli_query($conn,$events) or DIE (mysqli_error($conn));
while($eventsQuery2 = mysqli_fetch_array($eventsQuery1))
{
$eventstArray[] = array
(
'label' => $eventsQuery2['eventTitle'];
'venue' => $eventsQuery2['venueName'];
'category' => $eventsQuery2['catDesc'];
'price' => $eventsQuery2['eventPrice'];
'description' => $eventsQuery2['eventDescription'];
);
}
return json_encode($eventstArray);
}
echo request($conn);
?>
and this is my autoComplete.js file
$(document).ready(function()
{
'use strict';
$.ajax
({
method: "get",
url: "requestOffer.php"
})
.done(function(data)
{
var offers = JSON.parse(data);
// now we have the data attach the autocomplete
$('#EOffers').autocomplete
({
minLength:3,
source: offers,
select: function(event, ui)
{
$('#chosenEvent').text(ui.item.label);
$('#chosenEvent').text(ui.item.vanue);
}
});
});
});
i can't remove the JSON.parse() because i need that to convert from string to object, hope someone can help me to solve this and i really appreciate that.
The error is within your server side, when there's an error on your server side, the response comes with html tags '<' when there's an error php will add tag with the error message. Therefore your json contains the html tags and becomes invalid because of unexpected tags.
The error is within this array
$eventstArray[] = array
(
'label' => $eventsQuery2['eventTitle'];
'venue' => $eventsQuery2['venueName'];
'category' => $eventsQuery2['catDesc'];
'price' => $eventsQuery2['eventPrice'];
'description' => $eventsQuery2['eventDescription'];
);
it should be
$eventstArray[] = array(
'label' => $eventsQuery2['eventTitle'],
'venue' => $eventsQuery2['venueName'],
'category' => $eventsQuery2['catDesc'],
'price' => $eventsQuery2['eventPrice'],
'description' => $eventsQuery2['eventDescription']
);
(The problem source was the semi-colon(;) after the description value.
It should be only at the end of array)
That error is normally seen when the value given to JSON.parse is actually undefined. So, I would check the code that is trying to parse this - most likely you are not parsing the actual string shown here.
It's server side error. You can check the value returned from server(php code) using browser's developer tools like firefox and check the response message.
In addition, maybe you can remove JSON.parse() and add dataType: "json" inside the ajax function
Check if only the json encoded response is being thrown back only. If you do things like var dump in the php script make sure you comment it out as it also get attached to your javascript response
Check this option if you are sure that your php code is correct but the returned json string cannot be parsed.
I had a similar problem.
What I found was that my PHP code had been saved as UTF8 but without the No-BOM option.
That added three extra chars: ο»Ώ (hex: EF BB BF)
at the beginning of the file causing the returned json string to have those extra chars at the beginning.
here is how the beginning of my php file:
ο»Ώ < ?php include...
I am trying to assign a json array to a javascript array so that my JS functions can access the array.
So I have an ajax call to MySQL db to get a JSON array of data:
var data = [];
$.ajax({
type:"post",
url:"position.php",
dataType:'json',
success:function(jsonarray){
data=$.parseJSON(jsonarray);
}
});
position.php:
<?php
include 'dbconnect.php';
$sql = "SELECT pid, posX, posY FROM posTable;";
$result = $conn->query($sql);
$myrows = $result->num_rows;
$return=array();
if ($result->num_rows>0){
while($row=$result->fetch_assoc()){
$return[]=array((int)$row['pid'],(int)$row['posX'],(int)$row['posY']);
}
}else{
echo "[]";
}
echo json_encode($return);
$conn->close();
?>
This gives an output like this:
[[1,749,1000],[2,855,986],[3,955,946],[4,1037,934],[5,1111,912]]
And from this I want the following two dimensional array so that I can access its memebers in this form:
data[i][j]
data => [[1,749,1000],[2,855,986],[3,955,946],[4,1037,934],[5,1111,912]]
However when I execute the code I keep getting the following error:
Uncaught SyntaxError: Unexpected token , in JSON at position 1
What am I doing wrong?
jQuery will automatically parse a JSON response before populating the success function's first argument.
$.parseJSON(jsonarray); calls toString() on your array and then tries to parse it as JSON, which it isn't (because Array.prototype.toString() doesn't convert to JSON).
Just don't try to parse it again.
I'm creating a json in javascript in that way
jsonArr.push({
position: 'WN',
wind: windWN,
wave: waveWN,
sea: seaWN
});
var myJsonString = JSON.stringify(jsonArr);
I'm sending it via an AJAX method with jsonData: jsonData:Ext.encode(myJsonString)
My json array looks like that when I send it :
In PHP side, I'm getting the Json and decoding it that way :
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata, true);
I tried print_r( $rawpostdata2[1]); and got '{', as the second character of the "string", and I can't understand why.
In the other side, I tried print_r($rawpostdata), cut/past the result in a $string and retest my json_decode like that :
$rawpostdata = file_get_contents("php://input");
// print_r($rawpostdata);
$string = '[{"position":"N","wind":"2","wave":"65","sea":"65"},{"position":"E","wind":"3","wave":"5","sea":"6"},{"position":"S","wind":"56","wave":"4","sea":"8"},{"position":"W","wind":"1","wave":"56","sea":"84"},{"position":"NE","wind":"5","wave":"6","sea":"65"},{"position":"ES","wind":"6","wave":"45","sea":"6"},{"position":"SW","wind":"69","wave":"8","sea":"4"},{"position":"WN","wind":"7","wave":"8","sea":"56"}]';
$rawpostdata2 = json_decode($string,true);
print_r ($rawpostdata2[1]);
It gives me the correct result !
Array (
[position] => E
[wind] => 3
[wave] => 5
[sea] => 6 )
Do you have some explanations?
EDIT : I make it working by making another json_decode
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata,true);
$rawpostdata3 = json_decode($rawpostdata2,true);
But I don't really understand...
First, you create json string:
var myJsonString = JSON.stringify(jsonArr);
Then you encode the resulting string into json again:
Ext.encode(myJsonString)
Thus, you have to json_decode() twice in PHP.
Try using $_POST instead of file_get_contets() which gives you a string.
you need to do a type cast on the result of json_decode like this:
<?php
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = (array) json_decode($rawpostdata,true);
?>
I hope this works for you.. Cheers..!!
In page load I am calling this function
function myFunction(selectedCinemaID) {
$.ajax({
type: "POST",
url: "show_details.php",
data: {cinema_id: selectedCinemaID }
}).done(function( show_list ) {
console.log(show_list.length);
});
And my code in show_details.php
$query = "SELECT * FROM `show` WHERE cinema_id=2;";
$result = mysql_query($query);
if($result){
$show_list = array();
while($row = mysql_fetch_array($result)){
array_push ($show_list, array($row['id'], $row['cinema_id'], row['show_time']));
}
echo json_encode($show_list);
} else {
echo mysql_error();
}
In my database I have only two row and three column but the length showed in the console is 64. But according to the database length should be 2. console.log(show_list) output [["2","2","2014-11-01 01:00:00"],["3","2","2014-11-01 04:00:00"]] but it seems everything here is treated as an array element or string. What is wrong in this code?
You haven't told jquery that you're sending JSON. As such, it'll treat the json text that the server is sending as text. That means
console.log(show_list.length);
is outputting the length of the json string, not the count/size of the array you're building in PHP.
You need either
$.getJSON(....);
or
$.ajax(
dataType: 'json'
...
)
However, note that if your mysql query fails for any reason, then outputting the mysql error message as your are will cause an error in jquery - it'll be expecting JSON, and you could potentially be sending it a mysql error message, which is definitely NOT json.
Once you switch to JSON mode, you should never send anything OTHER than json:
if (query ...)
output json results
} else {
echo json_encode(array('error' => mysql_error()));
}
The JavaScript function .length is counting the length of the entire serialized array string. You need to parse it first:
.done(function( show_list ) {
var data = JSON && JSON.parse( show_list ) || $.parseJSON( show_list );
console.log( data.length );
});
Thanks,
Andrew