Send data with AJAX and receive in PHP - php

I'm having a script which is generating a JSON array, based values user have selected. These values are sent as a JSON with AJAX to a PHP script which should receive this values and process it.
What could be wrong?
JSON (That is sent):
[{
"Pages":
{"name":" Page Name 1",
"id":"252456436636644"}
},
{
"Pages":{
"name":" Page Name 2",
"id":"345345435435232"
}
}]
Jquery:
var json_pages = JSON.stringify(publish);
$.ajax({
url: "post.php",
type: "post",
data: { PublishToPages: json_pages },
success: function(){},
error: function(){}
});
Problem is that the JSON I recieve from PHP isn't getting the data,
if($_POST['PublishToPages']) {
$json = $_POST['PublishToPages'];
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
echo $page_id;
}
}
If I manually put in the JSON in the PHP script like this it Works,
if ($_POST['PublishToPages']) {
$json = '[{"Pages":{"name":" Page Name","id":"234545355345435"}},{"Pages":{"name":" Page Name 2","id":"345345435435435435"}}]';
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
echo $page_id;
}
}

Try using this:
if($_POST['PublishToPages']) {
$json = $_POST['PublishToPages'];
$items = array();
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
$items[] = $page_id;
}
echo json_encode($items);
}

Try this
$.ajax({
url: "post.php",
type: "post",
dataType:"json",
data: { PublishToPages: json_pages },
success: function(){},
error: function(){}
});

Thanks for all input! I figured it out using the var_dump and realized it was encoding error so added stripslashes(); and it worked! :)
if ($_POST['PublishToPages']) {
$json = stripslashes($_POST['PublishToPages']);
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
echo $page_id;
}
}

Related

cannot display array values in ajax success function

$.ajax({
type: "GET",
url: 'http://localhost/abc/all-data.php',
data: {
data1: "1"},
success: function(response)
{
alert(response);
}
});
return false;
I want to display each element of array one by one in success function of the ajax currently i get all elements to gether
this is my php code
$i=0;
while($row = mysqli_fetch_assoc( $qry )){
$temp[$i]['c_n'] = $row['c_name'];
$temp[$i]['j_t'] = $row['Job_Title'];
$temp[$i]['des'] = $row['description'];
$temp[$i]['req'] = $row['requirments'];
$temp[$i]['dat'] = $row['posted'];
$i++;
}
$data = array('temp'=> $temp);
echo JSON_encode($temp);
I do appreciate your helps
you probably use something like this in your success function :
response.temp.forEach(function(element){
console.log(element.c_n) ;
console.log(element.j_t) ;
console.log(element.des) ;
console.log(element.req) ;
console.log(element.dat) ;
});
In your success function, you need to json parse your response
var data = JSON.parse(response);
You can access to your data:
data['temp']
If you want your response parsed to json automaticallym you can setup your ajax settings like this:
$.ajaxSetup ({
contentType: "application/json",
dataType: 'json'
});
Then you don't need to call JSON.parse anymore.
Your code:
$i=0; while($row = mysqli_fetch_assoc($qry)){
$temp[$i]['c_n'] = $row['c_name'];
$temp[$i]['j_t'] = $row['Job_Title'];
$temp[$i]['des'] = $row['description'];
$temp[$i]['req'] = $row['requirments'];
$temp[$i]['dat'] = $row['posted'];
$i++;
} $data = array('temp'=> $temp); echo JSON_encode($temp);
Please change the last line as
return JSON_encode($data);
Hope this helps you :)

PHP Json echo specific item

