How to access array in PHP from Ajax call param? - php

I am making an Ajax call:
$.ajax({
url: "create_card.php",
type: "GET",
data: {deck: selection, data: $(input_form).serialize()}
});
Initially, I was just using the array in the call, so I had data: $(input_form).serialize(), and I was using this code to get the data from the input form (card_info is an array of the named data in the input form):
for($x = 0; $x < $array_length; $x++) {
if(isset($_GET[$card_info[$x]])){
$arg = $_GET[$card_info[$x]];
$sql_query .= "\"" . $arg . "\"";
if($x != $array_length - 1) {
$sql_query .= ", ";
} else {
$sql_query .= ")";
}
}
}
But now that I added the extra parameter to the Ajax call, I can't seem to access the data in the same way anymore. I've tried $_GET[data[$card_info[$x]]] but this did not work.

$(input_form).serialize() serializes data from your form to a string, kinda
inputName1=inputValue1&inputName2=inputValue2&inputName3=inputValue3 and etc.
Using
data: {deck: selection, data: $(input_form).serialize()}
means that you send to your server an object with two properties deck and data. On server this object will be converted to $_GET array with two keys: deck and data. And $_GET['data'] will hold a string with your previously serialized values.
If you use print_r($_GET) you will see, what I'm talking about.
So the solution is not to mix ways of sending data. Either you send a string, as #splash58 proposed:
// here you have a string
data: $(input_form).serialize() + '&deck=' + selection
Or an object:
// here you have an object
data: {deck: selection, field1: $("#someId").val(), field2: $("#yaId").val(), /* etc */ }
Where field1, field2 are keys and $("#someId").val(), $("#yaId").val() are methods which are used to get some values (in this case using ids).

Related

How to retrieve an array from an AJAX call?

