jQuery parse/display json data from php json_encode - php

Initial .ajax call in jquery:
$.ajax({
type: 'post',
url: 'items_data.php',
data: "id="+id,
dataType: 'json',
success: function(data){
if(data){
make_item_rows(data);
}else{
alert("oops nothing happened :(");
}
}
});
Sends a simple string to a php file which looks like:
header('Content-type: application/json');
require_once('db.php');
if( isset($_POST['id'])){
$id = $_POST['id'];
}else{
echo "Danger Will Robinson Danger!";
}
$items_data = $pdo_db->query ("SELECT blah blah blah with $id...");
$result_array = $items_data->fetchAll();
echo json_encode($result_array);
I am catching the $result_array just fine and passing it on to another function. I double checked that there is indeed proper values being returned as I can just echo result to my page and it displays something like the following:
[{"item_id":"230","0":"230","other_id":"700"},{"item_id":"231","0":"231","other_id":"701"},{"item_id":"232","0":"232","other_id":"702"}]
I am having trouble figuring out how to iterate through the results so I can inject values into a table I have in my HTML. Here is what I have for my function:
function make_item_rows(result_array){
var string_buffer = "";
$.each(jQuery.parseJSON(result_array), function(index, value){
string_buffer += value.item_id; //adding many more eventually
$(string_buffer).appendTo('#items_container');
string_buffer = ""; //reset buffer after writing
});
}
I also tried putting an alert in the $.each function to make sure it was firing 3 times, which it was. However no data comes out of my code. Have tried some other methods as well with no luck.
UPDATE: I changed my code to include the parseJSON, no dice. Got an unexpected token error in my jquery file (right when it attempts to use native json parser). Tried adding the json header to no avail, same error. jquery version 1.9.1. Code as it is now should be reflected above.

Set the dataType:"JSON" and callback in your ajax call.
For example:
$.ajax({
url: "yourphp.php?id="+yourid,
dataType: "JSON",
success: function(json){
//here inside json variable you've the json returned by your PHP
for(var i=0;i<json.length;i++){
$('#items_container').append(json[i].item_id)
}
}
})
Please also consider in your PHP set the JSON content-type. header('Content-type: application/json');

function make_item_rows(result_array){
var string_buffer = "";
var parsed_array=JSON.parse(result_array);
$.each(parsed_array, function(){
string_buffer += parsed_array.item_id;
$(string_buffer).appendTo('#items_container');
string_buffer = "";
});
}

You need to parse it with jQuery.parseJSON
function make_item_rows(result_array){
var string_buffer = "";
$.each(jQuery.parseJSON(result_array), function(index, value){
string_buffer = value.item_id;
$(string_buffer).appendTo('#items_container');
});
}

Try this.
function make_item_rows(result_array){
var string_buffer = "";
$.each(result_array, function(index, value){
value = jQuery.parseJSON(value);
string_buffer += value.item_id;
$(string_buffer).appendTo('#items_container');
string_buffer = "";
});
}

Assuming you already parsed the json response and you have the array. I think the problem is you need to pass a callback to $.each that takes and index and an element param
function make_item_rows(result_array){
$.each(result_array, function(index, element){
document.getElementById("a").innerHTML+=element.item_id;
});
}
(Slightly modified) DEMO

for starters within the $.each you need to access the properties of the instance of object contained within result_array, not result_array itself.
var string_buffer = "";
$.each(result_array, function(index, object){
/* instance is "object"*/
alert( object.item_id);
});
Not entirely sure what you are expecting from this line: $(string_buffer).appendTo('#items_container');
$(string_buffer) does not create a valid jQuery selector since nothing within string_buffer has a prefix for class, tagname or ID, and values from json don't either
If just want the string value of the item_id appended :
$('#items_container').append( object.item_id+'<br/>');
If you are receiving this using jQuery AJAX methods you don't need to use $.parseJSON as other answers suggest, it will already be done for you internally provided you are setting correct dataType for AJAX

Related

Submit Form Array Via AJAX

I have a form which I would like to submit via Ajax, however, part of it contains an array. I am having difficulty passing this array via Ajax. An example of my Ajax is below, where I would usually pass the form entry data via how it is below after data (one: $('#one').val()) where I would have one row of this for each field.
Now I have a new set of fields, where the information needs to be passed through as an array. I have tried using serialize and formData -- var fd = new FormData("#form") -- and so far either just this array has been passed through, or nothing from the form is passed through, or just the array is not passed through.
Can anyone please point me in the right direction?
$("#form").submit(
function() {
if (confirm('Are you sure you want to edit this?')) {
$("#formMessages").removeClass().addClass('alert alert-info').html(
'<img src="images/loading.gif" /> Validating....').fadeIn(500);
$.ajax({
url: $("#form").attr('action'),
dataType: 'json',
type: 'POST',
data: {
one: $('#one').val(),
two: $('#two').val()
},
success: function(data){
//success stuff would be here
}
});
}
return false;
});
Thanks.
You could try using :
var dataSend = {};
dataSend['one'] = $('#one').val();
dataSend['two'] = $('#two').val();
dataSend['three'] = $('#three').val();
then in the ajax
data: {dataSend:dataSend}
You can gather data in php with json:
$json = json_encode($_POST['dataSend']);
$json = json_decode($json);
print_r($json);
To see output.
Edit:
You can gather data in php like below:
$one = $json->{'one'};
$two = $json->{'two'};
Have you tried this:
Written in JavaScript:
your_array = JSON.stringify(your_array);
And in PHP:
$array = json_encode($_POST['array']);

