This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 1 year ago.
I am using jQuery to submit the following request:
$.ajax({
url: encodeURI('/server/api/user/update.php/'),
method: 'POST',
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + utility.getJsonWebToken()
},
data: JSON.stringify(e.model),
dataType: 'json'
})
And I have the following PHP code that verifies that the request is valid and contains the necessary body:
// check for bad method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
$returnedJson['error'] = 'The supplied request method is not supported for the requested resource. This resource expects a POST request.';
echo json_encode($returnedJson);
return;
}
// check for bad request
$errors = array();
$user = new UserModel();
foreach (UserModel::$RequiredColumnNames as $property) {
$success = ControllerUtility::isValueInRequest($_POST, $property);
if (!$success) {
array_push($errors, $property);
continue;
}
$user->$property = $_POST[$property];
}
if (count($errors) > 0) {
http_response_code(400);
$returnedJson['error'] = 'Malformed request syntax. The following properties are missing from the request: ' . join(', ', $errors);
echo json_encode($returnedJson);
return;
}
Every time I submit the request, I get 400 error with the 'Malformed request syntax. The following properties are missing from the request: ...' error message.
I echoed the $_POST and $_REQUEST but in both instances and empty array is returned.
I verified that the request headers is a POST:
POST /server/api/user/update.php/ HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Authorization: Bearer -removed-
X-Requested-With: XMLHttpRequest
Content-Length: 180
Origin: http://localhost
Connection: keep-alive
Referer: -removed-
Sec-GPC: 1
And the fields are included in my request JSON:
{
"CreatedBy": null,
"CreatedOn": "2021-02-28 13:53:54",
"DeletedOn": null,
"Email": "-removed-",
"ModifiedBy": "1",
"ModifiedOn": "2021-02-28 16:35:51",
"UserId": "1",
"Username": "Adminn"
}
I have even removed the content-type header from my PHP without success. I've also tried just passing e.model instead of calling stringify in the AJAX request. At this point I'm at a loss as to what I'm doing wrong.
// echo the json string from php://input.
file_get_contents('php://input');
Related
I'm trying to read the contents of a webhook notification in php. The content of the request is in the link below:
Link POST
HEADERS:
Pragma: no-cache
X-Request-Id: fec7f2ea-ae08-4fc1-9f81-b7ed9b976100
X-Newrelic-Transaction: PxQDWVNWCgBWBlJWVldRV1dUFB8EBw8RVU4aVgANAQAAA1tSBQBVBFUFUkNKQQtVVlNTUVZQFTs=
Accept: text/html, image/gif, image/jpeg, *; q=.2, /; q=.2
Connect-Time: 2
Connection: close
Content-Length: 931
Cache-Control: no-cache
User-Agent: Java/1.7.0_72
Accept-Encoding: gzip
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Via: 1.1 vegur
X-Newrelic-Id: UgcDUFdVGwQAXFdRBAU=
Host: requestb.in
Total-Route-Time: 0
FORM/POST PARAMETERS:
data: { "event": "PAYMENT_UPDATED", "payment": { "object": "payment", "id": "pay_158657847699", "customer": "cus_artujit2nfYe", "value": 160.0, "netValue": 155.75, "originalValue": null, "nossoNumero": "34271724", "description": "", "billingType": "BOLETO", "status": "PENDING", "dueDate": "21/12/2016", "paymentDate": null, "invoiceUrl": "", "boletoUrl": "", "invoiceNumber": "00507815", "externalReference": null, "deleted": false } }
I tried unsuccessfully through the line code: $datasrc = $_POST;
I also tried to read with $ _REQUEST unsuccessfully.
How to read the content in php?
No clue what webhook is or does. But if it is sent as as POST request to a page in PHP, the data posted will be present in the $_POST array.
To see what's in it: var_dump($_POST); will show you the array and it's structure.
To get the value of a specific key: $variable = $_POST['key']; will do the trick.
If I interpret the stuff you posted correctly the json encoded content should be in $_POST['data']; .
To decode the json encoded string, PHP has helpful functions such as json_decode.
$data=json_decode($_POST['data'], true); should give you a PHP array with the data.
I'm trying to read $_FILES uploaded by my AJAX upload form. This is the POST request:
POST myhost.net/csv.php
Host: myhost.net
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:36.0) Gecko/20100101 Firefox/36.0
Accept: application%2Fjson%2C%20text%2Fjavascript%2C%20*%2F*%3B%20q%3D0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
X-File-Name: Europe_1351.csv
Content-Type: multipart/form-data; charset=UTF-8
Pragma: no-cache
Cache-Control: no-cache
Referer: http://myhost.net
Content-Length: 26
Cookie: PHPSESSID=kourjvs7rm980d2cg4qvaav965
Connection: keep-alive
And on the server side, I got:
var_dump( $_FILES );
Even though 'multipart/form-data' is set, there aren't any data in $_FILES variable. Does this have something to do with PHP configuration? Thanks!
EDIT:
Here is my code:
<script src="//raw.githubusercontent.com/LPology/Simple-Ajax-Uploader/master/SimpleAjaxUploader.js">
$(document).ready(function()
{
var sizeBox = document.getElementById('sizeBox');
var uploader = new ss.SimpleUpload({
button: 'uploadButton', // file upload button
url: 'csv.php', // server side handler
name: 'uploadfile', // upload parameter name
contentType: 'multipart/form-data',
responseType: 'json',
allowedExtensions: ['csv'],
maxSize: 10 * 1024, // kilobytes
hoverClass: 'ui-state-hover',
focusClass: 'ui-state-focus',
disabledClass: 'ui-state-disabled',
onSubmit: function(filename, extension)
{
this.setFileSizeBox(sizeBox); // designate this element as file size container
},
onComplete: function(filename, response)
{
if (!response) {
alert(filename + 'upload failed');
return false;
}
alert( 'file ' + response.data + ' uploaded successfully ');
// do something with response...
}
});
});
</script>
<div id='uploadButton'>
CSV
</div>
<div id='sizeBox'>
size
</div>
Use php inbuilt function print_r();
print_r($_FILES);
It's the first time for me using ajax on WP.
I am working on a simple contact form, and for some reason whenever I click submit I get an error:
on console:
POST http://54.xxx.xx.xx/wp-admin/admin-ajax.php 500 (Internal Server Error)jquery.js?ver=1.11.1:4 m.ajaxTransport.sendjquery.js?ver=1.11.1:4 m.extend.ajaxmain.js:66 (anonymous function)jquery.js?ver=1.11.1:3 m.event.dispatchjquery.js?ver=1.11.1:3 m.event.add.r.handle
on chromes "Networks":
Remote Address:54.xx.xx.xx:80
Request URL:http://54.xx.xx.xx/wp-admin/admin-ajax.php
Request Method:POST
Status Code:500 Internal Server Error
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:73
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:wp-settings-1=editor%3Dtinymce%26posts_list_mode%3Dlist; wp-settings-time-1=1424359234
Host:54.xx.xx.xx
Origin:http://54.xxx.xx.xx
Referer:http://54.xxx.xx.xx/?page_id=73
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
action:submit_contact_form
fullname:test
email:test#gmail.com
text:test
Response Headersview source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://54.xxx.xx.xx
Cache-Control:no-cache, must-revalidate, max-age=0
Connection:close
Content-Length:0
Content-Type:text/html; charset=UTF-8
Date:Thu, 26 Feb 2015 16:10:19 GMT
Expires:Wed, 11 Jan 1984 05:00:00 GMT
Pragma:no-cache
Server:Apache/2.4.7 (Ubuntu)
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Powered-By:PHP/5.5.9-1ubuntu4.5
X-Robots-Tag:noindex
This is my ajax part:
//send info to php
$.ajax({
beforeSend: function() {
if ( IsEmail(email) == false) {
$('#aboutUnsuccess').show("slow");
$('.form_content').hide("slow");
}
},
url: document.location.protocol+'//'+document.location.host+'/wp-admin/admin-ajax.php',
type: "POST",
/*action: 'submit_contact_form',*/
data: ({ "action": "submit_contact_form", "fullname": fullname, "email": email, "text": text }),
success: function (results){
if ( IsEmail(email) == true) {
//hide table
$('.form_content').hide('slow', function() {
$('.form_content').hide( "slow" );
});
//show textboxes
$('#aboutSuccess').show("slow");
$( "#aboutSuccess" ).append( "<iframe id=\"pixel-thing\" src=\"http://54.xxx.xx.xx/wp-content/themes/twentyfifteen-child/thePixel.html\" width=\"1\" height=\"1\" border=\"0\"></iframe>" );
}
}
});
});
And this is my php fucntion:
// Contact form Ajax
add_action('wp_ajax_nopriv_submit_contact_form', 'submit_contact_form');
function submit_contact_form(){
if(isset($_POST['email'])) {
$email = $_POST['email'];
$email_to = "mail#main.com";
$host = "ssl://smtp.gmail.com:465";
$username = 'mainmain#mail.com';
$password = 'pass';
$email_subject = "You have a new email from $email via asdasd.com website";
$message = $_POST['text'];
$headers = array ('From' => $email, 'To' => $email_to,'Subject' => $email_subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($email_to, $headers, $message);
if (PEAR::isError($mail)) {
echo($mail->getMessage());
} else {
echo("Message successfully sent!\n");
}
}
}
Whay might be the cause of the error?
I tried var_dump() the variables in the php functions.php file, They all display fine.
when I add require_once "Mail.php";
on the top of my php file, pages just stop loading. I'm not sure this is the problem. So I'm trying without it (?)
The error 500 is throwing because your server is not responding to your call.
Did you tried with at start of the php file.
error_reporting(E_ALL);
ini_set("display_errors", 1);
Use firebug so it will post you the call to server and response so you could see the error.
If you are seeing a blank page,then you missed a syntax somewhere in your PHP file. Have a look into your brackets, colons and semi-colons
Develop a simple backbone and php application but on a server i get 403 error
whenever i use a put method
Of course when using more traditional method such as get and post i do not get any problem.
Could any one advise on what is the specific settings to tune because on another server it work great.
My suspects are
apache configuration
php configuration
Thanks in advance.
Code Sample
PHP file
$this -> method = $GLOBALS['_SERVER']['REQUEST_METHOD'] ;
switch ( $this -> method ) {
case ( 'POST' ) :
foreach ( $_POST as $k => $v )
$data -> $k = $v ;
$data = $this -> save ($data) ;
$this -> output( $data ) ;
break
case ( 'PUT' ) :
$putdata = fopen("php://input", "r");
while ($d = fread($putdata, 1024))
$data .= $d ;
$data = json_decode( $data ) ;
$data = $this -> save ($data) ;
$this -> output( $data ) ;
break ;
case ( 'DELETE' ) :
$data = $this -> delete($data) ;
$this -> output( $data ) ;
break ;
case ('GET') :
default:
$data = $this -> retrieve () ;
$this -> output( $data ) ;
break ;
}
Note that backbone does not need form using jquery ajax to make an xhr request
arguments: {
0: {
contentType: "application/json"
data: {
"id":0,
"dat":"10-03-2014",
"title":"Bunk bed",
"current":false,
"enrole":[],
"result":"",
"starts":{"m":{},"f":{}},"sex":"m"}
}
dataType: "json"
emulateHTTP: false
emulateJSON: false
error: function (resp) { ... }
parse: true
processData: false
success: function (resp) { ... }
type: "PUT"
url: "event" // event is a folder with index.php
validate: true
}
}
Backbone.$.ajax.apply(Backbone.$, arguments);
Here is the request made by the browser
Request Method:PUT
Status Code:301 Moved Permanently
Request Headersview parsed
PUT /maa/event HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 123
Cache-Control: no-cache
Pragma: no-cache
Origin: http://localhost
X-Requested-With: XMLHttpRequest
Content-Type: application/json
Accept: application/json, text/javascript, */*; q=0.01
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36
Referer: http://localhost/maa/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,fr;q=0.6,fr-FR;q=0.4
Request Payloadview parsed
{"id":0,"dat":"10-03-2014","title":"Acton Vale","current":false,"enrole":[],"result":"","starts":{"m":{},"f":{}},"sex":"m"}
Everything work except for the put which generates a 301 error
I am trying to send JSON data from a form using the XMLHttpRequest object. I can send the data using the following function. There are no errors displayed in FireBug and the JSON-data in the request is displayed well formed by FireBug.
However, I send the data to echo.php, what simply returns the content:
<?php
print_r($_POST);
print_r($_GET);
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
echo file_get_contents('php://input');
?>
The POST-array is always empty, but I can see the JSON string returned by file_get_contents. How does that happen? What am I doing wrong?
output of echo.php
Array
(
)
Array
(
)
Host: localhost
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: eo,de-de;q=0.8,de;q=0.6,en-us;q=0.4,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Referer: http://localhost/form.html
Content-Length: 88
Cookie: {{..to much data..}}
Pragma: no-cache
Cache-Control: no-cache
{"type":"my_type","comment":"commented"}
the sending function:
function submit(){
var data={};
data.type=document.form.type.value;
data.comment=document.form.comment.value;
//get right XMLHttpRequest object for current browsrer
var x=ajaxFunction();
var string = JSON.stringify(data);
x.open('POST','echo.php',true);
x.setRequestHeader('Content-type','application/json; charset=utf-8');
x.setRequestHeader("Content-length", string.length);
x.setRequestHeader("Connection", "close");
x.onreadystatechange = function(){
if (x.readyState != 4) return;
if (x.status != 200 && x.status != 304) {
alert('HTTP error ' + req.status);
return;
}
data.resp = JSON.parse(x.responseText);
if(data.resp.status=='success'){
alert('That worked!');
}else{
alert('That didn\'t work!');
}
}
x.send(string);
return false; //prevent native form submit
}
PHP does not process JSON requests automatically like it does with form-encoded or multipart requests. If you want to use JSON to send requests to PHP, you're basically doing it correctly with file_get_contents(). If you want to merge those variables into your global $_POST object you can, though I would not recommend doing this as it might be confusing to other developers.
// it's safe to overwrite the $_POST if the content-type is application/json
// because the $_POST var will be empty
$headers = getallheaders();
if ($headers["Content-Type"] == "application/json")
$_POST = json_decode(file_get_contents("php://input"), true) ?: [];
Quick note: you should not be sending a charset with your Content-Type for application/json. This should only be sent with text/* Content-Types.
You forgot to name your variables in the send function.
The good way to use it is
x.send('name1='+string+'&name2=value2');
Given that, I think you will have to change the content-length header. I don't think it is usefull to send it.
One another thing you can do is try with GET method.
You can also try to change your content-type header by that one :
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")