parsing and looping through json data - php

I have been working on this code for some time now and have researched on various solutions on how to solve it, but i have found none.
I am getting the following json data:
{"id":"4","name":"bugatti","details":"the bugatti v8 simplly the best","seats":"2","status":"0","image"
:"","category":"sedean"}{"id":"5","name":"bently","details":"the bently the best of the best","seats"
:"5","status":"0","image":"","category":"SUV"}
I'm having trouble parsing that json data which I get from the jquery ajax $.post request as shown below:
$.post('response.php',
{
task : 'fleet'
},
function(data)
{
data = $.parseJSON(data);
$.each(data , function (key,value)
{
console.log(value);
});
console.log(data.id);
}
).error(
function()
{
}
).success(
);
Here is the response.php data:
if(isset($_POST['task']) && $_POST['task'] == 'fleet')
{
$car = new Cars();
$fleet = $car->getAll();
foreach( $car->data() as $cars )
{
echo json_encode($cars);
}
}
What could be the problem?

I would do something like this
You can also add dataType: 'json' to your $.post function.
// making sure we pass the header for the json output
header('Content-Type: application/json');
// if $car->data() (is the array, just encode it to json)
echo json_encode($car->data());
I ran some examples with your code (without the ajax)
var data = '{"id":"4","name":"bugatti","details":"the bugatti v8 simplly the best"}';
data = $.parseJSON(data);
$.each(data , function (key,value)
{
console.log(value);
});
// key will output id, name, details..
// value will output (what is below)
output :
4
bugatti
the bugatti v8 simplly the best
(remove value.id and just say value)
If you wanted to confirm the param, you can easily do
if (key == 'id')

Related

Passing a jQuery array to PHP (POST)

I want to send an array to PHP (POST method) using jQuery.
This is my code to send a POST request:
$.post("insert.php", {
// Arrays
customerID: customer,
actionID: action
})
This is my PHP code to read the POST data:
$variable = $_POST['customerID']; // I know this is vulnerable to SQLi
If I try to read the array passed with $.post, I only get the first element.
If I inspect the POST data with Fiddler, I see that the web server answers with "500 status code".
How can I get the complete array in PHP?
Thanks for your help.
To send data from JS to PHP you can use $.ajax :
1/ Use "POST" as type, dataType is what kind of data you want to receive as php response, the url is your php file and in data just send what you want.
JS:
var array = {
'customerID': customer,
'actionID' : action
};
$.ajax({
type: "POST",
dataType: "json",
url: "insert.php",
data:
{
"data" : array
},
success: function (response) {
// Do something if it works
},
error: function(x,e,t){
// Do something if it doesn't works
}
});
PHP:
<?php
$result['message'] = "";
$result['type'] = "";
$array = $_POST['data']; // your array
// Now you can use your array in php, for example : $array['customerID'] is equal to 'customer';
// now do what you want with your array and send back some JSON data in your JS if all is ok, for example :
$result['message'] = "All is ok !";
$result['type'] = "success";
echo json_encode($result);
Is it what you are looking for?

$.post function is not returning the correct data

I'm using $.post to deliver data to my main page from droppable elements. Yet when I echo out the the data I'm getting my toolbar echoed out to me as well as the data I fetched.
if (isset($_POST['data'])){
$data = $_POST['data'];
echo $data;
The javascript containing the $.post is below
if(dropbox && dropbox1 !== ''){
$.post("account_main.php",
{data: $(this).text()},
function(data) {
$('#demo').html(data);
});
}
And a visual for the script using the droppable elements is HERE, but the problem is not shown here, can't duplicate it. I am open to any suggestions.
if (isset($_POST['data'])) {
echo $_POST['data'];
# Other stuff
exit; # Kill the script
}
If I understand your problem correctly, that should sort it :)
Just try :
if (dropbox && dropbox1 !== "") {
var url, params, callback;
url = "account_main.php";
params = {
"data": $(this).text()
};
callback = function(data) {
$("#demo").html(data);
}
$.post(url, params, callback, "html");
}
Please note that I would strongly advise you to use JSON for your response instead of HTML.
header("Content-type: application/json");
echo json_encode($my_result);
data: $(this).text()
$(this) refers to the $.post, I think that's not the data you want.

Display returned JSON objects with jQuery

