I'm trying to decipher how to get the json post from a JavaScript file to a PHP file.
This is my JS file:
var url2 = '/php/extractkeywords.php';
var jsonData = angular.toJson({
text: $scope.userTyping,
data: post
});
$http({
url: url2,
method: "POST",
data: "data=" + window.btoa($scope.textHTML),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
// Sending to extractkeywords.php
})
And this is my PHP file:
$data = json_decode(urldecode(base64_decode($_POST["data"])));
When I try to print $data, I don't get anything.
You need to pass JSON, here:
data: "data=" + window.btoa($scope.textHTML),
you are using the equals sign, which should not be used. JSON can have objects, arrays and key-value pairs, so you need a key. I believe this would improve your code:
data: {data: window.btoa($scope.textHTML)},
Related
I am using angular js and php. I have an array to post in my controller from js file. I have converted my array to JSON and tried to pass the data like below
var update = {
method: 'POST',
url: apiPoint.url + 'up.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params :{
alldatas: JSON.stringify($scope.alldata) ,
section : 'A',
}
By doing this I am getting 414 status error code. The url is too long.
So I have tried JSONC to pack my data..
I use jsonc.min.js and have updated my code as below.
var update = {
method: 'POST',
url: apiPoint.url + 'up.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params :{
alldatas: JSONC.pack($scope.alldata) ,
section :'A',
}
Now my data is passing through url and in my controller I get the data. But I can't unpack the data. Please help me to unpack the data.
I suppose you are using the standard $http component, and the mentioned JavaScript object stands for its configuration object.
You should pass JSON data through POST, i.e. the request body, because the request URI length is limited. The params option is serialized into GET.
So you need to move your data (alldatas) into data option:
var req = {
method: 'POST',
url: apiPoint.url + 'up.php',
data: { alldatas: $scope.alldata },
// you might even stringify it
//data: JSON.stringify({ alldatas: $scope.alldata }),
headers: { 'Content-Type': 'application/json;charset=utf-8' },
params: { section : 'A' }
};
$http(req).then(function (response) {
console.log(response.data);
});
For the application/x-www-form-urlencoded content type you should build a query string:
var req = {
method: 'POST',
url: apiPoint.url + 'up.php',
data: 'alldatas=' + encodeURIComponent(JSON.stringify($scope.alldata)),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
params: { section : 'A' }
};
The $_POST superglobal is filled only for application/x-www-form-urlencoded and multipart/form-data content types. The other content types are available via the php://input stream:
if (!empty($_POST)) {
$obj = $_POST;
} else {
$json = file_get_contents('php://input');
$obj = json_decode($json);
}
if ($obj) {
header('Content-Type: application/json');
echo json_encode($obj);
}
exit();
I have an javascript array which is json encoded and posted to PHP.
when I check a value in the array before posting
ie console.log(selection[878][2824]) I'm getting a value as its result. and then the variable is json encoded using JSON.stringify and posted to server. But when I json_decode the value in php and printed the same, I'm getting null array
js script
console.log(selection);
$http({
method: 'POST',
url: 'example.php',
data: 'selection='+JSON.stringify(selection),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
php script
$selectionData = json_decode($_POST['selection']);
print_r($selectionData[878][2824]);
So what is happening while encoding the data here. How is it lost ?
Seems data is not correctly formatted i think you must format the string in
"selection :" +JSON.stringify(selection);
try this
js
$http({
method: 'POST',
url: 'example.php',
data: {selection : JSON.stringify(selection)}
})
php
$data = json_decode(file_get_contents("php://input"),true);
$selection = json_decode($data['selection'],true);
You do not have to stringify your content when you are using POST, just set the right headers.
$http({
method: 'POST',
url: 'example.php',
data: selection,
headers: {'Content-Type': 'application/json'}
})
or if you need it with an identifier:
$http({
method: 'POST',
url: 'example.php',
data: {"selection": selection },
headers: {'Content-Type': 'application/json'}
})
and in PHP (if you are using the additional identifier):
$selectionData = $_POST['selection'];
I'm using jquery to make ajax calls. Basically I don't know how to access the data I'm sending to the server with a post request. I don't know what the variable is called or... something. I don't know!
Ajax functions:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = JSON.stringify({
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
});
return ajax_client(base_url+'ajax_port/gather_records', json);
}
Codeigniter Function:
public function gather_records()
{
$data = json_decode($this->input->post('ids'));
log_message('debug', $data);//null
return json_encode($data);//null :(
}
I'm having no trouble receiving data back from the server here (and accessing with jQuery), my problem is that I can't get the data I'm sending to codeigniter. I'm developing on MAMP if that makes any difference.
I've tried other variable names like,
$this->input->post('data');
$this->input->post('json');
None seem to work.
Thanks very much for any help I can get!
You don't need to do JSON.stringify({..
just pass an object, and everything will be fine. I mean:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = {
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
};
return ajax_client(base_url+'ajax_port/gather_records', json);
}
One more thing. You don't need to json_decode it in your PHP side. Because default contentType in jQuery is 'application/x-www-form-urlencoded; charset=UTF-8'
Change line
$data = json_decode($this->input->post('ids'));
to
$data = $this->input->post('ids');
But if you really want to send JSON, you can add contentType
return $.ajax({
url: url,
type: 'POST',
data: json,
contentType: 'application/json',
dataType: 'json'
});
dataType you have set is "The type of data that you're expecting back from the server." (http://api.jquery.com/jquery.ajax/)
I've written an application in angular for file download, the application is working fine only for small json string, but comes to large string the download fails. Can anyone please tell me some solution for this.
I'm using REST webservice
var json = _.getJson(); // here json value object be received from a script function
var myURL = 'rest/myMethod?jsonValue=' + JSON.stringify(json);
_.downloadFile(myURL);
The downloadFile method :
downloadFile: function(URL)
{
$.fileDownload(URL).done(function(e, response)
{
console.log('download success');
}).fail(function(e, response)
{
console.log('fail');
});
}
As per the comments, here's how to POST using Angular. I can only give you an example here. Header might depend on the angular version etc etc.
function TestController($scope, $http) {
$http({
url: 'yourwebsite',
method: "POST",
data: json, //this is your json data string
headers: {
'Content-type': 'application/json'
}
}).success(function (data, status, headers, config) {
//upload succesfull. maybe update scope with a message?
}).error(function (data, status, headers, config) {
//upload failed
});
}
I see two potential problems:
The request URL might be too long (see: this discussion)
The stringified JSON contains characters not valid in a URL
If the URL is too long, you'd have to move the jsonValue into the body of your request rather than passing it as a URL parameter.
To address the second problem, you need to URI encode the stringified value:
var myURL = 'rest/myMethod?jsonValue=' + encodeURIComponent( JSON.stringify(json) );
BTW, looking at tha fail parameters should indicate why the request failed in the first place.
Here is an example for using $http of Angular for sending a post request and download a XML file from the server.
$http({
url: '$your_URL_here$', // you should replace $your_URL_here$ by your own url
method: 'POST',
responseType: 'arraybuffer',
data: postJson, //***this is the request json data for post***
headers: {
'Content-type': 'application/json',
'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
}).success(function(data){
var blob = new Blob([data], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
saveAs(blob, $fileName$);// you should replace $fileName$ by your own fileName
}
}).error(function(data){
//Some error handling method here
});
Please note that you should import the FileSaver.js to save the file from 'arraybuffer' responseType.
I am using the following jquery ajax call:
$(document).ready(function () {
submitAct();
function submitAct(){
var alldata = [];
alldata.push( {
"pid": 'd2a7d886-6821-3eaa-079f-fbe278c6a16a',
"title": 'Fun with Gophers',
});
$.ajax({
dataType: "jsonp",
type: 'POST',
url: '//[server path]/act',
data: "data=" + JSON.stringify(alldata),
});
}
});
On the server, the result of $_POST[data] is showing as:
[{"pid":"d2a7d886-6821-3eaa-079f-fbe278c6a16a","title":"Fun with Gophers"}]
I am having trouble accessing the keys and related values of 'pid' and 'title'. Would someone please provide some insight? I've tried things like below but haven't had any success:
$_POST['title']
$data = json_decode( $_POST['data']);
$data->title
Thanks!
Several suggestions:
First you are enclosing the data object in an array, needlessly. To access it now:
$data = json_decode( $_POST['data']);
$data=$data[0];/* access object in array*/
$data->title;
The default content type for $.ajax is application/x-www-form-urlencoded; charset=UTF-8...exactly the same as sending a regular form. Think of each key in your data object as you would name of a form control.
There is no need to JSON.stringify to send. jQuery will serialize objects and arrays for you
You can simply send it like this:
var alldata = {
"pid": 'd2a7d886-6821-3eaa-079f-fbe278c6a16a',
"title": 'Fun with Gophers',
};
$.ajax({
dataType: "jsonp",
type: 'POST',
url: '//[server path]/act',
data: alldata
});
Then in php:
$title=$_POST['title'];
$a = json_decode($_POST['data']);
print_r($a[0]->pid);
Change the data part of the ajax request to the following:
$.ajax({
dataType: "jsonp",
type: 'POST',
url: '//[server path]/act',
data: {"data": JSON.stringify(alldata)},
});
Now you can access the sent content via $_POST["data"] in the appropriate php file.
Example:
$json = json_decode($_POST["data"]);
var_dump($json[0]->{"title"}); // [0] because of the array