Json eval not able to parse data - php

I have a php program where I just test some sample data. I am getting error as missing ] after element list. How can I read this?
$dataDetailsList = array();
array_push($dataDetailsList, array('a' =>'1','b' =>'2','c' =>'3','d' =>'4','e' =>'5'));
echo json_encode(array("DataDetailsList"=>$dataDetailsList));
Then in my jQuery processor I am doing like this.
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(data) {
//alert(json);
var jsonData = eval(" (" + data + ") ");
},
cache: false
});

function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(data) {
//alert(json);
var jsonData = data;
},
cache: false,
dataType: 'json' //data type that it will return
});
}

Don't use eval is evil.
Instead of this use:
JSON.parse(data); // not supported in IE7 and below
I think you need to try
dataType: 'json'
That is,
$.ajax({
url: 'live-server-data.php',
dataType: 'json',
success: function(data) {
var jsonData = data;
console.log(jsonData);
$.each(jsonData.DataDetailsList, function(key, val) {
var key = Object.keys(val)[0],
value = val[key];
console.log(key); // output: a, b, c ...
console.log(value); // output: 1, 2, 3,...
// alternative
for(var key in val) {
console.log(key);
console.log(val[key]);
}
});
},
cache: false
})

You should just set the dataType to json and jQuery will do the trick for you..
$.ajax({
url: 'live-server-data.php',
dataType: 'json', //Added dataType json
success: function(data) {
//Now data is a javascript object (JSON)
},
cache: false
});

Related

Json unable to pass array to php

