Send JSON to PHP and get a response - php

I'm just learning how to use jQuery and PHP together. This is my first attempt, and I feel like I'm almost getting the concept. However, there's an issue I failed to address. When I post a JSON object to PHP script and try to return one of the parameters, I get the following error : "Trying to get property of non-object in ..."
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style id="jsbin-css"></style>
</head>
<body>
<button onClick="postData();">Submit me!</button>
<script>
function postData() {
var myData = {
'firstName' : 'John',
'lastName' : 'Doe'
};
$.ajax( {
type: "POST",
url: "postData.php",
contentType: "application/json",
data: myData,
success: function(msg){
alert(msg);
},
error: function(err) {
alert('error!' + err);
}
});
}
</script>
</body>
</html>
postData.php:
<?php
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
$output = $jsonData->{'firstName'};
echo $output;
?>

With a bit more work, you can achieve this using a REST client that will automatically handle data-type conversion and URL parsing among other things.
To name some of the advantages of using a REST architecture:
Simple.
You can easily scale your solution using caching, loading-balancing etc.
Allows you to logically separate your URL-endpoints.
It gives you the flexibility to change implementation easily without changing clients.
Try reading, A Brief Introduction to REST to get a better idea about the design pattern and it's uses. Of course you won't need to write a framework from scratch if you don't want to, since there are already several open-source PHP based implementations out there such as Recess PHP Rest Framework.
Hope this helps!

json_decode (depending on PHP version) defaults to returning an array, not an object. The proper way to access it would be:
$output = $jsonData['firstname'];
You'll also want it to return an associative array, so pass true as the second argument of json_decode.
$jsonData = json_decode($input, true);
What could alternately be happening is that the JSON is invalid, in which case PHP returns null. You can check for that:
if ($jsonData = json_decode($input, true) === null) {
// Do stuff!
} else {
// Invalid JSON :(
}

I put it a little bit more simple with the function post of jquery.
I hope you found it useful:
first your html and js:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-git2.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<style id="jsbin-css">
</style>
</head>
<body>
<button onClick="postData();">Submit me!</button>
<script>
function postData() {
$.post(
"postData.php",
{
firstName : 'John',
lastName : 'Doe'
},
function(msg)
{
alert(msg);
}
);
}
</script>
</body>
</html>
then your php:
<?php
echo $_REQUEST['firstName']." - ".$_REQUEST['lastName'];
?>

