saving json data to json file using ajax PHP - javascript

My json file looks like this:
count_click.json
[
{
"link": "google.com",
"count": 2
},
{
"link": "yahoo.com",
"count": 3
}
]
now I open this file using
$.getJSON('count_click.json',function(data){
// do something with data
var stringData = JSON.stringify(data);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'http://127.0.0.x:3xx9/update.php',
data: {stringData: stringData},
success : function(d){
alert('done');}
})
}) // end of getJSON function
update.php
<?php
$a = file_get_contents("php://input");
file_put_contents('http://127.0.0.x:3xx9/count_click.json', json_encode($a));
?>
I get error in the browser console:
POST http://127.0.0.x:3xx9/update.php 404 (Not Found)
But the file is there. When I go to this http://127.0.0.x:3xx9/update.php in the browser, I see the contents of the php fine perfectly fine.

You could edit your PHP:
<?php
$a = $_POST['stringData'];
// you should check $a consists valid json - what you want it to be
file_put_contents('count_click.json', $a);
You really should check that posted data to be valid and not saving something unwanted. Also you could check that request really is POST -> $_SERVER['REQUEST_METHOD'].
Maybe you find some other methods to improve security (for example only allow post from own domain...).

A few problems.
file_get_contents("php://input"); Why? You are already sending a Post with data, no need to complicate things with a stream.
Also file_put_contents needs the path to the actual file on disk, not a URL!
data: {stringData: stringData} from your AJAX request means you can access it on your server with $data = $_POST['stringData'];.
Simply echo something out to see if you are actually getting anything.
echo json_encode( array("Payload" => $_POST['stringData']) );
If that doesn't work, try accessing the endpoint with your browser (not the file as that does not need PHP for the browser to read it).
Point your browser to http://127.0.0.x:3xx9/update.php and on your server, simply
echo "Request received!";
If you see that in your browser, your endpoint is working and you can continue troubleshooting. If you don't, then this is beyond JS and PHP and probably has to do with your server's settings. If you are using RStudio's Shiny Server, then that does not work for PHP
In any case, your endpoint should always return something when called. Not just save the file. It is just good practice.
header("HTTP/1.1 200 OK");

Related

PHP and AJAX internal 500 error

I have a strange problem, when I send data in POST with AJAX in JQuery to query SQL in php and push the data in array, the server return 500 error.
This the php file :
require_once 'db_connect.php';
$objConn=new ConnectionDB();
$connection=$objConn->ConnecteDB();
header('Content-Type: text/plain');
$dataRetourn=$_POST["test"];
$debut=$_POST['debut'];
$fin=$_POST['fin'];
$proute=array();
$i=0;
$i=0;
foreach ($dataRetourn as $data){
$imei = $data["aniImei"];
$requete="SELECT latitude, longitude, dateHeure
FROM anilog
WHERE anilog.imei='$imei' and dateHeure BETWEEN '$debut' AND
'$fin'
ORDER BY dateHeure ASC";
$resultat1=mysqli_query($connection,$requete);
while($donnees=mysqli_fetch_assoc($resultat1)){
$dataRetourn[$i]["path"][]=$donnees;
}
$i=$i+1;
}
echo json_encode($dataRetourn);
mysql_close($connection);
My query AJAX :
var options = {
url: "js/controller/getParcours.php",
dataType: "text",
type: "POST",
data: { test: parcours, debut : datep.debut, fin: datep.fin}
};
$.ajax(options).done(function(data){console.log(JSON.parse(data));});
PS: the PHP version on the server is the 5.3
And the variable parcours in query AJAX is $dataretourn in php script and it's an array of object
A HTTP 500 error code always means there is something wrong with your serverside code, your case being your PHP script. This may either be a syntax error or a bug.
You should be able to find more information in your server log, if you are using nginx this would be /var/log/nginx/error.log and if you are using apache, this would be /var/log/apache2/error.log (unless otherwise specified in your VirtualHost/site configuration).
However it is highly discouraged to use PHP 5.3 since it is deprecated, more information here: PHP version lifetime

jQuery AJAX PUT request data submission not working

