Ok, so here is my JS/jQuery code, my rate.php file simply has a print_r($_POST) in it. The problem is, the $_POST is accepting rated as the string "Array", rather than the actual array as I have defined it. How do I correct this code so PHP will recognize the JSON input as a proper array, rather than a string?
var rated = {"key" : key , "value" : value};
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: {
"rated" : rated
},
success: function(data) {
alert(data);
}
});
This is the output message I'm getting:
Array
(
[rated] => Array
)
Fatal error: Only variables can be passed by reference in .../ajax/rate.php on line X
EDIT: There are actually more variables that rated, but none of them are arrays (thus there isn't an issue with them), so I cut them out of the code above for brevity sake.
When passing JSON data to your php script through ajax I would recommend string encoding the JSON data and then parsing it on the server side.
var rated = {"key" : key , "value" : value};
var rated_encoded = JSON.stringify(rated);
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: {
"rated" : rated_encoded
},
success: function(data) {
alert(data);
}
});
Then you should be able to access the POST variable in your PHP script using $_POST as with any other scalar value. Once you have the JSON string 'rating_encoded' on the server-side, parse it to an associative array using PHP's json_decode().
if(isset($_POST["rated"])){
$rated_json = $_POST["rated"];
$JSONArray = json_decode($rated_json, true); //returns null if not decoded
//Values can now be accessed like standard PHP array
if($JSONArray !== null){
$key = $JSONArray["key"];
$value = $JSONArray["value"];
}
}
I've found that this method is very effective for transferring javascript object data to the server and vice versa (using PHP's json_encode() to translate PHP arrays into valid javascript objects)
It is a proper array, just not what you expect it to be. What you likely want can be achieved by simply passing rated to the data parameter as is. I.e.
var rated = {"key" : key , "value" : value};
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: rated,
success: function(data) {
alert(data);
}
});
Related
I would like to create a JSON object dynamically. The JSON object will have to be as the follows:
{
$capa:[$fila['test_name'],...etc],
.
.
.etc
};
The key and value will be retrieved through a MySQL query.
This is what i'm doing:
$array_container= array();
while($fila=mysqli_fetch_assoc($sql)){
$format_org=str_replace(" ","_",$fila["organization"]);
$format_eval=str_replace(" ","_",$fila["EvaluationType"]);
$format_test=str_replace(" ","_",$fila["test_name"]);
$CapaEnviar=$format_org.$format_eval;
$array_container[] = array($CapaEnviar => $fila['test_name']);
}
echo json_encode($array_container,true);
Using the previous code, I can retrieve a JSON object with duplicate keys.
This code is an answer for an AJAX request, so once the JSON object has been created correctly, I will send back this JSON object in order to retrieve the key and value, so I will have to retrieve separately the key and value.
From your comment,
...the results of this array is as the follows: [{"TEST1":"valueT1"},{"TEST1":"otherValue"}] and what i'm looking for is to have a json like this: [{"TEST1":['valueT1','otherValue']}] as you can see, i want to avoid duplicates keys.
Solution:
In your while loop, change this line
$array_container[] = array($CapaEnviar => $fila['test_name']);
to
$array_container[$CapaEnviar][] = $fila['test_name'];
Update:
how i can retrieve this key and their values through ajax?
Since you're expecting a json object from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, loop through the json result to get (key, value) pairs
Here's the reference:
jQuery.ajax()
So your AJAX skeleton code should be like this:
$.ajax({
type: 'POST',
url: 'yourpage.php',
dataType: 'json',
cache: 'false',
beforeSend: function(){
},
success: function(data){
$.each(data, function(key, value) {
alert("Key:" + key + ", value: " + value);
});
},
error: function(){
// error
}
});
var insertValue= $.ajax({
url: "handle.php",
type: "POST",
data: text,
dataType: "text"
});
insertGroupData.done(function(msg){
alert(msg);
});
This is the first half, I'm stuck in the 1st line of my backend.php
I think it should be catch the POST value, but what should I catch?
<?php
if(isset($_POST["_____??_____"])){
echo "test";
}
Jquery: if your data should be like
data: {test:text},
Then in PHP you can use to get like below,
if(isset($_POST["test"])){
echo "test";
}
Explanation about data:
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting .
Ref: http://api.jquery.com/jQuery.ajax/
change your code to this
var insertValue= $.ajax({
url: "handle.php",
type: "POST",
data: {text:text},
dataType: "text"
});
in backend page you can check it like
echo $_REQUEST['text];
or
echo $_POST['text];
A lesson in jQuery
$(function () {
var
url = 'your/target/script.php',
data,
fn = function (text) {alert(text);},
// fn will expect text, so set return as text
dataType = 'text';
// this POST data will populate $_POST as $_POST[key] = 'value'
data = {
ajax : 1,
key : 'value',
key2 : 'another value'
};
// shorthand notation is convenient sometimes
$.post(url,data,fn,dataType);
});
Your php now has access to your key value pairs
<?php
// in my example the 3 are set
if (isset($_POST['ajax'])) {
$_POST['key'];
$_POST['key2'];
}
Happy coding
Basically what I'm trying to do is returning the results of a mysql query. I know how to put each row of the query results into its own JSON object, now I'm just struggling with a way so that if there's multiple lines of results to return it to my jquery.
In my jquery I call the $.ajax() function and I don't have any issues with that. My problem lies within the success part, where I want to be able to do something like the following:
$.ajax ({
type: "POST",
url:"select.php",
data: {columns : "*",
table : "tbUsers",
conditions : "" },
success: function(results) {
foreach (results as obj)
{
JSON.parse(obj);
$("#page").html(obj.id + " " + obj.name);
}
}
});
I want to be able to iterate through the result variable like an array of JSON objects. The results variable is a string that consists of All the output of the php file. So let my question rather then be, how can I change it so that the function gets an array or how do I change it into one?
My php file currently returns something like this:
[{"0":1, "1":"name1", "id":1, "name":"name1"} , {"0":2, "1":"name2", "id":2, "name":"name2"}]
From the php you can use
echo json_encode($result); // result may contain multiple rows
In your success callback you can use
success: function(results) {
var htmlStr = '';
$.each(results, function(k, v){
htmlStr += v.id + ' ' + v.name + '<br />';
});
$("#page").html(htmlStr);
}
A Demo to help you understand.
Try something like:
$.ajax ({
type: "POST",
url:"select.php",
data: {columns : "*",
table : "tbUsers",
conditions : "" },
dataType: "json",
success: function(results) {
for( var i in results) {
$("#page").html(results[i].id + " " + results[i].name);
}
}
});
Note the dataType: "json" - This will parse it all into a JSON object(s) for you.
quote from your question
I know how to put each row of the query results into its own JSON
object
you need to send one big json string instead of multiple smaller ones. You'll not able to loop through the response because it is not a single json string (it are multiple json strings).
also it is better to chain the ajax callbacks because using them as options will be removed from jquery in the future.
$.ajax({
url: ' your/url ',
type: 'POST',
dataType: 'json',
data: {param1: 'value1'},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
http://api.jquery.com/jQuery.ajax/
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare
your code for their eventual removal, use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
You can just return one big JSON result. Because each of your JSON objects can be wrapped in another.
The JSON you return would then be an array of objects (whatever they may be)
{ "objects": [(first object), (second object), ... ] }
Then in your success function, you can iterate over each object and update the page:
var obj = JSON.parse(results);
jQuery.each(objs, function(i, obj) {
$("#page").html(obj.id + " " + obj.name);
});
return Because wrapped success Then in your success function,you can iterate over each object and update the page You can just return one big JSON result.Because each of your JSON objects can be wrapped in another. The JSON you return would then be an array of objects (whatever they may be)
I am new to JQuery and the whole JQuery to PHP back to JQuery process.
So i have a simple ajax JQuery script:
$.ajax({
type: "POST",
url: "includes/calc.php",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
This goes to a PHP script and then I return a value, using a simple echo
echo $newprice;
The success function above uses this as 'data'. This all works and is fine.
But what if I want to return more than one value.
I think I can used json_encode();
As I understand it something like:
$dataset = array($var1, var2, var3);
echo json_encode($dataset);
But say I have two values, how do i put them both into the JSON and then how do I split them on the other end.
So say 'data' is an array, how do I tell JQuery to split it?
Sorry if this is simple
If you specify the dataType option for .ajax() as json, jQuery will automatically parse the JSON string returned by the call into an appropriate javascript object/array.
So your call might look like this:
$.ajax({
type: "POST",
url: "includes/calc.php",
dataType: "json",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
Now, let's say the response from your PHP script is a JSON string representing an object like this:
{"key1":"value1","key2":"value2"}
In your success handler you can simply access this as an object like this:
success: function(data){
alert(data.key1);
alert(data.key2);
}
Or, if the returned JSON string represents an array like this:
["value1","value2"]
Then you can access the array values in the success handler like this:
success: function(data){
alert(data[0]);
alert(data[1]);
}
If you do not want to add the dataType option, you can also opt to manually parse the returned JSON string into an object/array like this:
success: function(data){
var dataObj = JSON.parse(data);
alert(dataObj.key1);
alert(dataObj.key2);
}
$.ajax({
type: "POST",
url: "includes/calc.php",
datatype : 'json',
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data.firstvalue);
alert(data.secondvalue);
}
})
please look at that datatype. now the respose need to be json.
In your php user json_encode instead of echo.
$firstvalue = 'your first value';
$secondvalue = 'your second value';
echo json_encode(array('firstvalue' => $firstvalue,'secondvalue' => $secondvalue));
There are many ways to organize data in a JSON object. The simplest is to return a linear array of strings or numbers. Use http://jsonlint.com/ to test your data to see if it's valid JSON, or just feed a PHP array (linear or associative) into json_encode.
If data is a JSON linear array, you can treat it like any other JavaScript array in your success callback:
var first = data[0]; // first element
var second = data[1]; // second element
implode your php variables with a symbol or any custom data
like
$var[0] = '1st variable';
$var[1] = '2nd variable';
$var[2] = '3rd variable';
echo implode('_SPLIT_',$var);
Now in jquery success function
split the response with 'SPLIT'
as
var response = data.responseText.split('_SPLIT_');
var variable1 = response[0];
var variable2 = response[1];
var variable3 = response[2];
and assign as your wish
I want to post an array using Jquery Ajax to php. Is this possible ?
Thanks
EDIT:
I tried following :
type: "POST",
url: "path",
data: "styles=" + strstyles + "&templateId=" + custTempId, //strstyles is an associative array
dataType: "json",
success: function (data) { .....}
but, styles hold no data. I spent a lot of time, before adding data type to the declaration. What can be the reason for "styles" being posted as null ?
Second Edit
I want to post style sheet dom object and save the class names and properties to DB. With the above edit, adding datatype did not help. I think it is b'coz the string is not in json format as follows -
{"a":1,"b":2,"c":3,"d":4,"e":5}
As the my string has double quotes, it is not following the format, and I think that's the reason, I'm getting an empty array. How can I handle this ?
With jQuery it is very easy:
$.ajax({
type: "POST",
url: location.href,
data: data,//data is array
dataType: "json",
success : function () {
// Something after success
}
});
You can use in following way too
$.ajax({
type: "POST",
url: location.href,
data: ({'data[]' : array}),//array is array
dataType: "json",
success : function () {
// Something after success
}
});
if you don't want to use JSON, PHP can automatically create arrays from Html forms
so you could do something like this:
type: "POST",
url: "path",
data: "styles[key1]=" + strstyles.val1 + "&styles[key2]=" + strstyles.val2 + ... + "&templateId=" + custTempId
...
that is if you want to have an associative array in php, but if you want just an array you could do
data: "styles[]=" + strstyles.val1 + "&templateId=" + custTempId
In POST call you dont use & , So your code should be
something like
type: "POST",
url: "path",
data: {styles: strstyles , templateId: custTempId}, //strstyles is an associative array
dataType: "json",
success: function (data) { .....}
is that point clear?
So coming to my solution,
you should download JSON parser from http://www.mediafire.com/?x6k3su7bbdrcta8.
Create object strstylesOBJ, code: var strstylesOBJ = {};
insert your strstyles array into strstylesOBJ and stringify it then pass to it in your post call
strstylesOBJ.styles = strstyles;
strstyles = JSON.stringify(strstylesOBJ);
In PHP code you refecth your array using $strstyles = json_decode($_POST['styles']);
do var_dump($strstyles) and please tell what was the output.
regards
Ayaz Alavi