jQuery get json_encode variable from PHP - php

My PHP file retrieves data from a PostgreSQL DB. I have to send them back to my jQuery function in two different arrays. One is passed by using:
echo json_encode($tb);
and works fine, in my js file i get data correctly by using:
$.ajax({
type: "POST",
url: './DB/lb.php',
data: {d_p: oa},
success: function (tb) {
console.log(tb);
})
console output is as expected.
The other is always a PHP array, but I have to replace chars:
str_replace(array('[', ']'), '', htmlspecialchars(json_encode($ltb), ENT_NOQUOTES));
but if I write:
$.ajax({
type: "POST",
url: './DB/lb.php',
data: {d_p: oa},
success: function (tb, ltb) {
console.log(tb);
console.log(ltb);
})
console.log(ltb) simply outputs
success
what I'm I getting wrong?

The second parameter of succes is the response staus. This is the reason because you get success when logging tlb.
You can only return one JSON at at time, so combine them:
echo json_encode(array("other stuff", "tb" => $tb, "tbl" => array("some" => "data")));
On JS side you can simple acces them by index or key:
tb[0]; // "other stuff"
tb.tb; // content of $tb variable
tb.tbl; // {some: "data"}

The final working code:
PHP:
$tb = array();
$ltb = array();
while ($row = pg_fetch_array($result, NULL, PGSQL_ASSOC))
{
array_push($ltb, $row["x"], $row["y"]);
array_push($tb, $row["z"],$row["t"]);
}
echo json_encode(array('tb'=>$tb,'ltb'=>$ltb));
JS
$.ajax({
type: "POST",
url: './DB/lb.php',
dataType: 'json', // this is what I forgot!!!
data: {d_p: oa}, // passes variable for PHP function
success: function (response) {
console.log(response.tb+" "+ response.ltb);
$.each(response.tb, function( i, item ) {
// iterate over tb array
}
$.each(response.ltb, function( i, item ) {
// iterate over ltb array
}
});

Related

PHP Array to jQuery - gmaps.js not creating marker

I'm trying to use a PHP Array to get long and lat values from a database, and put these onto a map using gmaps.js.
So far, I have created the array in PHP, and echoed this onto my page to confirm the correct values are being displayed.
$data = array();
$data['latitude'] = array($lat);
$data['longitude'] = array($lng);
echo json_encode($data);
So $data is the array, with the values I want inside.
I then want to use jQuery to get the data from json encode, put these into the map marker locations and display the markers like so:
$.ajax({
type: "POST",
url: "phppage.php",
dataType: "JSON",
success: function(data) {
$.each(data, function(key, value) {
poi_marker = {
marker: {
lat: data.latitude,
lng: data.longitude,
}
}
}
poi_markers.push(poi_marker);
});
map.addMarkers(poi_markers);
}
});
I get no errors in my console (using firefox and firebug), the map displays but no markers are shown.
I don't think that you're code is actually doing what you think that it is doing. See this fiddle for what is actually happening with your loop.
If you store the array differently on the PHP side, it'll be easier to loop through multiple markers in JS. Also, I don't think gmaps.js needs that extra 'marker' key in the object.
New PHP
$data = array();
$data[] = array(
'latitude' => $lat
,'longitude' => $long
);
echo json_encode($data);
New JS
var poi_markers = []; // make sure you declare this before using it. if you already declare it somewhere else, don't use this line
$.ajax({
type: "POST",
url: "phppage.php",
dataType: "JSON",
success: function(data) {
$.each(data, function(key, value) {
var poi_marker = {
lat: value.latitude,
lng: value.longitude
}
poi_markers.push(poi_marker);
});
map.addMarkers(poi_markers);
}
});
You might be having trouble because you specify dataType: "JSON" but (atleast in the code you posted) you don't change the header on the php side. You may need to add this line to the top of phppage.php
header("Content-Type: application/json", true);
Where I learned everything I know about gmaps.js
I suppose that the data retrieved successfully as needed
$.ajax({
type: "POST",
url: "phppage.php",
dataType: "JSON",
success: function(data) {
$.each(data, function(key, value) {
map.addMarker{
lat: data.latitude,
lng: data.longitude
}
}
}
});
Check This

Not displaying array count

I have number of checkboxes on my page and I want to get those checkbox values in my database.
$('#assign_data').on("click",function()
{
var mandate_array = [];
var i= 0;
$('.assign_mandate:checked').each(function(){
mandate_array[i++] = $(this).val();
});
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+mandate_array+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
});
assign_mandate.php :
<?php
$mandate = explode(',',$_POST['mandate_array']);
// print_r($mandate); //it shows the data in array
count($mandate);exit; // it does not show the count in console
?>
When I print the array it show me the array data in console but when I try to echo the count of array it shows blank. Why ?
Thanks in advance
You have to echo the variable count value.
<?php
$mandate = explode(',',$_POST['mandate_array']);
// print_r($mandate); //it shows the data in array
echo count($mandate);exit; // it does not show the count in console
?>
Use JSON.stringify.
You would typically convert the array to a JSON string with JSON.stringify, then make an AJAX request to the server, receive the string parameter and json_decode it to get back an array in the PHP side.
$('#assign_data').on("click",function()
{
var mandate_array = [];
var i= 0;
$('.assign_mandate:checked').each(function(){
mandate_array[i++] = $(this).val();
});
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+JSON.stringify(mandate_array)+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
});
mandate_array is Array so you wont posted array data in query string, you should use JSON.stringfy() function to convert array/JSON object into string.
$.ajax
({
type: "POST",
url: BASE_URL+"mandate/assign_mandate.php",
data: "mandate_array="+JSON.stringfy(mandate_array)+"&role_id="+$('#role').val()+"&user_id="+$('#user').val(),
success: function(msg)
{
console.log(msg)
}
})
In PHP code
var_dump(json_decode($_POST['mandate_array']));
Use echo in front of the count()

Using jquery sortable with ajax and php

I am trying to use jQuery sortable and then save the changes to the database, however before I even get to updating the database I have something strange going on that I can't fathom. If I log the serialised data to the console, I get all items in the 'list' but if I echo out the json encoded array from the php script I only get one item - confused.com.
The jquery at the moment is:
$('#sortable-list').sortable({
//handle : '.handle',
update : function () {
var order = $(this).sortable('serialize');
var table = $(this).parent().attr('id');
console.log(order);
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: "order=" + order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
}
});
The PHP at the moment is:
if (isset($_POST['sort']) && $_POST['sort'] == 1) {
if ($_POST['sort_table'] == 'nationalities') {
$output = array();
$list = parse_str($_POST['order'], $output);
echo json_encode($output);
}
}
The console log gives me:
nationality[]=17&nationality[]=1&nationality[]=47&nationality[]=23&nationality[]=3&nationality[]=4&nationality[]=5&nationality[]=6&nationality[]=7&nationality[]=8&nationality[]=12&nationality[]=10&nationality[]=11&nationality[]=13&nationality[]=14&nationality[]=15&nationality[]=16&nationality[]=18&nationality[]=19&nationality[]=20&nationality[]=21&nationality[]=22&nationality[]=24&nationality[]=25&nationality[]=26&nationality[]=27 etc
And the echo json gives me:
Object {nationality: Array[1]}
nationality: Array[1]
0: "17"
length: 1
So for some reason the full array isn't being passed through to the PHP file and I can't work out why.
Your problem is that you are trying to assign a serialized array, to a single query string parameter, which will yield an incorrect query string. Try passing the serialized list as returned by the plugin serialize method like so:
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
And then access the passed list in php with:
$list = $_POST['nationality'];

Post value via ajax to php

I trying to post some value via ajax to php then php print send back js console.log, have problem:
build array( I'm doubt below I made is array??)
$('.eachcontainer').each(function(){
var arr = $(this).find('img').map(function(){
return $(this).attr('src');
});
console.log(arr);
// result:
// ["16.png", "17.png", "19.png", "18.png"]
// ["0.png"]
// ["0.png"]
// []
// []
$.ajax({
type: "POST", url: "update.php",
data: arr
}).done(function(msg){
console.log(msg);
});
});
php
print_r($_POST);
js come back console.log
Array
(
[undefined] =>
)
Array
(
)
Array
(
)
Array
(
[undefined] =>
)
Why this does not work? How can i fix it?
Also, I tried to change the syntax in my ajax function data: {arr: arr} but this didn't work either.
Error message:
TypeError: Type error jquery-1.10.1.min.js:6
Found error line in jquery-1.10.1.min.js:6:
t = x.isFunction(t) ? t() : null == t ? "" : t, i[i.length] = encodeURIComponent(e) + "=" + encodeURIComponent(t)
you haven't constructed proper key&value pair using your data, if you want to pass a raw stream of data then set processData: false and capture with php://input
var arr = $(this).find('img').map(function(){
return $(this).attr('src');
});
$.ajax({
type: "POST", url: "update.php",
data: arr,
processData: false,
}).done(function(msg){
console.log(msg);
});
on the php side
$data = file_get_contents("php://input");
You first need to call arr.get() to get the jquery.map result back as a regular javascript array. Then you can pass it to the ajax data paramter as:
data: { "images" : arr.get() }
So the full ajax call would look like this:
$.ajax({
type: "POST", url: "update.php",
data: { "images" : arr.get() }
}).done(function(msg){
console.log(msg);
});
You can then read the array back in php as:
$images = $_POST['images'];

JQuery + Json - first steps with an example

I need (recently) to get an array from the server after an ajax call created by jquery. I know that i can do it using JSON. But i don't know how to implement it with JQuery (im new with JSON). I try to search in internet some example, but i didnt find it.
This is the code :
// js-jquery function
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
success: function(msg) {
// here i need to manage the JSON object i think
}
});
return false;
}
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo $linkspon;
}
in fact, i need to get the array $linkspon after the ajax call and manage it. How can do it? I hope this question is clear. Thanks
EDIT
ok. this is now my jquery function. I add the $.getJSON function, but i think in a wrong place :)
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
$.getJSON(url, function(data) { alert(data[0]) } );
}
});
return false;
}
Two things you need to do.
You need to convert your array to JSON before outputting it in PHP. This can easily be done using json_encode, assuming you have a recent version of PHP (5.2+). It also is best practice for JSON to use named key/value pairs, rather than a numeric index.
In your jQuery .ajax call, set dataType to 'json' so it know what type of data to expect.
// JS/jQuery
function changeSponsor() {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'id=changespon',
dataType: 'json',
success: function(data) {
console.log(data.key); // Outputs "value"
console.log(data.key2); // Outputs "value2"
}
});
return false;
}
// PHP
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon["key"]= "value";
$linkspon["key2"]= "value2";
echo json_encode($linkspon);
}
1) PHP: You need to use json_encode on your array.
e.g.
// php-server function
if((isset($_POST['id'])) && ($_POST['id']=="changespon")) {
$linkspon[0]="my ";
$linkspon[1]="name ";
$linkspon[2]="is ";
$linkspon[3]="marco!";
echo json_encode($linkspon);
}
2) JQUERY:
use $.getJSON(url, function(data) { whatever.... } );
Data will be passed back in JSON format. IN your case, you can access data[0] which is "my";

Categories