angularjs - POST an array of objects(JSON data) to a PHP page - php

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);
});

Related

angularjs $http post request making string data into an object

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' => '']);

AJAX POST JSON to PHP issue No DATA in PHP

I am having trouble sending $_POST data via jQuery Ajax. I have read over everything I can find regarding the matter and still I am getting nowhere. I have even gone back to very basic data and still nothing, the JSON data has been validated using the JSON validate site. For the life of me I cannot echo/print_r/var_dump or get access to any data.
My JavaScript:
$('#updateJSON').click(function(){
var content = [{
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
}];
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: content},
cache: false,
success: function(){
alert("success");
console.log(content);
window.location = "test.php";
},
error:function(){
alert('ajax failed');
}
});
});
My PHP:
<?php
if(isset($_POST['data'])) {
$json = stripslashes($_POST['data']);
var_dump(json_decode($json, true));
} else {
echo "No Data";
}
?>
So I do get the alert("success"), and then get redirected to test.php
once at test.php I get the echo "No Data".
Thanks in advance for any help with this issue.
The reason is you are using window.location to redirect to the PHP file (without any post data) instead of posting the form on test.php.
You should either post the form without ajax on test.php.
Or use the response from test.php in your success function.
$('#updateJSON').click(function(){
var content = [{
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
}];
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: content},
cache: false,
success: function(response){
alert("success");
console.log(response);
//window.location = "test.php";
},
error:function(){
alert('ajax failed');
}
});
You are passing data as a string to ajax file. Please use JSON.stringify(conten) to pass data as a json format in ajax file.
use
data: {data: JSON.stringify(content)}
in place of
data: {data: content}
Use:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
Then access each field as follows:
$field1 = #$request->field1Name;
$field2 = #$request->field2Name;
etc..
EDIT:
Well, the first part of the answer is still valid.
I've tried your code and slightly modified it on my machine, and i was able to access the whole data as you will see below:
Javascript: removed the square brackets from the outside of your JSON and removed the curly brackets from the 'data' part of the ajax since they are not necessary
as you can see, i've also added the "data" to the success function so i can debug the response from test.php better
$(document).ready(function(){
$('#updateJSON').click(function(){
var content = {
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
};
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: JSON.stringify(content),
cache: false,
success: function(data){
alert(data);
console.log(content);
},
error:function(){
alert('ajax failed');
}
});
});
});
PHP:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$field1 = #$request->id;
echo $field1;
and $field1 is echoed as "21", the correct answer
You can apply this to your code and check also.
Thanks everyone for the help I have managed to figure it out with the help of each of you.
I needed to create in the test.php file a, $json = array(), and then populate the array, $json[] = json_decode($_POST['data']);
that then allowed me to place the contents in a JSON file.
here is the php code:
<?php
$json = array();
if($_POST['data']) {
$json[] = json_decode($_POST['data']);
file_put_contents("../JSON/test.json",json_encode($json));
} else {
echo "No Data";
}
?>
and as long as the file "JSON/test.json" exists then it will write the JSON passed from the JS.
I would like to note:
without the JSON.stringify(content); the data is NULL so thank you # Rahul Patel for making sure this was being applied.
the JSON data is valide according to the JSON validate site.
also just for keeps sake the JS code:
$('#updateJSON').click(function(){
var content = {
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
};
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: JSON.stringify(content)},
cache: false,
success: function(){
alert("JSON Updated");
},
error:function(){
alert('ajax failed');
}
});
});

Angularjs - Cannot pass parameter

I'm using Angularjs for my mobile app project. My problem is I can't pass my all my parameters to my own API. My API can't detect any post parameters that my app send to it.
$http.post("http://xxxxxxxx/api/verify_login.php", {
"username": "admin",
"password": "12345678",
"secret_key": "123456789"
}).success(function(data, status, headers, config) {
alert(JSON.stringify(data));
}).error(function(data, status, headers, config) {
alert(JSON.stringify(status));
});
If using Postman it works.
how about this :
var postData = '{"username":"'+varUsername+'", "password" : "'+varPassword+'", "secret_key" : "'+varSecretyKey+'"}';
$http({
method: 'POST',
url: 'http://xxxxxxxx/api/verify_login.php',
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
$scope.result = response;
alert(JSON.stringify(data));
});
This will post data as :
username=hisname&password=hispassword&secret_key=hiskey
keep in mind that, angularjs will automatically convert your postdata as JSON.
Looks like this StackOverflow answer helps solve half the problem. Look at the accepted answer. To paraphase the quote on this post:
By default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.
There is a nice way to get it do this - override the default transformRequest - this is show in a nice post by Ben Nadel here - Here's a snippet:
var request = $http({
method: "post",
url: "process.cfm",
transformRequest: transformRequestAsFormPost,
data: {
id: 4,
name: "Kim",
status: "Best Friend"
}
});
He has a fairly simple implementation - if you find that this doesn't work for you, you can use the a detailed version here - you can inject this factory in your controller.
.factory("transformRequestAsFormPost", function() {
function transformRequest(data, getHeaders) {
var headers = getHeaders();
headers["Content-type"] =
"application/x-www-form-urlencoded; charset=utf-8";
return (serializeData(data));
}
return (transformRequest);
function serializeData(data) {
if (!angular.isObject(data)) {
return ((data === null) ? "" : data.toString());
}
var buffer = [];
for (var name in data) {
if (!data.hasOwnProperty(name)) {
continue;
}
var value = data[name];
buffer.push(encodeURIComponent(name) + "=" + encodeURIComponent((value ===
null) ? "" : value));
}
var source = buffer.join("&").replace(/%20/g, "+");
return (source);
}
});

