send jquery object with jquery post - php

i want to send a jquery object to a php function using post my object comes in then i stringify it and get the following output
[
{
"id": "701",
"user_id": "2",
"playlist": "ukg%20garage",
"tracks": "5",
"thumbnail": "Coldplay.jpeg",
"createdon": "2012-08-23 16:06:46"
}
]
so i then pass this thru with post as below
var sendData = JSON.stringify(data, null, 2);
console.log(sendData);
$.post('<?php echo base_url(); ?>account_media/updateplaylistpicture', sendData, function(response) {
console.log(response);
});
and with my php i am doing a print_r($_POST) but its returning nothing
Array
(
)
Where am i going wrong thanks
UPDATE I MANAGED TO SUSS IT WITH THE BELOW
var sendData = JSON.stringify(data, null, 2);
var sendData = sendData.replace(/[\[\]']+/g,'');
$.post('<?php echo base_url(); ?>account_media/updateplaylistpicture', jQuery.parseJSON(sendData), function(response) {
console.log(response);
});

That is very likely because the POST does not contain any "key".
Try this:
print_r(file_get_contents('php://input'));
Another way would be to:
$.post('<?php echo base_url(); ?>account_media/updateplaylistpicture', 'my_stuff=' + sendData, function(response) {
console.log(response);
});

Related

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 - POST an array of objects(JSON data) to a PHP page

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

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

Unable to parse knockout JSON in PHP $_get

Here is my JavaScript code
var student = student || {};
student.viewModel = function () {
var self = this;
self.courseCode = ko.observable("");
self.courses = ko.observableArray([
{ "code": "MTH101", "title": "General Mathematics I" },
{ "code": "CHM101", "title": "Introductory Chemistry I" },
{ "code": "PHY101", "title": "General Physics I" },
{ "code": "BIO101", "title": "Introduction to Biology" }
]);
self.removeCourse = function () { self.courses.remove(this); };
self.addCourse = function (data) {
self.courses.push({ code: data, title: "A new Course added " + new Date() });
$('#courseModal').modal('hide');
};
self.save = function() {
$.ajax("test.php", {
data: ko.toJSON({ courses: self.courses }),
type: "get", contentType: "application/json",
success: function(result) { alert(result) }
});
};
};
student.VM = new student.viewModel();
$(document).ready(function () {
ko.applyBindings(student.VM);
});
How do I read the data sent in PHP? json_decode() only accepts strings and when I also use htmlspecialchars($_GET["courses"]) I get the error undefined index courses. I just want to tell the user the number of courses that was sent to the server.
If it helps, I am testing on localhost using wamp
I think you're looking for:
data: {courses : ko.toJSON(self.courses)},
Also, a POST request would be better than a GET, if you're sending JSON.

Get matched data by using jQuery from a json array on the same php

I am new to jquery. In my current cakephp page url is:
http://localhost/ultimate/admin/treatments/add
I have a json array: <?php $json = $this->Js->object($matchs);?>the content has: '[{"Type":{"name":"Items 1","price":"15","duration":"10"}},{"Type":{"name":"Items 2","price":"30","duration":"25"}}]'
Now I have a name: Items 1, how can I get the price from json array by using Jquery and update to one input area.
Something like this, but I have no idea:
$(document).ready(function(){
$('#treatment_foo').change(function(){
$.ajax({
url: 'add',
data:
dataType: 'json',
cache: false,
success: function(result) {
$('#fee_foo').val($('#treatment_foo').val());
},
});
});
});
success: function(result) {
$('#fee_foo').val( result[0].Type.price );
},
You can also use getJson jQuery function.
Like
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
(function($)
{
$.getJSON(URL,
{
params1: "value",
params2: "value"
},
function(result)
{
$.each(result.Type, function(i,item)
{
console.log(item.name);
console.log(item.price);
console.log(item.duration);
if ( item.name == 'Item 1' ) return;
});
});
});
</script>
As you can see you can loop through result json and display and compare it as you need,
Cheers...
Feel Free To Ask.

Categories