Ajax call not passing any POST values

I have a table that has sortable rows. The table is generated from a mysql database that has a field called "displayorder" that oders the table. When the user drags and drops rows, I want to use AJAX to submit those changes to the database whenever a user drops a row.
Currently, I can see the console.log() output from the success part of the AJAX call, and when i output the data there (order) it looks great, like this:
["order_1=1", "order_2=2", "order_4=3", "order_3=4"]
But according to Firebug, all that's getting passed in the $_POST is "undeclared".
How do I access that order variable from my indexpage_order.php file?
I have this jquery code:
<script>
$(document).ready(function() {
var fixHelper = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index)
{
$(this).width($originals.eq(index).width())
});
return $helper;
};
var sortable = $("#sort tbody").sortable({
helper: fixHelper,
stop: function(event, ui) {
//create an array with the new order
order = $(this).find('input').map(function(index, obj) {
var input = $(obj);
input.val(index + 1);
return input.attr('id') + '=' + (index + 1);
});
$.ajax({
type: 'POST',
url: 'indexpage_order.php',
data: order,
error: function() {
console.log("Theres an error with AJAX");
},
success: function(order) {
console.log("Saved.");
console.log(order);
}
});
return false;
}
});
});
</script>
indexpage_order.php contains:
if(isset($_POST) ) {
while ( list($key, $value) = each($_POST) ) {
$id = trim($key,'order_'); //trim off order_
$sqlCommand =
"UPDATE indexpage
SET displayorder = '".$value."'
WHERE id = '".$id."'";
$query = mysqli_query($myConnection,$sqlCommand) or die (mysqli_error($myConnection));
$row = mysqli_fetch_array($query);
}
}
You can simply rewrite the js code that are generating the data for POST.
order = {}
$(this).find('input').map(function(index, obj)
{
return order[this.id] = index;
}
)
Rest should work in PHP.
Try $_REQUEST instead of $_POST on the PHP file for POST method with ajax.
convert the js array order to json object as ajax data needs to be in json using JSON.stringify. hence, it needs to be data:JSON.stringify(order), in the ajax function.
Or, use json_encode like this data: <?php echo json_encode(order); ?>, in the ajax function
order is an array. Convert the order to query string like this in your ajax script,
data: order.join('&'),
It looks like your sending your order in a JavaScript array
And when it arrives at your PHP, its unreadable.
If its an object look into the json_decode function.
If its an array, serialize the data before it goes, then unserialize on the php side.
PHP is unable to understand JavaScript array or objects unless they are encoded/serialized correctly.

why i am getting object object result from my ajax to php?

here's my jquery:
$.ajax({
url: 'function.php',
type: 'post',
datatype: 'json',
success: function(data){
var toAppend = '';
if(typeof data === "object"){
for(var i=0;i<data.length;i++){
toAppend += '<li>'+data[i]["asin"]+'</li>';
}
$('.results').append(toAppend);
}
}
});
here's my php:
echo json_encode($items_from_amazon);
I already use the firebug and i get successfully the json values from response but why i am getting object object output?what wrong?am i missing something?
From what i see in your print_r($items_from_amazon); output, you have Array-Object-Object, try use this code:
for(var i=0;i<data.length;i++){
toAppend += '<li>'+data[i]["asin"][0]+'</li>';
}
echo json_encode(array_values($items_from_amazon));
This should make sure your JSON will be an array. However, it drops any string keys.
If $items_from_amazon is an object, you can cast it to an array:
echo json_encode(array_values((array)$items_from_amazon));
EDIT:
If I misunderstood the question and you want to know why your ASIN elements have objects:
You may want to change the code that generates $items_from_amazon so it doesn't append, but assign the ASIN.
// This appends
$item['asin'][] = $asin;
// This assigns
$item['asin'] = $asin;
// Note: make sure $asin is a string, not an object or array...
You could also use data[i]["asin"][0] in client code instead.

jquery.ajax with php

