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'];
Related
$.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 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
?>
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;
}
}
Here is my HTML
<input x-webkit-speech id="mike" name="string" style="position: relative;" disabled lang="ru" />
Then when the field is changes,
This function executes
$(document).ready(function(){
$('#mike').bind('webkitspeechchange',function()
{
a= $(this).val();
recognizeAjax(a);
}) ;
});
function recognizeAjax(string) {
var postData ="string="+string;
$.ajax({
type: "POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php',
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
if (data.success == true){
alert(data.message);
}
else{
alert(data.message+'hy');
}
}
});
And here is my PHP (please don't say anything about the way i connect to DB it doesn't metter right now)
<?php header('Content-type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', true);
// Here's the argument from the client.
$string = $_POST['www'];
$quest=1;
$con=mysql_connect("localhost", "******", "*********") or die(mysql_error());
mysql_select_db("vocabulary", $con) or die(mysql_error());
mysql_set_charset('utf8', $con);
$sql="SELECT * FROM `text` WHERE event_name = 'taxi' AND quest_id = '".$quest."'";
$result = mysql_query($sql);
mysql_close($con);
while($row = mysql_fetch_array($result))
{
if ($string == htmlspecialchars($row['phrase']))
{
$data = array('success'=> true,'message'=>$row['phrase']);
// JSON encode and send back to the server
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
} else {
// Set up associative array
$data = array('success'=> false,'message'=>'aint no sunshine');
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
}
}
When i change the dataType to "text" in the javasript function - i receive an alert with 'undifiend'
But when chenge it to 'json'.. i receive nothing (chrome debuger see nothing)
I set up all encodings to this article http://kunststube.net/frontback/
And i checked it with simple POST requests - it works perfect.
The problem with json.
Any suggestions?
Thanks
Just remove the datatype="json" bit and change the data bit to data: { "string": string }
After that try a print_r(json_decode($_POST['string']));. I'm quite sure that will get you your data.
And indeed remove your beforeSend callback.
I think the prob is the code var postData ="string="+string;
jQuery expects this to be a proper JSON Object.
Next: $string = $_POST['www']; takes a parameter named "www" from your post request, but the name above is "string" (at least).
Try either (!) this:
var getData ="www="+string;
$.ajax({
type: "POST",
dataType: "json",
data: null,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php?' + getData,
and server:
$string = $_GET['www'];
or this (php)
$string = $_POST['string'];
$stringData = json_decode($string);
// catch any errors ....
$quest=$stringData[....whatever index that is...];
I am a newer for study php and jQuery, I tried many times myself, but also not work well.
How to modify a PHP json_decode into a jQuery.getJSON()? I want modify all the PHPcode into javascript.
$json_data = file_get_contents("data.txt");
$data = json_decode($json_data, true);
if($data){
$num = 1;
foreach ($data as $result) {
?>
$.ajax({
url: "page2.php",
dataType: "html",
type: 'POST',
data: "value=<?php echo $result['name']; ?>",
success: function(data){
$("#result<?php echo $num; ?>").html(data);
}
<?php
$num++
}
}
?>
json tree:
[
{"name" : "name1"},
{"name" : "name2"},
{"name" : "name3"},
]
If you're sure the text file is json then the following should work as JSON is a subset of javascript.
<?php
$json_data = file_get_contents("data.txt");
echo "var json_data = $json_data;";
?>
for (var i = 0; i<json_data.length; i++) {
$.ajax({
url: "page2.php",
dataType: "html",
type: 'POST',
data: "value="+json_data[i].name,
success: function(data){
$("#result"+String(i+1)).html(data);
}
}