I want to POST 3 parameters to my PHP web service. One of which is an array, so I used JSON.stringify() first and then added it as the parameter. The problem is, PHP isn't receiving the stringify'ed parameter.
My array is created by fetching IDs of each element in an object.
Converting it into a string:
var cid = JSON.stringify(cids);
Output as in the console for cid:
["1","2","3"]
And my $http.post call:
var dataObj = {
wid: wid,
type: type,
cid: cid
};
$http.post("my.php", dataObj);
From what I understand, the array gets converted into a string, which must get POSTed alike other strings, but when I echo back $_POST['cid'], it turns out to be blank; while the wid & type are proper.
From my understanding all post data is converted to JSON anyway. Manually changing your array to JSON and including is just the same as:
$http.post("my.php", {
wid: wid,
type: type,
cid: [1, 2, 3]
}
At the other side of the connection the JSON is converted back to objects(arrays) if possible. PHP doesn't print anything because arrays aren't converted to strings that well. Although you should expect the string 'array'. Try echo'ing $_POST['cid'][0]
EDIT:
As stated in the comments and this post the following code is required to get PHP and AngularJS to play together:
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
Related
I am implementing Backbone.js, and I am just trying to understand how the sync function works.
To keep it very simple, here is the model.
var Item = Backbone.Model.extend({
defaults: {
name: "Goo"
},
url: "commlink.php"
});
and then
Backbone.sync("create", item);
This is my commlink.php
$item=json_decode($_POST);
$name=$item->name;
$results=$mdb2->query("INSERT INTO list VALUES (NULL, '$name')");
I see a new row show up in my DB, however, the field "name" is blank.
I tried both item.save() and the above method...both ended up with the same blank cell but a new entry.
This is the error in chrome in network/content:
<b>Warning</b>: json_decode() expects parameter 1 to be string, array given in ...XXX...
This is in the request payload:
{"name":"Goo"}
$rawJSONString = file_get_contents('php://input');
$item = json_decode($wrapperString);
//$item->name is the data you want
$item = json_decode(file_get_contents('php://input'), true);
print_R($item);
Found this is more helpful
https://coderwall.com/p/vwvy_a
SECURITY NOTE: as pointed out in the comment this is not the way you should ACTUALLY insert the user provided content into your database, this is simply to show you how to get access to the array information as JSON, you should use prepared statements, a framework database adapter, or some other appropriate solution for escaping the user provided content before sticking it into the database.
You're trying to run an array ($_POST) through a function (json_decode) that only accepts a string. The solution in this specific example would be to do this:
$results=$mdb2->query("INSERT INTO list VALUES (NULL, '{$_POST['name']}')");
This would work because you're accessing $_POST as the associative array that it is.
However what I think you actually want to do is first convert the $_POST array to json, then decode it so you can use it the way you wanted to (accessing it as an object, which the json_decode returns):
$item=json_encode($_POST);
$item=json_decode($item);
$name=$item->name;
$results=$mdb2->query("INSERT INTO list VALUES (NULL, '$name')");
For reference:
http://php.net/manual/en/function.json-decode.php
http://php.net/manual/en/function.json-encode.php
I'm trying to return data as an array to my .ajax function on success so I can do do multiple things, but I can't get to work for anything except a single value. Like return $foo. But when I return $array, the page never loads up.
JavaScript's use & utilizing of array is different as compared to PHP's processing. So, either you need to send the data to your AJAX function as a JSON (JavaScript Object Notation), otherwise you need to send the data as a string with a common separator to your AJAX function.
In the latter case, you will need to split up the Response Text in your AJAX function, with that common separator, to make up a JS Array. Then it will be very much easy to use that array instead.
Hope it helps.
You would have to serialize your data into a string. My preference is JSON, so if your PHP version is >= 5.2.0, you'll most likely have access to a json_encode function. This will turn the PHP object into a JSON string. If you don't have access to json_encode, you can use the PECL JSON package.
Looking at the way you reference your ".ajax" function, I am assuming jQuery. So as long as you set the content type to 'json', the JSON response will result in a native JavaScript object. For example,
PHP,
return json_encode(array(1, 2, 3));
JavaScript,
$.ajax({
...
contentType: 'json',
success: function(response) {
for (var i = 0; i < response.length; i++) {
alert(response[i]);
}
});
This code should proceed to alert 1, 2, and then 3.
I haven't verified the code, but the essential parts are all there. A note to have though, a normal indexed array is turned into a JavaScript list while an associative array will be turned into a JavaScript object.
JSON is a good option to send your data array from PHP to Javascript. In PHP side just encode and return your data array as JSON string and in the Javascript side decode that JSON string and use as normal array.
Suppose your data array is like $array, in your PHP code just encode that array using json_encode($array) and return the resulted JSON string.
In your javascript code decode that JSON string using 'eval' function in the success callback function like:
$.ajax({
type: "GET",
url: "test.php",
success: function(data) {
var dataArray = eval('(' + data + ')');
}
});
I think this will help you ...
Siva
I'd like to pass content back and forth from PHP to jQuery and vice versa. I'm not sure if I fully understand the best way to go about this and am hoping for some best advice and clarification.
Below is an example of something I'm trying to do. The PHP lists the files in a directory (whose path is passed to it from jQuery), stores them in an array, then passes them back to jQuery. I'd like to use the values in that array for various purposes but really I just want to understand passing information back and forth between the two, wether it's from an array, or just a plain variable. Merci beaucoup!
The PHP:
$files = array();
$dir = ($_POST['dir']);
$count = 0;
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && strpos($file, '.jpg',1)) {$count++;
$files[$file] = $file;
}
}
closedir($handle);
}
echo json_encode($files);
?>
The jQuery:
$(document).ready(function(){
$('a').click( function(e) {
e.preventDefault();
$.post("php.php", 'path/to/directory/',
function(data) {
alert(data);
}, "json");
});
});
If I read your question correctly, you're not really looking for tips on this specific code, but more for comments about the process of transferring data back and forth between PHP and jQuery. Let's look briefly at JSON itself, and then look at each side of the communication.
JSON
JSON is a simple way of representing collections of data in a string format that is pretty easy for both humans and computers to read. You can get the full description at http://www.json.org/ but it basically boils down to:
data is enclosed by { and } characters
data is in the format string : value, where the string acts as a reference label
string is in the format of ", followed by any unicode char except / or ", followed by another quote
value can be another string, a number, a complete data object, a boolean value, or an array of some set of the above values
an array is of the format [, followed by a comma separated list of values, followed by a ]
PHP
On the php side, you are receiving a page request and using the attached parameters to decide how to process the page. For a JSON app, that means loading the data into an array, and then the json_encode() function does the grunt work for converting that array into JSON format. The rest of the app would work just the same if you manually created the JSON as a string, though obviously this would make for a lot more work in the PHP code for you. Hence the helper function :)
jQuery
On the jQuery side, the call to $.post() issues an AJAX request, to retrieve a page from the server. In this case, you are sending a request to php.php.
The second set of parameters in the $.post() call is a collection of parameters, which should consist of { followed by comma-separated sets of: a label, then a colon, then a value. Once you have specified all parameters, close the collection with a }. Note that though this is similar to a JSON string, it is not JSON. The label does not have quotes around it the way JSON requires. Any string values, however, do need quotes.
The third parameter of the $.post() call is a function that will be automatically applied to the data that is received from the page request. The results of the function are automatically loaded into whatever variable you specify in the function definition, and you are able to use that data within the function, pretty much as you please. In your example, you simply sent the data to an alert box, but you can do much more with it. You could actually parse this as a JSON collection and perform various actions based on the contents of individual components from within the JSON (which, ultimately, means that you are directly acting on individual values from the original php array).
The fourth parameter on the $.post() call is the data-type. It isn't required, however using it is required if you want to access the json collection as more than just a string. With it, you can specify that the type of data you are returning is json, by simply including "json". If you have done this, you can access the elements of the JSON collection directly within the third parameter function, by referencing their label.
Here's an example of a complete JSON $.post() call:
$.post("test.php", { "func": "getNameAndTime" },
function(data){
alert(data.name); //pretend it's John
console.log(data.time); //pretend it's 10:05am
}, "json");
So here, an ajax request is sent to test.php with the parameter func="getNameAndTime" which the php uses to determine that it should return a json-encoded collection of the form {"name":"John", "time":"10:05am"}, and then the response reaches the function specified to first alert() with the value "John" and then log "10:05am". Again, the only reason that data.name and data.time works in this function is because we specified that json was the return type in the fourth parameter.
The code is correct except for this line in the jQuery:
$.post("php.php", {dir: 'path/to/directory/'},
By the way, it looks like your request is idempotent, so consider using GET instead of POST.
I have a $.get() call to a PHP page that takes 4 GET parameters. For some reason, despite giving the $.get() call all 4, it only passes the first two. When I look at the dev console in chrome, it shows the URL that gets called, and it only passes action and dbname. Heres the code:
$.get('util/util.php', { action: 'start', dbname: db, url: starturl, crawldepth: depth }, function(data) {
if (data == 'true') {
status = 1;
$('#0').append(starturl + "<ul></ul>");
$('#gobutton').hide();
$('#loading').show("slow");
while(status == 1) {
setTimeout("update()",10000);
}
} else {
show_error("Form data incomplete!");
}
});
and heres the URL that I see in the developer console:
http://localhost/pci/util/util.php?action=start&dbname=1hkxorr9ve1kuap2.db
** EDIT **
I have been informed that I need to encode the URL that I am trying to pass through the header. How would I go about encoding it in javascript, and decoding it in php?
Are you sure that the starturl and depth variables are defined? A simple alert() before the $.get() will be enough to check.
In regards to your edit, you can encode strings in JavaScript with the encodeURIComponent function. And decode it back again in the PHP with urldecode. They both take one string argument.
Probably you will need to check whether your input strings are properly quoted. Internally jQuery will build the paramter string out of the parameter map you specified using its param() method. This method will construct an object of the keys and values, which will likely not be parseable if you quoted your keys and values incorrectly.
# Felix Kling: jQuery automatically encodes keys and values of the parameter string with encodeURIComponent.
I'm trying to pass a JavaScript object to a PHP script through jquery.ajax(), basically:
var bigArray = new Object();
//Dode
//Start loop
bigArray[x] = {name: exname, id: exID, order:e, set: setBox, inc: incBox, example: exampleBox, day: i};
So it's pretty much an array of these objects.
var anotherTest = $.toJSON(bigArray);
var ajxFile = "routineajax.php";
$.ajax({
type: 'POST',
processData: false,
url: ajxFile,
data: anotherTest,
success: function(data) {
$('#result').html(data);
alert('Load was performed.');
}
});
});
The PHP side script
print_r($_POST);
$params = json_decode($_POST);
print_r($params)
The Ajax call is going through, and I can see in Firebug, but print_r($_POST) is returning an empty array. While if I change it to $_GET in both the $.ajax function and PHP script it works. My main problem is I'm getting this error message:
Warning: json_decode() expects parameter 1 to be string, array given in
How do I fix this problem?
After adding this snippet to the PHP file
$data = file_get_contents('php://input');
var_dump($data);
var_dump(json_decode($data));
I'm getting this output
string'{"0"{"name":"Decline`Abs","id":"54","order":0,"set":"","inc":"","example":"","day":1}}' (length=87)`
object(stdClass)[2]
public '0' =>
object(stdClass)[4]
public 'name' => string 'Decline Abs' (length=11)
public 'id' => string '54' (length=2)
public 'order' => int 0
public 'set' => string '' (length=0)
public 'inc' => string '' (length=0)
public 'example' => string '' (length=0)
public 'day' => int 1
So at least it's going through, I'm not sure how to access it though, a step in the right direction!
I think the problem is that normally POST data is sent encoded as key=value&key2=value2, and you're sending it as JSON. Try accessing the raw post data as follows:
$data = file_get_contents('php://input');
var_dump($data);
var_dump(json_decode($data));
and see if that works. If not, please post in your question what it returns, if anything.
Based on the comment below and additions to the OP.
Did the var_dump of $data copy-paste correctly? The reason I ask is that this: string'{"0"{"name" does not look right to me. That isn't valid JSON or a properly encoded POST string. It might be that some of the characters got encoded when you copied and pasted.
Either way, you're now getting the result you need. The stdClass is just a blank container that it puts the data into, which you can access using the normal object syntax. In this case, you'd have to do $data->{0}->name I think, because of that 0. If you do $data = json_decode($data, true) it will be an associative array, and you can access the POST'ed data as $data[0]['name'].
If you want to keep exploring this, it might be helpful to show the results of doing window.console.dir(data) right before you do the ajax request, and make sure when you var_dump(data), you view the source of the page to copy and paste. window.console.dir(data) will show data's properties in the Firebug window (you are using Firebug, right?). It also works in Chrome's debugger, and maybe others as well. Like I said though, it looks like you're probably getting what you need already, so investigating isn't necessary.
Turn processData to true. I don't believe your JSON is being passed through correctly. Also note that it won't come through as a json, but rather the key value pairs of your JSON will be the contents of $_POST when you get to it.
Also, are the values of your bigArray easily convertable to string? If you're passing in DOM elements or something, you're going to have issues.
Isn't it clear enough? json_decode() expects parameter one to be string, not array. But $_POST and $_GET are always arrays. You can pass a member of this array to json_decode().
To see an array's contents, use this snippet:
echo "<pre>";
print_r($_GET);
echo "</pre>";