I finally figured it out:
js:
function postData() {
var myData = {
firstName: 'John',
lastName: 'Doe'
};
$.ajax({
type: "POST",
url: "postData.php",
data: JSON.stringify(myData),
success: function(msg){
alert(msg);
},
error: function(err){
alert('error!' + JSON.stringify(err));
}
});
}
php:
<?php
$input = file_get_contents('php://input');
$jsonData = json_decode($input);
$output = $jsonData->{'firstName'};
echo $output;
?>
When decoding you DON'T want to put "true" as the second argument, because then, it's not JSON but an associative array (or so I've read). If I put json_decode($input, true), then it won't work.

Related

How do you save a file to a directory given by an input type="text" with php?

I have a html page with jQuery and I used ajax to send data to the a php file to save the data.
I have seen other questions like this but none of them seemed to match my purpose.
The data is an iframe's srcdoc.
My html looks like this:
<iframe srcdoc="<h1>hello</h1>" id="iframe"></iframe>
<br />
<input type="text" placeholder="Filename to save as..." id="fn">
<input type="button" value="Save" onclick="saveDoc(document.querySelector('#fn').value)">
My jQuery and JS looks like this:
function saveDoc(e) {
let iframe = document.querySelector("#iframe");
let data = {"srcdoc": iframe.srcdoc, "lnk": e};
$.ajax({
type: "POST",
url: "saver.php",
dataType : "text",
contentType: "application/json",
data: data,
cache: false,
timeout: 3000,
success: function (data) {
alert("SUCCESS");
console.log(data);
},
error: function (e) {
alert(e);
}
});
}
And my php code looks like this:
<!doctype html>
<html>
<body>
<?php
if (isset($_POST["lnk"]) && isset($_POST["srcdoc"])) {
$myfile = fopen($_POST["link"], "w");
fwrite($myfile, $_POST["srcdoc"]);
fclose($myfile);
echo $_POST["lnk"];
echo "\n <br/>";
echo $_POST["srcdoc"];
} else {
echo "Error";
}
?>
</body>
</html>
When I run it, I get an alert message saying "SUCCESS". And the console.log gives me:
<!doctype html>
<html>
<body>
Error</body>
</html>
What is happening here, and what am I doing wrong?
contentType: "application/json"
You are explicitly sending this to the server as JSON - so you can not access it via $_POST. (PHP only populates $_POST for Content-Types application/x-www-form-urlencoded or multipart/form-data.)
Either remove contentType, so that it can fall back to the normal way of sending form data, or go read up on how to actually read POSTed JSON data in PHP. (That would involve reading the data from php://input first, see Receive JSON POST with PHP)

Ajax: unexpected character at line 1 column 1 of the JSON data

I'm new to AJAX. I've looked at previous postings and see this is a common question. The usual answer is that the data isn't actually in JSON format. This is certainly true in my case - the correct response is preceded by other data from earlier echo output, like this:
<button type="button" id="dotest" name="dotest" >SAVE</button>{"foo":"bar"}
This is the test code that creates this output:
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="../js/jquery-3.3.1.min.js"></script>
</head>
<body>
<?php include "../php/bin/test-bin.php"; ?>
<script src="../js/test.js"></script>
</body>
</html>
JS
$('#dotest').click(function(){testCode()});
function testCode()
{
$.ajax({
type: 'POST',
dataType: 'json',
data: {testvar:true},
url:'../php/bin/test-bin.php',
success: function(formdata) {
alert(formdata['foo']);
},
error: function(xhr, status, error) {
alert(xhr.responseText);
},
});
}
PHP
<?php
echo '<button type="button" id="dotest" name="dotest" >SAVE</button>';
if(filter_has_var(INPUT_POST, 'testvar'))
{
$myArr = array("foo" => "bar");
$json = json_encode($myArr);
return;
}
If I move the echo button statement to the end of the PHP code, the unwanted text doesn't appear in the response.
Have I some error in my code? Or is there some way to flush the PHP output after echo calls? I've tried flush() but it doesn't work.
Any help you can give would be good for my blood pressure!
EDIT
I've done what's suggested and put the Ajax call in a separate file. I get the same problem. In testing I've removed almost all the code, leaving this (the requires and defines do nothing at this point):
<?php
// include global constants etc
require_once(__DIR__.'/../inc/config.php');
require_once(__DIR__.'/../inc/errorhandler.php');
require_once(__DIR__.'/../inc/common.php');
// fl_data
#define('FL_PREVVAL', 0);
#define('FL_CURRVAL', 1);
$data = array('animal' => 'horse', 'vehicle' => 'cart');
$json = json_encode($data);
echo $json;
The Ajax response is an error, but xhr.responseText contains correctly formatted JSON.
If I remove the two define statements, the response is success with the same data. Putting back any code preceding the echo produces the same error situation.
What am I doing wrong!

How to ouput JSON in javascript?

I am trying to print the results of a json object from a php query into javascript.
So basically the query results looks like:
{"points":
[{"lat":40.766696929932,"long":-73.990615844727},
{"lat":40.688514709473,"long":-73.96475982666},
{"lat":40.714504241943,"long":-74.005630493164},
{"lat":40.704719543457,"long":-74.009262084961},
{"lat":40.693260192871,"long":-73.968894958496},
{"lat":40.760955810547,"long":-73.967247009277},
]}
When i try to get the php variable (using AJAX) containing the json object i get:
VM62:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
I tried googling to see how the error relates to my code but i still don't get it.
Can someone explain to me how to get the json in javascript?
<?php
$connect = pg_connect("host=127.0.0.1 dbname=datab user=thomas password=iamtom") or die("Could not connect: ");
$result = pg_query($connect,"SELECT geometry FROM table");
if (!$result){
echo '{"error":"no results"}';
}
$points= array();
while($row = pg_fetch_array($result)){
$coordinate = json_decode($row['geometry'])->coordinates;
$p = new stdClass;
$p->lat = $c_2[0];
$p->long = $c_1[1];
array_push($points, $p);
}
$output = new stdClass;
$output->points = $points;
echo json_encode($output);
pg_close($connect);
?>
Here is my HTML/JS:
<html>
<head>
<title>Simple Map</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$.ajax({
type: "GET",
dataType: "JSON",
url: "dab.php",
data: {
sataVariable: "here is some data send with GET method"
},
success: function(data) {
var j = JSON.parse(data);
document.writeln(data); // attempting to take the coordinates and store it in a variable
},
error: function(data) {
console.log(data);
}
});
</script>
</head>
<body>
</body>
</html>
Because you're feeding dataType: "JSON" into your call to jQuery.ajax() the data retrieved from the AJAX call is automatically being parsed from JSON to a JavaScript object (though I'd switch "JSON" to "json" to match the documentation):
"json": Evaluates the response as JSON and returns a JavaScript object.
Don't manually parse the response again using JSON.parse() in your success handler; just work directly with data.
Now that you have your data in a JavaScript object called data you can interact with it, e.g.
for (var i = 0; i < data.points.length; i++) {
console.log(data.points[i].lat, data.points[i].long);
}

angular $http.post() and php?

I know there are several posts on SO and on many blogs explaining how to get the JSON data that was sent to be read by php. Some use url-encoding, others file_get_contents.
Anyway, it doesn't work for me. I'm sure there is ridiculously easy explanation for it but my code simply doesn't work (the request is sent, the backend answers but that message is more or less always the same: nothing seems to arrive there !
So in my controller I have :
var request_data = {
firstname: 'Quentin',
lastname: 'Hapsburg'
};
$http.post("lib/api/public/blog/post", JSON.stringify(request_data))
.success(function(data) {
console.log(data);
})
And in the php file:
$data = file_get_contents("php://input");
$data = json_decode($data, TRUE);
var_dump($data);
The result is NULL !
Any suggestions on where my error is ???
EDIT: This might have something to do with the rewriting rules but is not a duplicate since the same answer does not solve this question !
try using application/x-www-form-urlencoded
$http.post(urlBase, $httpParamSerializer(object), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
}).then(function(r) {
callback(r);
});
and then php will be able to access to your posted object using $_POST
Please use this js file. It will work
Index.html:
<html>
<head>
<script src="js/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="mainCtrl">
sdadasdasd
</div>
<script src="app.js"></script>
</body>
</html>
app.js:
var app = angular.module("myApp", []);
app.controller("mainCtrl", function($scope,$http){
var request_data = {
firstname: 'Quentin',
lastname: 'Hapsburg'
};
$http.post("test.php", JSON.stringify(request_data)).success(function(data) {
console.log(data);
});
});

