appending a json file with PHP - php

I have a json file to which i'm trying to append data.
The json file content looks like this .
{
"KEYOP": ["01KEYOPS","23016/scripts/3rdParty/pusher-chat/assets/cobain.jpg"]
}
Below is my add_user.php
<?php
$sentArray = $_POST['dataString1'];
$boxArray = file_get_contents('results.json');
$sentdata = json_decode($sentArray);
$getdata = json_decode($boxArray);
foreach($sentdata as $value)
$getdata[] = $value;
print_r($getdata);
?>
and below is my jquery script where i'm trying to send data to server
var myObj = {foo: "bar", "baz": "wockaflockafliz"};
var jsonString = JSON.stringify(myObj, null, 2);
$.ajax({
type: "POST",
url: "23016/scripts/3rdParty/pusher-chat/server/add_user.php",
data: { 'dataString1': jsonString },
cache: false,
success: function(response)
{
alert(response);
}
});
The appended JSON file should look like this.
{
"KEYOPS01!": ["01 KEYOPS","23016/scripts/3rdParty/pusher-chat/assets/cobain.jpg"],
foo: "bar",
"baz": "wockaflockafliz"
}
I'm getting 500 Internal server error whenever I try to merge the data.

check the log, but, if you want to merge the 2 arrays ($sentdata and $getdata), you should use something like array_merge()
http://php.net/manual/es/function.array-merge.php
with this:
foreach($sentdata as $value)
$getdata[] = $value;
you are loosing your keys (and its slow)
and by the way... your appended json is not valid json...

Related

Array values returns null

I am making post request with ajax and sending data with json format.Then I am fetching json with php and decode it into an array.When I print out whole array there is no problem. I can see the key value pairs.But when I try to print out this array's one of index value it returns null.What could be the problem?Here is my ajax request
$(function() {
$("#del").click(function() {
var file_id = 32
var file_update = 1321321
var obj = {
file_id: file_id,
file_update: file_update
};
$.ajax({
type: "post",
url: "config/ajax.php",
data: {
"file_update": JSON.stringify(obj)
},
success: function(response) {
alert(response);
}
})
})
})
Here is my php code
if (isset($_POST["file_update"])) {
$file_update = json_decode($_POST["file_update"], true);
$x = $file_update[0];
var_dump($x);
var_dump($file_update);
}
The $file_update array is associative, therefore it doesn't have integer keys, its keys are strings.
$file_update[0] does not exist and this statement should throw an error given you have proper error reporting configured.
If you want to access specific array values use:
$file_update['file_id'];
$file_update['file_update'];
If you want to access the first element of an associative array you can use the following:
$key = array_keys($file_update)[0];
$value = $file_update[$key];

extract json.stringify(data)

I'm building an API, and I need a little help, to understand how can I parse data from JSON request, here is my code:
<textarea style="width: 100%; height: 300px;" id="request_json">
{
"requestType":"TourListRequest",
"data":{
"ApiKey":"12345",
"ResellerId":"999",
"SupplierId":"999",
"ExternalReference":"12345",
"Timestamp":"2013-12-10T13:30:54.616+10:00",
"Extension":{
"any":{
}
},
"Parameter":{
"Name":{
"0":" "
},
"Value":{
}
}
}
}
</textarea>
<script>
function SubmitAPI() {
var sendInfo = {
JSON : $('#request_json').val(),
URL : $('#supplier_api_endpoint_JSON_Tour_List').val(),
Type : 'JSON Tour List'
};
$('#response_json').html("Calling API...");
$.ajax({
url: 'post_JSON.php',
type: "POST",
data: JSON.stringify(sendInfo), // send the string directly
success: function(response){
var obj = jQuery.parseJSON( response );
$('#response_json').html(response);
$('#response_validation').html( obj.json_valid );
},
error: function(response) {
$('#response_json').html(response);
}
});
}
</script>
So I need to know how to receive "JSON.stringify(sendInfo)" in my php script post_JSON.php
Any idea ?
Thank you in advance,
I think you need to name you data string, something like...
data: {info: JSON.stringify(sendInfo)},
and in your php:
$json_data = $_POST['info'];
var_dump(json_decode($json_data, true));
to get at that data using php, do something like:
$postedData = json_decode($json_data, true); // turns json string into an object
$requestType = $postedData['requestType'];
if you need to parse a returned json string with jquery you do something like this:
var jsonStuff = jQuery.parseJSON( data );
alert( jsonStuff.requestType);
I don't know php, but I think you have to do the below.
In the post_JSON.php, you can do: json_decode.

How to retrieve data from jQuery.Post() in PHP?

