Receive json post in php from browser - php

I am trying to receive and print json with this php code:
<?php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
?>
I am not receiving or printing any data. But if i use this ajax:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
(function($){
function processForm( e ){
$.ajax({
url:'http://mydyndns:8010/has/input_parameters_startReg.php',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ DeviceID: 23, ForceReg: 0, StartTime: "10/06/2015 17:45"}),
success: function (data) {
},
error: function (e) {
alert(e.responseText);
},
});
e.preventDefault();
}
$('#my-form').submit( processForm );
})(jQuery);
it is working, and i get the posted data printed in my browser. How can i alter my php so the direct hitting from browser will give me the result the ajax gives?

Function parse_str will do the job in combination with $_SERVER['QUERY_STRING']
<?php
parse_str($_SERVER['QUERY_STRING'], $output);
$json = json_encode($output);
echo $json;
?>

I don't think you'll be able to fetch it using GET because php://input seems to only read POST data. If you want to be able to use the GET data, you can refer to the $_GET global:
print_r($_GET);
Note that you can also use $_POST in place of php://input, but here's a question/answer on here that talks about that some:
PHP "php://input" vs $_POST
EDIT: Oops, I see this was answered while I was taking my sweet time.

Related

Decode a multipart array from jQuery to PHP via ajax

Ive finally managed to get this array build and sent to my PHP function via ajax however, I dont seem to be able to decode it / var_dump produces nothing in the response panel on success.
My arrays:
var data = JSON.stringify({
newEmailForm: newEmailForm,
properties: properties
});
Which produces this:
{"newEmailForm":[["coda#knoppys.co.uk","sikjdhf","Youe message here"]],"properties":[["31466","asdasd","asdads"],["31440","asdasd","asdad"]]}
My ajax function which is posting over the following array.
jQuery(function(){
jQuery.ajax({
url: siteUrl,
type:'POST',
action: 'elegantSendEmail',
data:data,
dataType:'json',
success:function(result){
console.log(result); //This returns nothing, not even 0
}
});
});
My PHP function. If i simply echo hello world then it works.
add_action( 'wp_ajax_elegantSendEmail', 'elegantSendEmail' );
function elegantSendEmail() {
$array = json_decode($_POST('data'), true);
var_dump($array);
wp_die();
}
You're not posting the data as form-encoded, so it won't be in $_POST. It will be sitting in the input buffer.
$your_json = file_get_contents('php://input');
$your_array = json_decode($your_json, true);
If you want to access the sent data in you php code through $_POST('data') you would want to send it in the data key
jQuery.ajax({
url: siteUrl,
type:'POST',
action: 'elegantSendEmail',
data: { data: data },
dataType:'json',
success:function(result){
console.log(result); //This returns nothing, not even 0
}
});

Getting an ajax post data in php

$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
dataType: 'json',
}).done(function(){
console.log('done');
});
Above is my AJAX post, below is my PHP:
var_dump($_POST['test']);
die();
The problem is, this fails to work (I get a NULL value) - why?
I know my call is getting to the PHP code as I can dump any old string:
var_dump('hello');
die();
Where am I going wrong?
Just remove this dataType: 'json'. Your $_POST['test'] is a string value, not a JSON string.
The POST value that you are testing with is not JSON, it's a string.
Remove the
dataType: 'json',
and it should work.
When you set dataType: "json" within the AJAX request it means the expected response should be parsed as json, (not the outgoing POST, as others have said).
Heres is a stripped down copy&paste example, for you to build upon. Hope it helps
<?php
//is it POST
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// set var
$test = isset($_POST['test']) ? $_POST['test'] : null;
//do some logic - skip that bit ;p
//was the request from AJAX, ok send back json
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//always a good idea
header('Content-Type: application/json');
//json encode, notice the ABC, then look at the jQuery below
die(json_encode(
array('ABC' => 'From Response: '.$test)
));
}
}
?>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function(){
var ajax = $.ajax({
url: "./",
type: "POST",
data: {test : 'test'},
dataType: "json"
});
ajax.done(function(data) {
$("#result").html(data.ABC); /* << See data is an object */
});
ajax.fail(function(xhr, status, error) {
$("#result").html(xhr.responseText);
});
});
</script>
<span id="result"></span>
I'm not totally sure if this is the issue, but .done is deprecated. Additionally, as others mentioned, you are asking for json from the server and not receiving json.
Your code should look like this
$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
success: function () {console.log('done');}
});
I would like to recommend you my code. and please do check the following points.
check the location of the url you are giving. If it is in parent directory then you can access it using ../ and the most important thing give the extension of the file. like 'gateway.php'
and write success and failure function. It gives a better insight of what's going on.
$.ajax({
type:'POST',
url:'gateway',
data:{test:'test'},
success: function(data){
if(data)
{
alert(data);
}
},
failure: function(){
alert(failed);
}
}) ;
comment if there are any errors
hope it helps :). If it does then don't forget to green it :P
Or change PHP code
header('Content-Type: application/json');
exit(json_encode(array('data' => 'Bla bla bla')));