As the title says, I failed to pass the data array via json ajax to php. I am using codeigniter, what did I do wrong? here is the jQuery code:
function load_page_data1(){
var data = [];
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Here is the php code:
function getdata(){
$parameter = '';
if(isset($_POST))
{
if(isset($_POST['val']))
{
$parameter = $_POST['val'];
} else
{
echo "failed!";
}
}
$this->load->model('Chart');
$this->load->helper('url');
$data1 = $this->Chart->getdata_solid($parameter);
echo json_encode($data1);
}
Final:
Guys, it turn out that the values did passed from jQuery to php, the problem is that I stupidly call the same php function twice within the javascript function, then the second time calling without posting the 'val', so that the php function error and stop.
Thank you all for your answers, at least I learn the different ways to passing data by using jQuery.
Don't make a array if it's not a array just make a object
var data = {};
data.val = "solid_t1";
// equivalent to
data ={val:"solid_t1"};
// equivalent to
data['val'] ="solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
Update 1: if you need to send array you need to make a proper array object like below
Example :
var data=[];
item ={val:'value'};
data.push(item);
var new_data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: new_data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
For Debugging :
May be problem with your server side code .so for the testing purpose comment all the line in function just do this echo json_encode($_POST); and in your ajax success function just add console.log(output); and let me know the result.
create one json object
jsonObj = [];
create array list as per your need
item = {}
item ["val"] = "solid_t1";
push the array list in to the json.
jsonObj.push(item);
Please have a try like this. It is working in my case.
Your full code will be like
function load_page_data1(){
jsonObj = [];
item = {}
item ["val"] = "solid_t1";
jsonObj.push(item);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
The another way to use this is given below.
function load_page_data1(){
var jsonObj = {};
jsonObj["val"] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Instead of var data = []; use var data = {}; to initialize your data. It should solve your problem.
Your data wasn't being passed as json, now it will.
Code will be:
function load_page_data1(){
var data = {};
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/welcome/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
One more suggestion please use CI input library for post request in controller.
e.g.
$parameter = $this->input->post('val');

Json on input instead of autocomplet

$('#lev_nr').on('input', {
source: function(request, response) {
$.ajax({
url : 'pallavvikelse/jsonData',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'lev_table',
row_num : 1
},
success: function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 1,
select: function(event, ui) {
var names = ui.item.data.split("|");
$('#lev_namn').val(names[1]);
var txt = $('#avta').val(names[2]);
if (txt.val() == "ja"){
$('#t').hide();
}
} }).trigger('input');
Can someone see why this does not work?
I am trying to change autocomplete function to on.input but I can't get it to work.
The code works perfectly when i change the first line to $('#leverantors_nr').autocomplete({
and when I remove .trigger('input')
$('#lev_nr').on('input', function() {
$.ajax({
url: 'pallavvikelse/jsonData',
data: {
name_startsWith: this.value,
type: 'country_table',
row_num: 1
},
dataType: 'json',
success: function(data) {
alert(data);
var names = data.split('|');
alert(names[0]);
}
});
});
I have managed to make it work this far, but when i try to alert(names[0]) i get nothing when alert(data) i get resault.. The data i get loocks like this: 5000950|TEST|BLABLA
Wen i try to split and alert again it dosent work
$('#leverantors_nr').on('input', function() {
$.ajax({
url: 'pallavvikelse/jsonData',
data: {
name_startsWith: this.value,
type: 'country_table',
row_num: 1
},
dataType: 'json',
success: function(data) {
alert(data.lev_namn);
}
});
});
Problem solved:
i changed the database so it outputs array like this:
$arr['lev_nr'] = $row->lev_nr;
$arr['lev_namn'] = $row->lev_namn;
I think you are not properly parsing JSON data.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

access the json encoded object returned by php in jquery

I want to post some data to php function by ajax, then get the encoded json object that the php function will return, then I want to get the information (keys and values) from this object, but I don't know how, here is my code:
$.ajax({
url: "functions.php",
dataType: "JSON",
data: {id: id},
type: 'POST',
success: function(json){
for(var i=0;i<json.length;i++){
alert(json['fname']);
}
}
});
and here is the json object returned:
[{"id":"1","fname":"kjhkj","mname":"kjhjh","lname":"lname","prefix":"Mr.","suffix":"jhkjhk","email":"hf#dd.com","image":"11281454_423648214427141_318277024_o.jpg","info":"hjgvhd"}]
Try:
$.ajax({
url: "functions.php",
dataType: "JSON",
data: {id: id},
type: 'POST',
success: function(json){
for(var i=0;i<json.length;i++){
alert(json[i].fname);
}
}
});
It is rather simple to do this:
var data = jQuery.parseJSON(json);
jQuery.each(data, function(i, item) {
jQuery('.derp').append(item.mname + "<br />");
});
Example
Reference
jQuery.each()
jQuery.parseJSON()

ajax link json datatype call

I want to send the data via ajax to other page. I have isolated the problem. This is the code.
Thank you all for your help..But no effect..
updated code
It worked...
<script>
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
var size=123;
var itemname=123;
var potency=123;
var quantity=12333;
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
</script>
So I click the link,it navigates, to dd.php which has
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']));
echo $_POST['itemname'];
?>
I get Object Object as alert. What am doing wrong? Pls throw some light here..thanks you..
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault();
var data = {"box":1233,
"size":565,
"itemname":565,
"potency":876,
"quantity":234};
$.ajax({
url: "dd.php",
type: "post",
data: data,
dataType: "json",
success: function(data) {
if(console){
console.log(data);
}
},
error: function(data) {
if(console){
console.log(data);
}
}
});
});
});
few things to consider... you can post data as object..which is clean and easier to use
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
....
var dataString ={'box':box,'size':size,'itemname':itemname,'potency':potency,'quantity':quantity};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json", //<--- here this means the response is expected as JSON from the server
success: function(data) {
alert(data.itemcode); //<--here alert itemcode
},
error: function(data) {
alert(data);
}
});
so you need to send the response as json in PHP
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Here you are using querystring as sent in GET request.
If you want to send the data in same form, you can use this with GET request type:
$.ajax({
url: "dd.php"+dataString,
type: "get",
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
Or for POST request,you will have to put data in json object form, So you can use :
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
});
And put echo in your php code :
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Javascript alert shows [Object object] for object. You can see response using console.log or can use that key with alert.
For more information, refer jQuery.ajax()

read JSON data from PHP with jQuery

I send an array from PHP with json_encode, and I trying to get with AJAX and jQuery.
Every thing is ok.
JSON structure is :
names{"p1":"John","p5":"Smith"}
jQuery code is :
$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
$(data.names).each(function(key, txt) {
alert(txt);
});
}
}
this code don't return any thing! I think browser don't enter in each
what should I do ?
instead this:
$(data.names).each(function(key, txt) {
alert(txt);
});
use this:
$.each(data.names, function(key, txt) {
alert(txt);
});
and your json seems to be incorrect as you mentioned: names{"p1":"John","p5":"Smith"}
this should be like this:
{
"names": {
"p1": "John",
"p5": "Smith"
}
}
you can check your json here: http://jsonlint.com/
I'd suggest you use jQuery's $.getJSON(); http://api.jquery.com/jQuery.getJSON/
But to answer your question directly; you didn't close your ajax() function.
$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
$(data.names).each(function(key, txt) {
alert(txt);
});
}
});
In your code you could just use parseJSON().
$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
var d = jQuery.parseJSON(data);
// ... do stuff
}
});

Categories