I have a PHP file which contains the following:
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
echo '{ "response": "' . $_REQUEST['id'] . '" }';
}
Now I want to make an AJAX call to this file via jQuery:
var send = {
id: 10
};
$.ajax({
data: send,
method: 'PUT',
url: "myphpfile.php",
success: function(responseData) {
console.log(responseData.response);
}
});
This should return 10 as a response, however the output is empty. In the PHP file I also tried writing the id to a text file, which turned out to be empty as well. This means that my PHP code isn't the problem here, it's JavaScript.
When I change the AJAX url to myphpfile.php?id=10 however, the response is correct and 10 is logged to the console.
I have tried a lot of things to fix this, nothing worked. This includes setting contentType: 'application/json; charset=utf-8', dataType: 'json' and data: JSON.stringify(send). I can't find any more forum questions or articles on this and the ones I found didn't work.
Any help is appreciated.
You cant access the data from a PUT request via $_REQUEST. You'd need something like:
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
parse_str(file_get_contents("php://input"),$sent_vars);
echo json_encode(['response'=>$sent_vars['id']]); // use an array and json_encode to avoid messy string concatenation
}
See also Accessing Incoming PUT Data from PHP
So there are a couple of issues here:
PUT requests handle data parsing differently to POST, which is how you've formatted your request. So Delighted's response for more details.
You return a json string but don't convert it into a js object. You need something like $.parseJSON(...) for the object to return properly. So something like:
success: function(responseData) {
var r = $.parseJSON(responseData);
console.log(r.response);
}

Why php json response does not send back the data array to ajax jquery request?

I have made an ajax request to the php server where I send a data from a form request and I would to get back the same data from the server just for testing requests and responses of the same data throwing between the client and the server.
$.ajax({
method: "POST",
url: "addRaces",
dataType: "json",
data : sending_data,
success : ...
})
sending_data is an array like {field_form_name : value}
The server responds to the request with the following code :
$data = [];
foreach ($request->Input() as $key => $value) {
$data[$key] = $value;
}
return json_encode($data);
The same data should come back to the client, but nothing happen with an alert(response) or a jquery showing debug data like $('#debug').html(response);
The strange thing coming up when I try to push the server answer like
return json_encode([
'debug' => $data['name']
]);
and showing results to client like
$('#debug').html(response.debug);
it is working for a single key-value response showing the properly value field I have send from the client.
Other wise whether I send the full data as an array nothing is shown in the debug area of the client.
return json_encode($data); wont work. as it is returning the json string to the calling method which is not your jQuery at front end. Don't confuse front end (html javascript, jQuery, etc...) with back end (PHP) the two of them are running in different machines. One at client end and another at your server.
you should use echo json_encode($data); this will output the json string and your web server will send it to the front end.
Make sure you are echoing the data not returning as #bansi said, if you are echoing it already then debug using var_dump(json_encode($data)) . If json_encode() found errors it will return False instead of the expected json array.
You should debug using the developer tools instead of using code $('#debug').html(response.debug);. The Network tab of developer tools is very useful to debug HTTP requests, it will show response header and body of your requests.
In your case, just change return to echo like #bansi's answer. The return command does not print the data so you did not get anything in the response.

JQuery $.ajax request returns me "Error 404" even if the resource exists

I'm developing an app with TideSDK and I need to send some data to a PHP script that will create a file to store it on the pc. I'm pretty new to AJAX and to send data I do:
var jsonString = JSON.stringify(GW2.items);
$.ajax({
url: "/assets/scripts/save.php",
type: "post",
dataType: "json",
data: { jsonString: jsonString }
}).done(function(data){
console.log(data);
});
Where GW2.items is a JSON object, "save.php" is my script and jsonString is the variable I want to send.
But, when I try to execute the program it returns me:
POST http://127.0.0.1:52432/assets/scripts/save.php 404 Not Found
And the answer is: Cannot POST /assets/scripts/save.php
This is the PHP script:
<?php
$jsonString = $_GET['jsonString'];
return {};
?>
I checked the path and it's correct so why it can't find my file?
Did you try your path with POST or just GET? It could be exist for GET requests (pasting the url on a browser) but probably not for POST or other HTTP verbs.
You can use REST clients like Postman to be sure, which is also a Chrome extension.

Why is my Angular POST request to a PHP page not setting up the POST array?