Retrieving JSON array in Javascript from PHP

I am attempting to return a json encoded array to JS from PHP and i've done so many times before but now i'm getting a weird error. I am successfully getting the data and it's displaying the array in chrome. However, I cannot get it to enter the AJAX success function if I specify the dataType: 'json'. If I remove the dataType and use var parsed = JSON.parse(data); it will enter the success function but it will throw an unexpected type error. Please help.
Chrome output:
[
{
"fullURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s912/2010raptor_firstdrive002_opt.jpg",
"thumbURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s128-c/2010raptor_firstdrive002_opt.jpg",
"location": "",
"caption": "",
"tags": "",
"program_instance_id": "a0Ji0000001pPO6EAM"
},
{
"fullURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s912/220px-Microchip_PIC24HJ32GP202.jpg",
"thumbURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s128-c/220px-Microchip_PIC24HJ32GP202.jpg",
"location": "",
"caption": "",
"tags": "",
"program_instance_id": "a0Ji0000001pPO6EAM"
}
]
PHP
$arr = array();
foreach($photoURLS as $photo)
{
$arr[] = $photo;
}
}
echo json_encode($arr);
JS
$.ajax
({
async: "false",
type: 'POST',
data: {action: 'var1', albumName: 'var2'},
dataType: 'json',
url: '/controller/function',
success: function(data)
{
//alert($.isArray(data));
$.each(parsed, function(i, index) {
alert(index.fullURL);
});
}
});
So I worked the code back and think this solution might work for you.
$.ajax({
async: "false",
type: 'POST',
data: {
action: 'var1',
albumName: 'var2'
},
dataType: 'json',
url: '/controller/function',
success: function(data) {
$.each(data, function(index, element) {
console.log(index);
console.log(element.fullURL);
console.log(element);
});
}
});
I can't test the ajax event however I have tested out the json you provided with the each loop and it seams to work. LINK TO FIDDLE
var data = [{
"caption": "",
"fullURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s912/2010raptor_firstdrive002_opt.jpg",
"location": "",
"program_instance_id": "a0Ji0000001pPO6EAM",
"tags": "",
"thumbURL": "https://lh6.googleusercontent.com/--ZKG_L-SA9c/UgqECNqP4II/AAAAAAAAA2I/i5nCa3CvKqM/s128-c/2010raptor_firstdrive002_opt.jpg"
}, {
"caption": "",
"fullURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s912/220px-Microchip_PIC24HJ32GP202.jpg",
"location": "",
"program_instance_id": "a0Ji0000001pPO6EAM",
"tags": "",
"thumbURL": "https://lh3.googleusercontent.com/-kyUg7_Rul90/UgqEDIu4DhI/AAAAAAAAA2Q/WF0BAEI7smo/s128-c/220px-Microchip_PIC24HJ32GP202.jpg"
}];
$.each(data, function (index, element) {
console.log(index);
console.log(element.fullURL);
});
also good news is that your json is 100% valid so what is being passed back seams correct. Hope this helps
Maybe you need to send the correct HTTP header with your response.
See here: https://stackoverflow.com/questions/267546/correct-http-header-for-json-file
The variable parsed at your $.each function is not defined. you should use data instead of parsed as data is the variable at your success callback function.
$.each(data, function(i, index) {
alert(index.fullURL);
});

PHP Web Service with json not working

I am new to web services.I have the following code and when I try to run it on the local host I am not geting the required output...it shows FirstName:undefined LastName:undefined..
following is my code
$(document).ready(function(){
var employees = [
{ "firstName":"John" , "lastName":"Doe" }
];
$.ajax({
url: "MyService.php",
type: "POST",
data: employees,
dataType: "json",
success:function(data) {
alert("Firstname:"+data.firstName+", LastName: "+data.lastName);
},
error:function(data) {
alert('error');
} });
});
The php code is
echo json_encode($_POST);
The value of data should be an object. You are passing an array containing an object. Get rid of the array.
This:
var employees = [
{ "firstName":"John" , "lastName":"Doe" }
];
… is submitting the following to the server:
undefined=
It should be:
var employees = {
"firstName": "John",
"lastName":"Doe"
};
which would submit this:
firstName=John&lastName=Doe
Additionally, you don't appear to be specifying a Content-Type header, so PHP is defaulting to text/html. This is forcing you to write JavaScript that says "Don't believe the server, threat this as JSON and not HTML".
You can fix that with:
header('Content-Type: application/json');
echo json_encode($_POST);

Categories