I have just started working on php. It's a very good lang as I'm feeling but some point I get stuck as I'm new to this.
My javascript code
var pv = $("#txtStart").val();
var av = $("#txtStartNextLevel").val();
var au = $("#fileStartPlay").val();
alert(pv+" "+av+" "+au);
var myau = au.split('\\');
$.ajax({
type:"POST",
url:php_url,
data:"{startPoint:"+pv+"nextLevelPoint:"+av+"audioFile:"+myau[myau.length-1]+"}",
contentType:"application/json",
dataType:"json",
success:function(){
alert("done");
},
error:function(){
alert(response);
}
});
My PHP code.
<?php
if(file_exists("Text.txt"))
{
$fileName = "Text.txt";
$fh = fopen($fileName,"a")
$Starts = $_POST["startPoint"];
$NextLevel = $_POST["nextLevelPoint"];
$AudioFileName = $_POST["audioFile"];
$code .=$Starts."*".$NextLevel."_1*".$AudioFileName."\"";
fwrite($fh,$code);
fclose($fh);
}
?>
When I run this it executes but doesn't write the values in the variable
$Starts,$NextLevel,$AudioFileName**.
And further if I write the same ajax procedure in
$.post(php_url,{startPoint:pv,nextLevelPoint:av,audioFile:myau[myau.length-1]},function(data){});
this works fine and write the content in the file.
Also As I'm using post method it should not display the values in Address bar what I'm passing to write. But it's showing those values in both the method.
localhost://myphp.php?txtStart=Start&fileStartPlay=aceduos.jpg&txtStartNextLevel=adfd
Please guide me where I'm lacking...
Replace the value bellow (with quotas)
"{startPoint:"+pv+"nextLevelPoint:"+av+"audioFile:"+myau[myau.length-1]+"}"
to
{startPoint:pv, nextLevelPoint: av, audioFile: myau[myau.length-1]}
Do what Burak TAMTURK said, and also get rid of
contentType:"application/json",
$_POST data should be in content-type application/x-www-form-urlencoded, which is the default.

Unable to get posted array from jQuery

I am trying to post a group of arrays using the jQuery post method, but I am having trouble getting the value of the arrays. How can I get the values of the array that I have sent?
If somebody could help me i would be grateful....
Here is what i have done:
$(document).ready( function()
{
$("#submit_info").click (
function()
{
var batchArr= new Array();
batchArr=arrPush('batch');
var facultyArr= new Array();
facultyArr=arrPush('faculty');
var levelArr= new Array();
levelArr=arrPush('level');
var sectionArr= new Array();
sectionArr=arrPush('section');
var shiftArr= new Array();
shiftArr=arrPush('shift');
$.post("server_side/college_info_insert.php",{
batchArr:batchArr,
facultyArr:facultyArr,
levelArr:levelArr,
sectionArr:sectionArr,
shiftArr:shiftArr
}, function(data)
{
alert(data);
});
}
);
function arrPush(opt)
{
var Arr= new Array();
Arr.push($("#"+opt+"_1").val());
var count= $("#"+opt).val();
var i=0;
for(i;i<=count;i++)
{
if(i==0)
{
Arr.push($("#txt"+opt).val());
}
else
{
Arr.push($("#txt"+opt+i).val());
}
}
return Arr;
}
}
);
How can I get the array values in the next page "college_info_insert.php" ??
okay, so this is actually a really common issue. It's unclear that you can't just send an array as-is from javascript to PHP and have it recognized.
The problem is that PHP doesn't know how to read in multiple values from a POST request - typically things like that require the PHP author to use brackets like: varname[].
So, basically you must send variables as strings. Using JSON you can send even complicated objects as strings to PHP using a single variable name. Typically you'd use JSON.stringify or something along those lines - but if you have a simple array you might not even need it.
Here's a full example of the problem/solution, found using jquery and $.post:
Asume you have a file myurl.php:
<?php
print_r($_POST);
?>
And in a separate file (or the console), you try:
var myarray = Array('some','elements','etc');
var mydata = {postvar1: 'string', postvar2: myarray};
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
This doesn't work! The result is that postvar2 only contains "etc".
The solution is force the array into a JSON string that can be decoded from PHP.
var myarray = Array('some','elements','etc');
var json_array = $.map(myarray,function(n) {
return '"'+n+'"';
});
var mydata = {postvar1: 'string', postvar2: '['+json_array+']' };
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
ON the PHP side you now must use: json_decode($_POST['myarray']); to get your results in a proper array.
Note, this example assumes very simple strings or numbers in your array. If you have complex objects, you will need to use a JSON.stringify function which will take care of extra quotes, escaping special characters, etc.
Not sure if i understood the question but wouldn't something like this work
if (isset($_POST['batchArr'])) {
$batchArr = $_POST['batchArr'];
// Then populate your html here e.g
echo $batchArr[0];
}

Categories