I'm having trouble figuring out how to display some return JSON objects.
My script works like this:
I'm making an ajax call, sending some params to a CodeIgniter Controller where I'm processing it with a model, making some queries towards an database and then returning the json_encoded rows to the ajax callback function. This works great btw.
Here is what I want to do now and here its where I'm stuck. I want the new JSON objects (contains database rows) to "replace" the old rows in a html table. So I want it to update the table depending on the params I'm passing but only in the tbody mind.
I'm new at jquery so I've tried i few things. I've tried iterate trough the json data and use the $.html(string) function but i guess this replace everything and it will eventually just display the last object(Am i right?).
So I wonder how in a general sense I would do this?
$.ajax({
type: 'GET',
url: 'someSite.com/someEndpoint'
data: xyz.
success: function( response ) {
//lets say you have an object like this: object = { data: { ... } }
var html = '';
for(var i = 0; i<response.data.length; i++) {
html += '<tr><td>'+response.data[i].title+'</td></tr>';
}
$('#someTable tbody').html(html);
}
});
You don't have to return JSON objects in an AJAX request. Try setting the data_type config setting for the $.ajax call to "html" (or leave it blank--jQuery is really good about figuring it out from the response data).
I usually factor out the <tbody>...</tbody> portion of a view to its own view partial. Then, the "original" page load can use it, and so can an updating AJAX call.
The only asterisk to this is if you need some sort of object-oriented response along with the HTML. I would usually do something like this:
{
"stat": "ok",
"payload": "<tr><td>row1</td></tr><tr><td>row2</td></tr>"
}
And then in the ajax success function:
$.post('/controller/action', { some: 'data' }, function(response) {
$('#my_table tbody').append(response.payload);
}, 'json');
What are the params your passing in?
for example you might use a select or input field to trigger an ajax call and pass its value as the param.
var tableObj = {
var init : function(){
//check that your selectors id exists, then call it
this.foo();
},
foo : function(){
var requestAjax = function(param){
var data = {param : param}
$.ajax({
data : data,
success : function(callback){
console.log(callback);//debug it
$("tbody").empty();//remove existing data
for(var i =0; i < callback.data.length; i++){}//run a loop on the data an build tbody contents
$("tbody").append(someElements);//append new data
}
});
}
//trigger event for bar
$("#bar").keyup(function(){
requestAjax($(this).val());
});
}
}
$(function(){
tableObj.init();
})
Your php method
public function my_method(){
if($this->input->is_ajax_request())
{
//change the output, no view
$json = array(
'status' => 'ok',
'data' => $object
);
$this->output
->set_content_type('application/json')
->set_output(json_encode($json));
}
else
{
show_404();
}
}

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');

JSON returned as individual string and not objects

I am using Codeigniter and trying to use the jQuery autocomplete with it. I am also using #Phil Sturgeon client rest library for Codeigniter because I am getting the autocomplete data from netflix. I am return correct JSON and I can access the first element with
response(data.autocomplete.autocomplete_item[0].title.short);
but when I loop through the results
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short)
}
it acts like a string. Lets say the result is "Swingers", it will return:
Object.value = s
Object.value = w
Object.value = i
and so on.
the js:
$("#movies").autocomplete({
source: function(request, response) {
$.ajax({
url: "<?php echo site_url();?>/welcome/search",
dataType: "JSON",
type:"POST",
data: {
q: request.term
},
success: function(data) {
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
}
});
}
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
$(ul).attr('id', 'search-autocomplete');
return $("<li class=\""+item.type+"\"></li>").data( "item.autocomplete", item ).append(""+item.title+"").appendTo(ul);
};
the controller:
public function search(){
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// set var equal to results
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'));
//$this->rest->debug();
//$json_data = $this->load->view('nice',$data,true);
//return $json_data;
echo json_encode($netflix_query);
}
the json return
{"autocomplete":
{"autocomplete_item":[
{"title":{"short":"The Strawberry Shortcake Movie: Sky's the Limit"}},
{"title":{"short":"Futurama the Movie: Bender's Big Score"}},
{"title":{"short":"Daffy Duck's Movie: Fantastic Island"}}
...
any ideas?
thanks.
there are some console logs with the return
the url
in, as you've noticed, doesn't do what you'd like with arrays. Use $.each
As far as I know, for (property in object) means that you want to access each of its properties rather than accessing them via the index. If you want to access them via the index, you probably want to use the standard for loop.
for (i = 0; i <= 10; i++) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
or if you still want to use your code, try this:
for (i in data.autocomplete.autocomplete_item) {
response(i.title.short);
}
I haven't test them yet but I think you have the idea.
ok I figured out the correct format that I need to send to the autocomplete response method:
the view
$("#movies").autocomplete({
minLength: 2,
source: function(request, response) {
$.post("<?php echo base_url();?>welcome/search", {q: request.term},
function(data){
//console.log(data);
response(data);
}, 'json');
}
});
the controller:
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// Pull in an array
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'),'json');
$json = array();
foreach($netflix_query->autocomplete->autocomplete_item as $item){
$temp = array("label" => $item->title->short);
array_push($json,$temp);
}
echo json_encode($json);
what was needed was to send back to the view an array of objects. Thank you guys for all your answers and help!!

Categories