Ajax with CodeIgniter - data not received on server side

I have the following AJAX:
$.ajax({
type: "POST",
url: base+"tree/plant/",
data:{
name: $('#field_treename').val(),
summary: $('#field_summary').val(),
description: $('#field_description').val(),
address: $('#field_url').val(),
category: $('#field_category').val()
}
})
.done(function(resp){
$('#plant-tree-inner').html(resp);
});
base is my base URL, tree is a controller and plant is a method in that controller.
The URL is correct, the controller and method are in place, with correct names. I've made sure of that by echoing a string in the plant method and it appeared correctly on the client after the AJAX response.
However, none of the post data seems to be arriving at the server.
Doing echo $this->input->post('name'); inside the plant method gives an empty string. Doing var_dump($_POST) gives an empty array. I even tried giving parameters to the plant method but that just throws a missing parameter error.
So where is the data getting lost and why?
EDIT: I see now that my question is wrong. It has nothing to do with CodeIgniter, since the data isn't being sent at all. The field values are undefined according to Javascript, but they certainly exist in HTML:
<input type="text" id="field_treename" placeholder="Tree name" value="" />
Seems like something is wrong with jQuery library.
For test' sake, try to send request avoiding it.
You may try this also..
$.ajax({
type: "POST",
url: base+"tree/plant/",
data:{
name: $('#field_treename').val(),
summary: $('#field_summary').val(),
description: $('#field_description').val(),
address: $('#field_url').val(),
category: $('#field_category').val()
}
success:function(resp){
$('#plant-tree-inner').html(resp);
}
});
Try to simulate the problem in the very basic method like creating another directory in your localhost or server like this and create files as describe below.
in the index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>POST Sending Problem</title>
<script src="jquery-1.12.2.js"></script>
</head>
<body>
Link
<script src="custom_function.js"></script>
</body>
</html>
Create js file for example test.js and put this as test
function test (id, base) {
$.ajax({
type: "POST",
data: {
'id': id
},
url: base,
success: function(data) {
alert(data);
},
error: function(data) {
alert('no data');
}
});
}
Next create a php file your_phpfile.php
<?php
if (isset($_POST['id'])) {
echo $_POST['id'];
} else {
echo "no-result";
}
?>
This would help you determine the problem. If this works fine, try applying it using codeigniter.
Good Luck
User this one..
var request = "name="+$('#field_treename').val()+"&"
request += "summary="+$('#field_summary').val()+"&"
request += "description="+$('#field_description').val()+"&"
request += "address="+$('#field_url').val()+"&"
request += "category="+$('#field_category').val()
and in set as data=request. This should work.

Categories