Jquery Ajax read post values with php - 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"; }

Related

Remove the desired number from data

I have a question about how can I delete the desired number from the img_ids. As you see in the table below the img_ids like 68,67,66,65,64, . I want to delete for example number 67, how can I do that with PHP. My mind is confused because of the commas :S.
<div class="delete" id="67">Delete Image</div>
Ajax
$("body").on("click", ".delete", function(){
var deleteimgid = $(this).attr("id");
var data = 'img='+deleteimgid;
$.ajax({
type: 'POST',
url: 'delete.php',
data: data,
cache: false,
beforeSend: function(){},
success: function(response){
}
});
});
delete.php
<?php
include_once 'inc.php';
if(isset($_POST['img'])){
$imgid = mysqli_real_escape_string($db, $imgid);
// Then what should be the query ?
// I am confused because of the commas.
}
?>
Even tho you should not store data like that, here a working approach:
$imgList = '12,23,45,56,67,78';
$imgid = 12;
$imgIds = explode(',', $imgList);
$imgIds = array_filter($imgIds, function ($item) use ($imgid) {
return $imgid != $item;
});
$imgList = implode(',', $imgIds);
print $ImgList; // prints 23,45,56,67,78
What it does:
Splitting the list of ids into an array by comma
Use array_filter to map over the array and remove the desired value
Implode the list again by comma
How you actually should/could store your data
As others have pointed out in the comments, you should normalize your database. Read more
You also could use a blob field instead of a text field, since PHP can handle blob data very easy using serialize/unserialize

How to access array in PHP from Ajax call param?

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).

working with ajax and php as front and backend

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

jquery each loop into a multi array, check for duplicates

I think what I want to do is really simple but can't get it to work. I'm looping through a table and getting some values from the existing rows, that part works. Then I'm using AJAX to try and make a multidimensional array without duplicates but something isn't working. What I really want to do is delete the duplicate part, reorder the array and array_push new values. Here's what I have:
AJAX:
function getData(){
$("#table .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
$.ajax({
type: "POST",
async: false,
data: {key: key, s: sel, q: q}
});
});
}
PHP:
if(isset($_POST['key'])){
$title = $_POST['key'];
$s = $_POST['s'];
$q = $_POST['q'];
if(!empty($_SESSION['check'])){
foreach ($_SESSION['check'] as $key=>$value){
if(in_array($title, $value)){
unset ($_SESSION['check'][$title]);
$_SESSION['check'] = array_values($_SESSION['check']);
array_push($_SESSION['check'], array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
}else{
$_SESSION['check'] = array(array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
Is there something wrong with the logic? It seems like it should work. The same foreach loop works when trying to delete a table row. It finds the correct KEY and deletes it. Why doesn't it work here?
Here's the answer I got by hours and hours of searching. I avoided using serialize since...well I don't understand how to use it. In JS I'm looping to find values in the table and making an array like this:
function getData(){
var checkArray = new Array();
$("#shopCart .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
checkArray.push(key);
checkArray.push(sel);
checkArray.push(q);
});
$.ajax({
type: "POST",
data: {ch: checkArray}
});
}
In my PHP is where I found a cool trick. Since I'm controlling the data in the array, I know how many values will be in it. The trick I found is "array_chunk" so for the 3 values I'm doing this:
if(isset($_POST['ch']) && (!empty($_POST['ch']))){
unset($_SESSION['check']);
$_SESSION['check'] = array_chunk($_POST['ch'], 3);
}
So I'm just clearing the session variable and adding the new values. That eliminates all the checking and clearing and all that. I'm sure there are better ways to do this but this method is short and works and that's what I'm looking for. Hope this helps someone!

Get all Form values - working with jquery ajax in PHP

I'm using this jquery to serialize my form and pass it to a PHP script called write.php;
$("form").submit(function(){
var_form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "write.php",
data: var_form_data,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});
Normally, lets say I had a form with the fields Address F_name and S_name, I'd do something like this to get the values into PHP vars;
$Address = $_POST["Address"];
$F_name = $_POST["F_name"];
$S_name = $_POST["S_name"];
I'd then go onto persist these to the DB
However, this particular form is liable to change on a regular basis. Therefore, I'd like to be able to get at all of the data that was passed through the ajax request in the form of a string that I can explode or an array.
I can then loop through the items in the array and persist them to the DB one by one (i think!).
I hope this makes sense, if I have missed anything or you would like me to explain further please let me know.
As always - all help is very much appreciated.
foreach($_POST as $form_key => $form_val){ }
you will not want to query each time inside this loop, however. Instead append each time to a string that you will query with afterwards.
var $results = '';
foreach ($_POST as $key => $value) {
echo $results .= "$key = $value;";
}
// $results holds the posted values
foreach($_POST as $k => $v)
but this is pretty risky as malicious user could manually add post values to the request and do crappy stuff with your code. Make a list of allowed value maybe ;)

Categories