i want to get the specific value from the json, but i can't get it to work.
this is my save format, these are values from input fields.
$.ajax({
type: "POST",
url: "speichern.php",
dataType: 'json',
data: {
"Produkt": {
"Produktkategorie": Produktkategorie,
"Optionen": {
"MaxBreite": MaxBreite,
"MaxHoehe": MaxHoehe,
"MinBreite": MinBreite,
"MinHoehe": MinHoehe,
"ProduktStaerke": ProduktStaerke,
"KantenAuswahl": KantenAuswahl, },
"Formen": {
"FormRund": FormRund,
"FormEllipse": FormEllipse,
"FormHexagon": FormHexagon,
"FormSchnittlinks": FormSchnittlinks,
"FormRechtQuad": FormRechtQuad,
}
}
},
}).done(function( msg ) {
console.log( msg );
});
here it gets saved to file:
$neu = json_encode($_POST);
$file = file_get_contents('results.json');
$data = json_decode($file);
unset($file);
$data[] = $neu;
file_put_contents('results.json',json_encode($data));
unset($data);
and now i want to echo these values seperately:
$string = file_get_contents("results.json");
$jsonObject = json_decode($string);
$jsonArray = json_decode($string, true);
echo $jsonObject->Produkt->Produktkategorie . " and " . `$jsonArray['Produkt']['MaxBreite'];`
but this only throws me following errors:
for the object: Notice: Trying to get property of non-object in
for the array: Notice: Undefined index: Produkt in
this is the complete json file:
["{\"Produkt\":{\"Produktkategorie\":\"TestArtikel\",\"Optionen\":{\"MaxBreite\":\"250\",\"MaxHoehe\":\"150\",\"MinBreite\":\"10\",\"MinHoehe\":\"5\",\"ProduktStaerke\":\"3\",\"KantenAuswahl\":\"Ecke\"},\"Formen\":{\"FormRund\":\"true\",\"FormEllipse\":\"true\",\"FormRechtQuad\":\"true\"}}}"]
could you help me please?
When you posting the data, maybe you have to set the datatype.
dataType: 'json'
$.ajax({
url: 'speichern.php',
type: 'post',
dataType: 'json',
success: function (data) {
},
data: {data:jsondata}
});
And in your php file, you could get the json data like following.
$json=json_decode(stripslashes($_POST['data']), true);
Hope it helps you.
You need to decode the json two times because the way you have it in the file. Try this:
$json = file_get_contents('results.json');
$json = json_decode($json, true);
$json = json_decode($json[0], true);
echo $json['Produkt']['Produktkategorie'];
Simply replace your last line with
echo $jsonObject->Produkt->Produktkategorie . " and " . `$jsonArray['Produkt']['Optionen']['MaxBreite'];

Passed array to php from jquery with ajax value just shows Array not actual array value

Please can someone tell me where I'm going wrong
js file:
//Checkboxid is an array which is populated using .push();
$.ajax({
type: "POST",
url: "test.php",
dataType: 'html',
data: { data: Checkboxid },
success: function (data) {
console.log(data);
}
});
test.php:
<?php
$test = $_POST['data'];
for ($i = 0; $i < count($test); ++$i) {
echo $test[$i];
}
foreach($test as $val) {
echo $val;
}
?>
console.log displays:
ArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArray
Your $test variable is a two-dimensional array. Try this
<?php
$test = $_POST['data'];
foreach($test as $arr) {
foreach($arr as $val){
echo $val;
}
}
?>

why NULL in a json after JSON.stringify?

php 5.4 fastcgi
jquery 1.10
Jquery code:
$.ajax({
type: "POST",
url: "",
dataType: "json",
data: { json: JSON.stringify({test: 'teste'}) }
}).done(function(msg) {
var msg = $.parseJSON(msg);
alert(msg);
});
PHP code:
$json = $_POST['json'];
$info = json_decode($json, true);
var_dump($info);
Result:
array(1) {
["test"]=>
string(5) "teste"
}
null
i dont know why this null apper and how to remove it. Because if i try to use:
$i = info['test'];
echo $i;
i will recieve:
testenull
Seems like your JSON data is the issue.
json_decode() in PHP takes a JSON encoded string as input and converts it to a PHP variable.
It works like this
<?php
$json = '{"test": 12345}';
$obj = json_decode($json);
print $obj->{'test'}; // 12345
?>

Ajax request on wordpress returns 404 error

On my function.php file on my custom theme folder I have this:
function getPrices(){
$price = get_post_meta($_REQUEST["post_id"], "price_one", true);
$results['price'] = $price;
$results = json_encode($results);
die($results);
}
add_action('wp_ajax_getPrices', 'getPrices');
add_action('wp_ajax_nopriv_getPrices', 'getPrices');
and on the js file I had this:
$('ul.people_adult li').click(function(){
var post_id = $("#post_id").val();
jQuery.ajax({
type:"POST",
dataType : "json"
url: "http://localhost/wordpress/wp-admin/admin-ajax.php",
data: {
action: 'getPrices',
post_id: post_id
},
complete:function(data){
console.log(data.price);
}
});
});
When I click the following error message:
POST http://localhost/wp-admin/admin-ajax.php 404 (Not Found)
Also when I alert the returned data it shows object Object but when I log it to console it shows all the html code of the responded page.
Any ideas ??
Thanks!
The big problem was the bad URL I was providing and for some reason couldn't notice until Jackson and cointilt mention it.
Also I had typo errors in my function.php file.
Here is the answer to my problem.
function getPrices(){
$the_id = $_REQUEST["post_id"];
$results[] = get_post_meta($the_id, "price_one", true);
$results[] = get_post_meta($the_id, "price_two", true);
$results[] = get_post_meta($the_id, "price_three", true);
$results[] = get_post_meta($the_id, "price_four", true);
$results[] = get_post_meta($the_id, "price_five", true);
$results[] = get_post_meta($the_id, "price_six", true);
$results[] = get_post_meta($the_id, "price_seven", true);
$results[] = get_post_meta($the_id, "price_eight", true);
$results = json_encode($results);
die($results);
}
add_action('wp_ajax_getPrices', 'getPrices');
add_action('wp_ajax_nopriv_getPrices', 'getPrices');
and on the js file
$('ul.people_adult li').click(function(){
var post_id = $("#post_id").val();
jQuery.ajax({
type:"POST",
dataType : "json",
url: "http://localhost/wordpress/wp-admin/admin-ajax.php",
data: {
action: 'getPrices',
post_id: post_id
},
success:function(response){
$("#price_est_person").html(response[0]);
/*Do some stuff with response[1], response[2 etc]*/
}
});
});

Categories