I've been trying to save some data to a .json file with ajax and php.
At the moment I'm receiving an error and my data is not being saved and can't figure out why.
This is my .js file:
var data = {
"test": "helloworld"
}
$.ajax({
url: "save.php",
data: data,
dataType: 'json',
type: 'POST',
success: function (data) {
$("#saved").text("Data has been saved.");},
error: function (data){
$("#saved").text("Failed to save data !");}
});
And here is my php file:
$json = $_POST['data'];
if(json_decode($json) != null){
$file = fopen('web/js/data_save.json', 'w+');
fwrite($file, json_encode($json));
fclose($file);
}else{
print("<pre>Error saving data !</pre>");
}
When I'm trying to save the ajax error is getting triggered:
error: function (data){
$("#saved").text("Failed to save data !");
}
I hope someone can guide me in the right direction :)
this works fine for me
.js:
$(document).ready(function() {
var json_object = {"data": "helloworld"};
$.ajax({
url: "../tests/save.php",
data: json_object,
dataType: 'json',
type: 'POST',
success: function(json_object) {
console.log(json_object);
$("#saved").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$("#saved").text("Failed to save data !");
}
});
});
.php
$post_data = $_POST['data'];
if (!empty($post_data)) {
$file = fopen('data_save.json', 'w+');
fwrite($file, json_encode($post_data));
fclose($file);
echo json_encode('success');
}
if you do a var_dump on the $_POST you ll see that your variable is sent as an array in php. also you need to echo a json string for the callback success
You do not have any key data in your request.
You need to parse the whole request body as JSON with http_get_request_body or something to get the raw body in order to get the result you want.
EDIT: As it seems that there has been some confusion, here are some further explanations.
When sending a JSON POST request to PHP, you cannot use the $_POST variable as you would with a normal request.
curl -H 'Content-Type: application/json' -d '{"foo": "bar"}' myhost/foo.php
with foo.php defined as bellow will print an empty array, try it yourself if you want.
<?php
print_r($_POST);
When you need to get JSON from the body of the POST request, you need to get all the body, and then parse it from JSON.
You can do this in several ways, one of which being the one I wrote before editing.
You can also get the whole body without using any extension by using
file_get_contents('php://input')
The result should be the same.
So with the code bellow you should get what you want.
<?php
$json = json_decode(file_get_contents('php://input'), true);
print_r($json);
Related
This might be a dumb question. I'm fairly new to PHP. I am trying to get a look at some echo statements from a page I'm posting to but never actually going to. I can't go directly to the page's url because without the post info it will break. Is there any way to view what PHP echos in the developer console or anywhere else?
Here is the Ajax:
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
imgurl = 'url';
filepath = 'path';
$.ajax({
url: imgurl,
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
error: function(data) {
console.log(data);
}
});
}
And here is the php file:
<?php
$image = $_FILES['image']['name'];
$uploaddir = 'path';
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo $uploadfile;
} else {
echo "Unable to Upload";
}
?>
So this code runs fine but I'm not sure where the echos end up and how to view them, there is more info I want to print. Please help!
You already handle the response from PHP (which contains all the outputs, like any echo)
In the below code you have, url will contain all the output.
To see what you get, just add a console.log()
$.ajax({
...
success: function(url) {
// Output the response to the console
console.log(url);
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
...
}
One issue with the above code is that if the upload fails, your code will try to add the string "Unable to upload" as the image source. It's better to return JSON with some more info. Something like this:
// Set the header to tell the client what kind of data the response contains
header('Content-type: application/json');
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo json_encode([
'success' => true,
'url' => $uploadfile,
// add any other params you need
]);
} else {
echo json_encode([
'success' => false,
'url' => null,
// add any other params you need
]);
}
Then in your Ajax success callback, you can now check if it was successful or not:
$.ajax({
...
dataType: 'json', // This will make jQuery parse the response properly
success: function(response) {
if (response.success === true) {
var image = $('<img class="comment_image">').attr('src', path + response.url);
$('#summernote').summernote("insertNode", image[0]);
} else {
alert('Ooops. The upload failed');
}
},
...
}
If you add more params to the array in your json_encode() in PHP, you simply access them with: response.theParamName.
Here is a basic example...
HTML (Form)
<form action="script.php" method="POST">
<input name="foo">
<input type="submit" value="Submit">
</form>
PHP Script (script.php)
<?php
if($_POST){
echo '<pre>';
print_r($_POST); // See what was 'POST'ed to your script.
echo '</pre>';
exit;
}
// The rest of your PHP script...
Another option (rather than using a HTML form) would be to use a tool like POSTMAN which can be useful for simulating all types of requests to pages (and APIs)
I have a strange behaviour, I sent data to a PHP page using Post request, my problem is when I try to manipulate this data (echo for exemple) in PHP page I get nothing, but when I make condition on the value I sent the condition is ok.
My JS code
$.ajax({
type: "POST",
url: 'admin/page.php',
data: {
type: 'search',
date1:'2021/04/15',
date2:'2021/04/13'
},
success: function(data){
alert(data);
}
});
My PHP code
$uname = $_POST["type"];
$date1 = $_POST["date1"];
$date2 = $_POST["date2"];
if ($uname=='search') // condition OK
{
echo $date1;
echo $date2;
}
I am trying to transfer a javascript array to a php array and I used the following code in my php file to do so:
var rowArr=[];
var currow=$(this.closest('tr'));
var col1=currow.find('td:eq(0)').text();
rowArr.push(col1);
var col2=currow.find('td:eq(1)').text();
rowArr.push(col2);
var col3=currow.find('td:eq(2)').text();
rowArr.push(col3);
var myJSONText = JSON.stringify( rowArr );
$.ajax({
type: "POST",
url: "jsonRecieve.php",
data: { emps : myJSONText},
success: function() {
alert("Success");
}
});
so when I run this code, I get the success alert but I am not seeing any of the array elements being printed out. I am also not getting any error messages.Here is my jsonRecieve.php:
<?php
$rowAr=$_POST['emps'];
print_r($rowAr);
?>
is there a way to verify that it has been transferred? I don't believe it has but if it hasn't can someone help?
Seems you need to decode the json string with json_decode() to get your emps value on the server side and to alert the server response need to send something from the server. Let's debug this way-
ON JS
$.ajax({
type: "POST",
url: "jsonRecieve.php",
data: { emps : myJSONText},
success: function(data) {
alert(data); // alert your data to see that returns from server
}
ON PHP
<?php
$rowAr=$_POST['emps'];
$array = json_decode($rowAr,1); // 2nd params 1 means decode as an array
print_r($array);
die('response from the server');
?>
I'm trying to update json file on the server on button click.
So when i click the button #update I'm collecting values from input fields and insert them to json object then I sent this json object to controller.php.
But how to handle this json object delete the old json file and and create new json file with the json object in it.
Lets say the json file path is : js/currencies.json
JS:
function ajaxPost(obj){
$.ajax({
type: "POST",
dataType: "json",
url: "controller.php",
data: {myData:obj},
contentType: "application/json; charset=utf-8",
success: function(data){
alert('Items added');
},
error: function(e){
console.log(e.message);
}
});
}
$(document).ready(function(){
$('#update').on('click', function(){
var objrates =
{
"EURbuy" : $('#eurbuy').val(),
"EURsell" : $('#eursell').val(),
"USDbuy" : $('#usdbuy').val(),
"USDbuy" : $('#usdbuy').val()
}
ajaxPost(objrates);
});
});
PHP :
<?php
$data[] = $_POST['myData'];
$inp = file_get_contents('js/currencies.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('js/currencies.json', $jsonData);
?>
The php code works withouth errors but the .json file is not replaced with the new values
Use json_encode to return the altered object or save it to a file with file_put_contents
<?php
$obj = $_POST['myData'];
$obj['key'] = 'newVal';//edith the values based on key
echo $json = json_encode(array('newobj'=>$obj));//echo the json object if you want
file_put_contents('js/currencies.json',$json); //replace the json with new json in the file
?>
Note: you can even pass the file name to the ajax and retrieve to to append the it
alter the data:
data: {myData:obj,filename:'js/currencies.json'},
php get the url and alter the file:
$filename= $_POST['filename'];
file_put_contents($filename,$json);
Hello i have a page can calla an ajax page in json with jquery.
i just set
dataType: "json"
in ajax call and i set header in php
header("Content-type: application/json; charset=utf-8");
but when i try read my response in a client i have this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
var o = JSON.parse(jsonString);
For more information
PHP file function:
function _addToWishlist($v,$db){
$ris = array();
$data = array();
$data[0]=20;
$data[1]=25;
$data[2]=30;
$ris['stato']="1";
$ris['mex']="DA IMPLEMENTARE!!!";
$ris['data']=$data;
$ris['action']="";
ob_clean();
echo json_encode($ris);
}
and thi is a php response:
{"status":"success","stato":"1","mex":"DA IMPLEMENTARE!!!","data":[20,25,30],"action":""}
in client i use this javascript:
$.ajax({
url: "common/function/include/dataLoad.php",
type: "POST",
data: datas,
async:false,
//dataType: "text",
dataType: "json",
success: function(ris) {
// Run the code here that needs
// to access the data returned
//$(this).parent
//alert (ris);
risp=ris;
//var a = JSON.parse(ris);
tryParseJSON(ris);
//return ris;
},
error: function() {
alert('Errore di rete');
}
}).done(function(){
if(divwhere!=""){
$(divwhere).html(risp);
}
if(actionAfter!=""){
eval(actionAfter);
}
});
the function for test json is here: stackoverflow
how can i do for create a correct call json? thank you very much
jQuery will automatically parse a JSON response for you - you don't need to do it again. The returned ris object is ready for you to work with as-is. Assuming the request works, there is no problem with the format of your PHP response.
success: function(ris) {
console.log(ris.status); // = 'success'
console.log(ris.mex); // = 'DA IMPLEMENTARE!!!'
},