I have a angular post that sends to my php file, but in the PHP file, I cannot access anything from the post variable. It returns my SUCCESS string, but nothing after that, so my return on the post is "SUCCESS - - - - - " where the data should be between the dashes.
JSON/JS object:
DESCRIPTION: "123321"
LOCATION: "ab_calgary_eighth_ave_pl"
NAME: "123321"
QUANTITY: 123321
TYPE: "cycle"
Angular POST Code:
$scope.insertNewInventoryItem = function()
{
if(typeof ($scope.newItem.LOCATION) == 'undefined')
alert("LocationCannot Be Empty. Please Select An Option From The Drop Down.");
else if(typeof ($scope.newItem.TYPE) == 'undefined')
alert("Type Cannot Be Empty. Please Select An Option From The Drop Down.");
else
{
$http.post("dataaccess/addnewinventory.php", $scope.newItem).then(onAddNewComplete, onAddNewError);
}
}
PHP Page attempting to find the posted values:
<?php
$con = mysqli_connect("localhost", "dbadminuser", "password", "database_demo_inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "FAIL - Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "SUCCESS - " . $HTTP_POST_VARS['newItem.NAME'] . " - " . $HTTP_POST_VARS['TYPE'] . " - " . $HTTP_POST_VARS["QUANTITY"] . " - " . $HTTP_POST_VARS . " - " . $_POST[0];
}
mysqli_close($con);
?>
Picture of the Request from GOOGLE developer tools:
Picture of return data from the request (see PHP code for where SUCCESS is coming from):
Why can I not access the post variables? Am I missing something here?
By default, Angular transmits data using the Content-Type: "application/json" and PHP can't parse the JSON data into the $_POST natively. You could follow these two steps to resolve this issue:
Step 1: Change the default value of header Content-Type:
angular.module("myApp",[], function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
})
Step 2: Convert the JSON data into key=value pair serialized data. (I'm using jQuery $.param function to convert the data)
$http({
method:"POST",
url: "post.php",
data: $.param($scope.newItem)
}).success(function(data, status, headers, config){
console.log(data);
}).error(function(data, status, headers, config){
console.log(status);
});
Note: $HTTP_POST_VARS is not a super global variable and it has been completely deprecated in PHP 5. I think you could use $_POST.
while chickenrice's answer is true and solves the issue, I'd prefer to use the JSON data as the payload at least for few reasons.
suits if your objects are complicated, contains nested structures.
It allows you to send any kind of object e.g. [[1,2],[3,4]] -
Array(array,array..) This is just impossible to send in uri-encoded
string.
It's not comfortable if you send simple "name=egor&type=lulzsec"
since it will look "verbose".
You CAN omit CSRF tokens with this!
To get this in PHP make use of file_get_contents("php://input"); to get the request body directly.
You would need to have a small wrapper around this. Moreover you might need to whitelist the content type headers to mitigate the CSRF.
EDIT
if (0 === strpos($_SERVER['CONTENT_TYPE'], 'application/json')) {
$input_json = file_get_contents('php://input');
$input= json_decode( $input_json, TRUE ); //convert JSON into array
}
My backend is Apache22/PHP5.4. I've been banging my head against the wall on this issue for days. Just now, I finally cracked it.
Setting content-type to application/x-www-form-urlencoded didn't get the data into input:// or $_POST. Then I came across this thread: https://groups.google.com/forum/#!topic/angular/MBf8qvBpuVE
Not setting Content-Type will make the underlying XHR browser implementation add a correct header
The keys is to set content-type: false. This is my working code, and I don't even have to get the data from input:// it goes directly to $_POST.
var serialized = $httpParamSerializer($scope.formData);
return $http({
method : 'POST',
url : 'your-url-here',
data : serialized,
headers : { 'Content-Type': false }
}).then(
function(response) {
return response;
},
//Network or server error
function(data, status, headers,config,statusText) {
console.log('AJAX failure: status='+status+', statusText='+statusText);
}
);
I am very new to AngularJS, and so I have no idea why setting the header didn't work for me.
For decoding the PHP, I used the following code, which gave me direct access into the POST data, which in my case was JSON. Apparently JSON is a unsupported data structure, so PHP failed to parse it automatically into the POST array:
$jsonText = file_get_contents('php://input');
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode('[' . $decodedText . ']', true);
Explanation:
Line 1 gets the raw data that was sent over from the request (in this case it was from the Angular Controller posted in the OP.
Line 2 decodes the JSON array grabbed in step one, correctly forming it to parse later. Note that in this case, steps one and two both return the exact same looking object.
Line 3 takes the formatted JSON data and decodes it into a PHP array. Now you can use the following to access parts of the array:
$myvar = $myArray[0]["SOME_VARIABLE"];
Thanks for the answers guys!

Categories

Resources