$_POST not being set with AJAX call

This should be a fairly simple call but I just can't seem to make it work. Basically, I'm trying to pass a set of search parameters to a PHP script but $_POST is coming up empty. The call (via jQuery)...
self.search = function () {
var data = {
'year': 2013,
'month': 10,
'day': 1
};
$.ajax({
dataType: 'json',
type: 'POST',
url: 'repositories/blogposts.php',
data: { 'search': data },
success: function(results) {
// populate knockout vm with results...
}
});
};
The PHP code waiting to do something with the incoming json object...
if (isset($_POST['search'])) {
echo find_blogposts(json_decode($_POST['search']));
}
I've tried this many ways but no matter what, print_r($_POST) gives me an empty array. What's missing?
PHP is probably choking on the object you are trying to send.
You should either send the data object directly:
data: data,
(to get $_POST['year'], etc. in php)
or convert the object to a json string you can decode on the php side:
data: { 'search': JSON.stringify(data) },
What does happen inside of find_blogposts()?
Alternatively you could try .post().
$.post( "repositories/blogposts.php", { year: "2013", month:"10", day:"1" }, function( data ){
// do something here
});
In your php just receive $_POST['year'] which will be 2013.
Hope it helps.
Here is api doc for .post()

Can't post a JSON using $.ajax() or can't read it using php

I can't figure out where the problem is.
This is my JS function to post the JSON:
function send(var1, var2) {
var result;
att = window.location;
$.ajax({
'crossDomain': true,
'type': 'POST',
'async': false,
'global': false,
'data': {
"event_id": var1,
"status": var2
},
'url': att + 'post.php',
'dataType': 'json',
success: function (data) {
result = data['result'];
}
});
}
On the server side, this (file: post.php):
<?php
echo $_POST;
?>
only prints "Array".
The problem is that I have to send "data" in that exact format (I can't stringify it and then use the php json_decode() function). I also tried the « file_get_contents("php://input") » way, but still nothing.
I don't understand if the problem is that I can't properly post the json or that I'm not able to read it php-side.
Experiments with the GET method were fine.
Sorry for my bad english and thanks everyone for the attention.
To print array you can make use of print_r() function in php
<?php
print_r(json_encode($_POST)); //use json_encode() since dataType in ajax call is json
?>
To print individual values, you can make use of echo()
<?php
echo(json_encode($_POST['event_id']));
?>
try the following js function :
function send(var1,var2) {
$(document).ready(function(){
$.ajax(
{
url:"post.php",
data:{event_id: var1,status: var2},
success:function (data, textStatus){
alert(data['status']);
},
type:"post",
dataType: 'json'
}
);
});
}
and in server side "post.php" :
echo json_encode($_POST);

jquery ajax not working?

i have a jquery ajax post that for some reasons doesn't work:
<script>
var callback = function(data) {
if (data['order_id']) {
$.ajax({
type: 'POST',
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { myid: 123456 },
success: function(data) {
alert("Transaction Completed!");
}
});
}}
</script>
<?php if ($_POST['myid']) { echo $_POST['myid']; } ?>
the 'callback' functions works fine(i test it), just that it stops at the ajax post
and i cant see my echo's
any ideas on what i am doing wrong?
thanks
edit:
i edited the script a bit at the point where the ajax is posting successfully but i cant get the php to echo anything
If the AJAX - Call is succeeding now, you can't just echo anything with PHP. The data is sent to the client, but PHP is interpreted at the server. You're not sending an HTTP - Request anymore (which is pretty much the point of an AJAX-Call), so PHP is not going to do anything at this point.
You have to add your new content to the DOM with JavaScript. Try this and see if you get the message shown on your page. I append it to the body, because I don't know how your Markup and your returned data looks like:
$.ajax({
type: 'POST',
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { myid: 123456 },
success: function(data) {
alert("Transaction Completed!");
$('body').prepend('<p>Successful AJAX - Call</p>');
}
});
Then you can take a look at your data-variable with console.log(data), access the returned data and modify the DOM via JavaScript.
ok, for a start.
writeback("Transaction Completed!";
fix it to:
writeback("Transaction Completed!");
you have a trailing comma after 123456
data: { myid: 123456, },
you're missing a closing } to your callback function

Categories