I make an Ajax call that needs to return (after success:...) a multidimensional array representing an SQL query :
$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
data: {action: this.title},
type: 'post',
success: function(data) {
//I need to use the data array here.
});
Here is the method that is called :
<?php
$bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');
$req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");
$data = ... //Here I need to transform the previous request into a multidimensional array.
//For exemple data[3][2] will contain the value within the third row of the second column
echo $data; //returning the array
}
Thanks
Problem
You are trying to return am array. But as AJAX calls works on HTTP protocol, you can transfer only text, normally. So your ajaxmethod.php will print the array and the rendered page i.e. the text will be returned as it is displayed, not an array.
Solution
Convert the array into a JSON object using json_encode() (PHP) andreturn that. Then decode it on the page that made the ajax call, using JSON.parse() (JavaScript). This will give an array.
Code
$.ajax({ url: 'http://localhost/Project/ajaxmethod.php',
data: {action: this.title},
type: 'post',
success: function(data) {
//I need to use the data array here.
var array = JSON.parse(data); //This is the array you want
});
...
<?php
$bdd = new PDO('mysql:host=localhost;dbname=DATABASE;charset=utf8', 'root', '');
$req = $bdd->query("SELECT column1, column2, column3 FROM TABLE ");
$data = ... //Here I need to transform the previous request into a multidimensional array.
//For exemple data[3][2] will contain the value within the third row of the second column
echo json_encode($data) //returning the array
}
You cant just echo an array (you can't, it an array not a simple value).
Luckily, there is a thing called JSON. In PHP you store all the information you want (in this case, your rows from the DB) in a large array and then you do echo json_encode($array);.
At the Javascript side you change the $.ajax to $.getJSON so that jQuery also understands that we're talking about JSON, et voila, you have a nice javascript version of your PHP array.
// I am not familiar with PDO, but something along these lines:
$allData = $req->fetchAll();
echo json_encode($allData); // Now you output a JSON version of the array
And then javascript
$.getJSON(
'http://localhost/Project/ajaxmethod.php',
{action: this.title},
function(response) {
// And in 'response' you now have a ready to use JS object)
console.log(response);
});
*You can also use $.ajax() if you really want to, just add a dataType: 'json

How do i send a 2d array with ajax?

I am currently trying to send a 2d array that i receive from a database (sql, phpmyadmin) with ajax.
My ajax function looks like this: (it is generated in php)
$.ajax({
type: \"POST\",
url: \"resultQuizGet.php\",
data: \"getAnswer=\"+question+\"\", //question is just a int variable
success: function(msg) {
alert(\"Data Saved: \" + msg);
}
});
my resultQuizGet.php file then look like
$sql = "SELECT `quiz`.question,`quiz`.rightAnswer
FROM `quiz`
WHERE `quiz`.quizID=:qID";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(":qID", $_POST['quiz']);
$stmt->execute();
$resultsQuiz = $stmt->fetchAll();
echo ...
What do i have to do now to receive a 2d array instead of just a normal string.
What i would like to the msg variable to be is a 2d array that is equal to $resultsQuiz
Modify your php as follows, to output the data as a json formatted string:
$sql = "SELECT `quiz`.question,`quiz`.rightAnswer
FROM `quiz`
WHERE `quiz`.quizID=:qID";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(":qID", $_POST['quiz']);
$stmt->execute();
$resultsQuiz = $stmt->fetchAll();
echo json_encode($resultsQuiz);
Then, modify your jQuery as follow to parse that structured string back into an array / object:
$.ajax({
type: "POST",
url: "resultQuizGet.php",
data: "getAnswer="+question, //question is just a int variable
success: function(msg) {
// Note: if it's not json, this can cause a problem
var data = $.parseJSON(msg);
// output to your console so you can see the structure
console.log(data);
// Utilize the data somehow
$.each(data, function(key, arr) {
// Arr should contain an object / array representing the rows from your php results
console.log(arr);
// If your row has a field titled `question`, you can access it one of two ways:
alert(arr.question); // Object notation
alert(arr['question']); // Array notation
});
}
});

explain how this jquery ajax passes data

I have the following class in a php file:
function calcTotal(){
var productID = <?php echo $product_info['products_id'];?>;
var sizeID = 0;
$(".mine_sizes").each(function() {
if ($(this).is(':checked')) sizeID = $(this).val();
});
//alert(sizeID);
var colorID = 0;
$(".mine_color").each(function() {
if ($(this).is(':checked')) colorID = $(this).val();
});
$.ajax({
type: "POST",
url: 'get_product_price.php',
data: "product_id="+ productID +"&color_id="+ colorID +"&size_id="+ sizeID,
success: function( response ) {
$("#price_container").html(response);
;
}
});
}
and the php file get_product_price.php:
if($_POST){
$product_info_query = tep_db_query("select products_price, products_tax_class_id from " . TABLE_PRODUCTS . " where products_id = '" . (int)$_POST['product_id']."'");
$pricePrice = tep_db_fetch_array($product_info_query);
$productPrice = $pricePrice['products_price'];
$sizesPrices = tep_db_query("select options_values_price from products_attributes where products_id='".$_POST['product_id']."' and options_values_id='".$_POST['size_id']."'");
// echo "select options_values_price from products_attributes where products_id='".$_POST['product_id']."' and options_values_id='".$_POST['size_id']."'";
// exit;
if(mysql_num_rows($sizesPrices)>0){
$priceRow = tep_db_fetch_array($sizesPrices);
$productPrice = $productPrice + $priceRow['options_values_price'];
}
$sizesPrices2 = tep_db_query("select price from product_attributes_color_relation where product_id='".$_POST['product_id']."' and color_id='".$_POST['color_id']."' and color_size_option_id='".$_POST['size_id']."'");
if(mysql_num_rows($sizesPrices2)>0){
$priceRow2 = tep_db_fetch_array($sizesPrices2);
$productPrice = $productPrice + $priceRow2['price'];
}
//echo $productPrice; exit;
echo $currencies->display_price($productPrice, tep_get_tax_rate($product_info['products_tax_class_id']));
//echo $productPrice;
}
The function is called on a radio button click and is currently working but I am trying to understand how it works for myself (and to possibly recreate a similar function)
What I am not really understanding is the data parameter from the ajax api. How is that data parameter used?
another question I have is the success parameter. Is the "response" parameter a standard or can in be called anything?
Thanks for any help explaining this to me. I don't think any other information is necessary, there is a div with a class id #price_container which is where the price is echo'd.
The data parameter passes the information the same way an HTML form will. At least that's the easiest way to think of it. So that "data" will come through as $_POST or $_GET arrays. I always setup my data as JSON format:
data: { "product_id": productID,"color_id": colorID, "size_id": sizeID },
With your type set as "POST" that would come through as:
$_POST['product_id']
$_POST['color_id']
$_POST['size_id']
You can specify any variable name for the response - but 'response' is nice and easy to remember and work with. :)
from the ajax documentation
data
[Object, 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 (described below).
Basically if you set the data variable to a query string, it sends it to the server as is, other wise it will generate a query string from the key value pairs that you set. Once the php server receives the query string it is parsed and you can access your values using
$_POST['key']

Jquery Ajax read post values with php

I'm sending the following info to a php file. data contains 'one' and 'two'. 'One' contains the serialized form and two contains similar custom info. How can i read those post values with php. I want to be able to differentiated between the value contained in one and value contains into two.
$('form').submit(function() {
x = $(this).serialize(),
test = 'testing=whatever&something=else';
$.ajax({
type: 'POST',
data: {'one':x, 'two':test}
...
})
})
How can i read the values in php in such a way where i can do
$one = $_POST['one'];
foreach($one as $key=>$value){ $message.= $key.": ".$value."\r\n"; }
I'm not sure what you want to do with the serialised version of the form (x) but you can get access to both of the variables in the receiving PHP script using $_POST as per usual and then probably use parse_str (http://au.php.net/manual/en/function.parse-str.php) to break 'test' out into the various parameters, but I question why you are taking this route instead of breaking the parameters up and passing them as individual arguments in the data argument:
data: {'testing' : whatever, 'something' : else}
you need to cancel the default behavior of submit
$('form').submit(function(e) {
e.preventDefault();
x = $(this).serialize();
test = 'testing=whatever&something=else';
$.ajax({
type: 'POST',
data: {one:x, two:test}
...
})
})
on the php side
$one = $_POST['one'];
$two = $_POST['two'];
update:
im not that well versed in php but i think the following should work
$one = $_POST['one'];
$two = $_POST['two'];
$cols = explode("&", $one);
foreach($cols as $col) {
$key_values = explode("=", $col);
$key = urldecode($key_values[0]);
$values = urldecode(key_values[1]);
}
echo $key, $values;
If your form contains checkboxes or radioboxes (inputs with same names) use $(this).serializeArray() instead of $(this).serialize() to distinguish between them
You need to first convert your form data into JSON! not the query string which serialize does, for that see This, JSON can give you ability to have nested keys.
Then you can put seperate data in different keys in JSON like:
var myData =
{
'one': $('form').serializeObject(),
'two': 'testing=whatever&something=else',
};
$('form').submit(function() {
$.ajax({
type: 'POST',
data: myData,
...
});
});
And the on PHP side you can easily get it using the way you want to:
$one = $_POST['one']
foreach($one as $key=>$value) { $message.= $key.": ".$value."\r\n"; }

build php array using jquery

i have a select box where in it has a list of items and he enters value for each selected option and saves it .
i have written a function like.
$('.add_recordings').click(function () {
if (($('#recordings_name').val() != '') && ($('#recordings_value').val() != '')) {
if ($('#recordings').val() == '') {
var result = $('#recordings_name').val() + '=' + $('#recordings_value').val();
$('#recordings').html(result);
var result1 = $('#recordings_name').val() + '=>' + $('#recordings_value').val();
$('#recordings_array').val(result1);
}
else {
var result = ', ' + $('#recordings_name').val() + '=' + $('#recordings_value').val();
$('#recordings').append(result);
var result1 = ', ' + $('#recordings_name').val() + '=>' + $('#recordings_value').val();
alert(result1);
$('#recordings_array').append(result1);
}
}
});
the append function for recordings_array is not working, its a input of type text.
what i am trying to do is to build an php array using jquery ,so that it can be passed in $_POST.. is there any better method to do this?
the append function for recordings_array is not working, its a
input of type text.
why not set its value instead of appending?
$('#recordings_array').val(result1);
Edit
if you want to append value, it's easy on jQuery 1.4
$('#recordings_array').val(function(i,val){
return val + result1;
// this will get the current value of the input (val),
// add result1, then return the result as the new value of the input
});
below jQuery 1.4
$('#recordings_array').val($('#recordings_array').val() + result1);
If you are not sending any other data and you send it via Ajax, I would do it totally differently:
Create a global records object (functioning as associative array):
var records = {};
and you just add the values to this object when the click occurs:
$('.add_recordings').click(function () {
if (($('#recordings_name').val() != '') && ($('#recordings_value').val() != '')) {
records[$('#recordings_name').val()] = $('#recordings_value').val();
}
});
Then you send it, e.g. with ajax():
$.ajax({
type: "POST",
url: "some.php",
data: records,
success: function(msg){
/...
}
});
records will be transformed to a query string like
recordnameA=recordvalue&recordnameB=recordvalue
and on the PHP site you already have all these values in an array:
$_POST['recordnameA']
Of course it also works if you sent other data via POST in addition, you can remove this data from the array after processing it with unset($_POST['otherdata']).
Note: It is only confusing to build the PHP array string on the client side and you would have to evaluate it, e.g. with eval(). But you cannot ensure that the string you get only contains an array, the user could have manipulated it and you have a potential security hole.

Categories