When I send data into PHP file using AngularJS $http post, the data type is supposed to be a string. But when I try to get the output data from PHP file (I just simply echo $_POST['string']) by the then function, it automatically changes to [object Object] type somehow.
Here is the code:
JS:
$http({
method:"POST",
type:"json",
url:"./forms/crud.php",
data:{id:cId}
}).then(function (d) {
alert(d.config.data.id);
console.log(d);
})
PHP:
if(is_post_quest()){
echo $_POST['id'];
}
Output on console:
{data: "", status: 200, headers: ƒ, config: {…}, statusText: "OK", …}
The way I can access the id data is by typing d.config.data.id which is not exactly what I want.
I think the problem is that get data from AngularJs in PHP file is kinda different from that using AJAX.
For AJAX, geting data literally just need to use $_POST['id'].
However, for AngularJS HTTP POST request, need to type something like:
$data = json_decode(file_get_contents("php://input"));
echo $data->id;
And here is how it look right now.
{data: "568", status: 200, headers: ƒ, config: {…}, statusText: "OK", …}
You should do it like this
$http({
method:"POST",
type:"json",
url:"./forms/crud.php",
data:JSON.stringify({id:cId})
}).then(function (d) {
alert(d.config.data.id);
console.log(d);
})
I will do an example for requesting data from angular and getting into php code, then getting result back.
//Angular code
var url = 'your url';
var data = {
"type": "json",
};
//Ajax call
$http.post(url, data).success(function (data, status, headers, config) {
var result = angular.fromJson(data);
}).error(function (data, status, headers, config) {
$scope.preloader=false;
});
//PHP Code
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo json_encode(['data' => $this->request->data, 'status' => true, 'error' => '']);
Related
To receive my response object from my PHP server I have the code down below.
First of all, it works. What does not work is that if my first PHP condition is met, the success function in my Ajax responds correctly but only without using the data object.
This is my AJAX function:
$.ajax({
type: "PUT",
url: "http://server/register",
contentType: "application/json",
data: '{"username":"' + username + '", "password":"' + password + '"}',
success: function(data) {
console.log(data) // The output in my dev tools under Firefox is just a blank line, no error message or even "undefined".
console.log("Success") // Works!
if(data.status == 200){
console.log("Test 1") // Doesn't work. Although status code 200 is shown to me.
}
},
error: function(data) {
console.log(data) // This works! I can see the content of the object. The correct status code (409) is shown to me.
if(data.status == 409){
console.log("Test 2") // Works
}
}
});
This is my PHP function:
public function register($request, $response)
{
...
if(condition-1) {
echo("Condition 1 works!"); // Works.
return $response->withStatus(200);
} elseif(condition-2) {
echo("Condition 2 works!"); // Works too.
return $response->withStatus(409);
}
}
I don't see why there is no data object. I'm using the Slim 3 Framework and could probably return a JSON object like this:
$content = ["foo" => 'bar', ...] ; //Any data you wish to return
return $response->withJson($content);
But so far my whole code works without using JSON objects. Even if I var_dump the $response object, I can see that on the server side it is there.
if(condition-1) {
var_dump($response->withStatus(200)); // Works. I can see it.
}
There's a lot wrong here, so I've done my best to point out what I see wrong, and hopefully with the changes I'm going to suggest you will have success.
If you are trying to use data.status in your ajax success function, then it looks like you think you are returning json, but you aren't. Even if you are, you are corrupting it by echoing "Condition 1 works!".
So think about it, if you have a json response like this:
{'a':'1'}
And you echo something out before it, your response is corrupted, and looks like this:
Condition 1 works!{'a':'1'}
Same corruption occurs if PHP throws an error your way, so be aware of that.
You should also be declaring a dataType for your ajax request, so:
$.ajax({
type: "PUT",
url: "http://server/register",
contentType: "application/json",
data: JSON.stringify({
"username": username,
"password": password
}),
dataType: 'json', // <-- THIS LINE IS IMPORTANT
success: function(data, textStatus, jqXHR) {
// ...
},
error: function(jqXHR, textStatus, errorThrown) {
// ...
}
});
Note: you were single quoting your data object, so you were doing it the hard way. Just use JSON.stringify on a JS object like I did!
Since my code expects a json response, make sure to look at the other answer here, as it shows how to send back a proper json response with slim.
Finally, in your ajax success function, data.status is not ever going to be available. Docs for jQuery show that there are three parameters, (data, textStatus, jqXHR) and data is specifically for the data, not the HTTP status code or any headers.
I put together a full working example of a mini Slim app. It's fully tested and works (it's just not awesome, so don't laugh):
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
$app = new \Slim\App;
$app->get('/', function (Request $request, Response $response) {
$response->getBody()->write('<!doctype html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
$("p").on("click", function(){
var username = "kookoopapa";
var password = "gr3atp4ssWerd";
$.ajax({
type: "PUT",
url: "/register",
data: JSON.stringify({
"username": username,
"password": password
}),
contentType: "application/json",
dataType: "json", // <-- THIS LINE IS IMPORTANT
success: function(data, textStatus, jqXHR) {
alert( data.a );
alert( data.b );
},
error: function(jqXHR, textStatus, errorThrown) {
// ...
}
});
});
});
</script>
</head>
<body>
<p>Click</p>
</body>
</html>');
return $response;
});
$app->put('/register', function (Request $request, Response $response) {
$php_input = file_get_contents('php://input');
$vars = json_decode( $php_input, TRUE );
$content = [
'a' => $vars['username'],
'b' => $vars['password']
];
return $response->withStatus(200)->withJson($content);
});
$app->run();
Try to use the following return:
$content = ["foo" => 'bar', ...] ; //Any data you wish to return
return $response->withStatus(200)->withJson($content);
Vue-Resource Post Request:
this.$http.post(form.action, new FormData(form)).then(function (response) {
FetchResponse.fetch(this, response.data)
})
Request are Send as Content-Type:"application/json;charset=utf-8" But No data can be displayed by PHP Post.
Set Up Header Vue-Resource:
request.headers.set('Content-Type', '');
But Request Content-Type:", multipart/form-data; boundary=----WebKitFormBoundaryTsrUACAFB1wuhFOR"
there is a comma at the beginning of the query.
Jquery Post Request:
$.ajax({
url : form.action,
type : 'POST',
data : new FormData(form),
success : function (reqData) {
FetchResponse.fetch(ss, reqData)
},
});
The same query works seamlessly with jQuery. jQuery Content-Type: "multipart/form-data; boundary=----WebKitFormBoundaryTsrUACAFB1wuhFOR"
Issue:
https://github.com/vuejs/vue-resource/issues/398
Please try instead to post a simple JSON object and enable the 'emulateJSON' vue-resource option:
const formData = {
someProp: this.someProp,
someValue: 'some value'
};
this.$http.post(this.postUrl, formData, {emulateJSON: true})
.then(response => {
console.log(response.body);
}, response => {
console.error(response.body);
});
I send an ajax post request , and get a response, but it comes up empty. Is there is some details that need to be adjusted?
The idea is to send text that is submitted with a submit button. But just for testing, I have specified the data to be sent as "url": "helllo".
$(document).ready(function() {
$('form.ajax').on('submit', function(e) {
e.preventDefault();
var submitted = $(this),
destination = submitted.attr('action'),
method = submitted.attr('method'),
url_send = {
"url": "helllo"
};
$.ajax({
type: method,
contentType : 'application/json',
url: destination,
data: url_send,
success: function(response){
console.log(response);
},
error: function(){
console.log("there was an error");
}
});
The "method" (post) and "destination" is specified in the form. So "url_send" is the object which is sent. Should this be retrieved as {"url": "helllo"} on the other end, or is it nested inside an object?
In PHP with laravel,I have a controller function where the request is recieved:
$data = json_decode(file_get_contents("php://input"));
If $data is empty, it's returned:
return Response::json($data);
And that gives me
Object { }
You are passing data an object, so it will be urlencoded by jQuery.
urlencoded data is not JSON, so trying to parse it as JSON will fail.
You need to actually send JSON.
data: JSON.stringify(url_send)
An example of how my JSON data is like:
$scope.a = [{
"email": "keval#gmail",
"permissions": {
"upload": "1",
"edit": "1"
}
}, {
"email": "new#aa",
"permissions": {
"upload": "1",
"edit": "1"
}
}];
I want to post the same, and here's my approach:
$http({
method: 'POST',
url: 'backend/savePermissions.php',
data: {
mydata: $scope.a
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
});
And the PHP is to take the request and respond:
echo $_POST['mydata'];
I tried JSON.stringify before the call and json_decode while echoing it back; still didn't work. Been trying all the possibilities I can think of, and what I find on the web/other questions, but still not working.
I've made plnkr for you
http://plnkr.co/edit/K8SFzQKfWLffa6Z4lseE?p=preview
$scope.postData = function () {
$http.post('http://edeen.pl/stdin.php', {user:$scope.formData}).success(
function(data){
$scope.response = data
})
}
as you can see I'm sending a raw JSON without formating it, then in php
<?php
echo file_get_contents('php://input');
I read the JSON directly and echo it but you can do whatever you want
read more about php://input here http://php.net/manual/en/wrappers.php.php
I was using it for a long time for REST services to avoid transforming JSON to string to many times
I use this, with which I can send Array JSON:
var array = {}
array['key1'] = value1;
array['key2'] = value2;
$http.post(URL, array)
.success(function(data){
})
.error(function(){
});
try using $httpParamSerializer or $httpParamSerializerJQLike
$http({
method: 'POST',
url: 'backend/savePermissions.php',
data: $httpParamSerializer($scope.a),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
});
I am trying to send simple data to theservre, and I need a "rough and ready" way to do this.
This is what I have so far:
var emails = ['a#123.com', 'b#123.com', 'c#123.com'];
var ruff_json = "{ 'emails': [";
for (i in emails)
ruff_json += ((i == 0) ? '' : ', ') + '\''+emails[i]+'\'';
ruff_json += '] }';
jQuery.ajax({
type: 'POST',
url: '1.php',
data: ruff_json,
dataType: "json",
timeout: 2000,
success: function(result){
//do something
},
error: function (xhr, ajaxOptions, thrownError){
//do something
}
});
Using Firebug, I can see that the data is POSTed to the server - however, at the server, there is no data ($_POST is empty) - what am I doing wrong?
We post all of our data with json.
var myobj = { this: 'that' };
$.ajax({
url: "my.php",
data: JSON.stringify(myobj),
processData: false,
dataType: "json",
success:function(a) { },
error:function() {}
});
then in php we do
<?php
$json = json_decode(file_get_contents("php://input"), true);
// Access your $json['this']
// then when you are done
header("Content-type: application/json");
print json_encode(array(
"passed" => "back"
));
?>
This way we don't even mess with the post variables, and in general, its faster than having jQuery process them.
Your data field should contain an object with key-value pairs, because it gets encoded as POST key-values pairs.
data = {my_json: encoded_string};
Then on the PHP side you can access the data as:
$data = json_decode($_POST['my_json']);
PHP populates $_POST by parsing the data received. However, it only knows form-encoded data, JSON data cannot be parsed automatically. So $_POST will be useless in this case. You need to get the raw post data and parse it with json_decode.