I am currently trying to send a string to a to a php script which will eventually return a JSON file.
Here is code i'm using to send the string:
var str = "testString";
$.post("php/getTimes.php", str,
function(data){
console.log(data.name);
console.log(data.time);
}, "json");
In the 'getTimes' php file I am simply trying to receive the 'str' variable I am passing. Any ideas how to do this? It seems like it should be pretty simple.
You have to name attributes in POST data either with serialized string:
var data = "str=testString";
$.post("php/getTimes.php", data, function(json) {
console.log(json.name);
console.log(json.time);
}, "json");
or with map:
var data = {
str : "testString"
};
$.post("php/getTimes.php", data, function(json) {
console.log(json.name);
console.log(json.time);
}, "json");
To handle this variable in PHP use:
$str = $_POST['str'];
In getTimes.php:
<?php
$var = $_POST['string']; // this fetches your post action
echo 'this is my variable: ' . $var; // this outputs the variable
?>
Also adjust:
$.post("php/getTimes.php", str,
to
$.post("php/getTimes.php", { string: str },

How to send array of JSON objects with jQuery

I'm programming an web page and I really stucked trying to send an Array of JSON objects to my PHP backend script.
this is my javascript code (using jQuery):
var toSend = new Array();
$("input[type=checkbox]").each(
function (indice, item)
{
var dom = $(item);
var domJSON = {
id: dom.attr("value"),
checked: (dom.attr("checked") == "checked" ? true : false)
};
//put object as JSON in array:
toSend.push($.toJSON(domJSON));
}
);
$.ajax({
type:"POST",
url: "salvar_escala.php",
data: {checkbox: toSend},
success: function(response) {
$("#div_salvar").html(response);
},
error: function() {
alert("Erro");
}
}
);
And in PHP I have this:
//Grab the array
$arrayFromAjax = $_POST['checkbox'];
foreach($arrayFromAjax as $aux) {
$temp = json_decode($aux, true);
$id = $temp['id'];
$value = $temp['checked'];
//This line doesn't print anything for $id and $value
echo "Id: $id | Value: $value<br />";
//This line prints an crazy string, but with right values
echo "CHEKBOX[] => $b<br />";
}
In this code, I'm decoding my objects to json, putting then in an array and sending. I also tried but objects in array (without json), and then, convert the array to json, and send them like that:
$.ajax({
type:"POST",
url: "salvar_escala.php",
dataType: "json",
data: {checkbox: $.toJSON(toSend)},
success: function(response) {
$("#div_salvar").html(response);
},
error: function() {
alert("Erro");
}
}
);
But in this case, it's worse, the error function is called.
You should be able to do the following in PHP
<?php
$checkboxes = json_decode($_POST['checkbox']);
foreach($checkboxes as $checkbox) {
$id = $checkbox['id'];
$val = $checkbox['value'];
print $id . ': ' . $val;
}
The problem is that you're trying to loop through a JSON string without first decoding it into a PHP array.

Sending JSON via AJAX to PHP using jQuery

I am trying to send JSON to a PHP file using jQuery AJAX, basically what I am trying to do is get the values and id's of a bunch of child elements and then assign them to a JSON object and then send that object via ajax to the PHP file which would then process it and enter it into a database.
Here is my code,
Javascript/jQuery:
function test(){
var selects = $('#systems_wrapper').find('.dropDowns');
var newArray = new Array();
selects.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
var o = { 'id': id, 'value': val };
newArray.push(o);
});
$.ajax({
type: "POST",
url: "qwer.php",
dataType: 'json',
data: { json: newArray }
});
}
PHP:
<?php
$json = $_POST['json'];
$person = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $person);
fclose($file);
echo 'success?';
?>
It creates the file, but it is completely blank, any idea what it could be?
Thanx in advance!
You could try using the JSON.stringify() method to convert your array into JSON automagically. Just pass the output from this.
data: { json: JSON.stringify(newArray) }
Hope this helps
Don't use an array.
use a simple string like this:
var o = '[';
selects.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
o += '{ "id": "'+id+'", "value": "'+val+'" },';
});
o = o.substring(0,o.length-1);
o += ']';
and in the ajax just send the string 'o'
data: { json: newArray }
in the php file just make a json_decode($json, true);
it will return an array of array that you can access by a foreach
if you want to see the array, use var_dump($person);
You should set a contentType on your ajax POST. I would use contentType: "application/json";
You should use json_encode() not json_decode()! This way you will get the json string and be able to write it.
No need to use json_decode if you're saving it to a text file. jQuery is encoding your array in JSON format, PHP should then just write that format right to the text file. When you want to open that file and access the data in a usable way, read its contents into a variable and THEN run json_decode() on it.

Categories