working with ajax and php as front and backend - php

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

Related

Only 1 character instead of the whole word being returned in a PHP array after retrieving from javascript

In Javascript I'm creating an array for a user side list
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).html();
});
alert(dataArr[0]);
This is working as expected and will alert the first item in the list. "Frank" or whatever it may be.
$.ajax({
url: "fiddle.php",
type: "POST",
data: "dataArr="+dataArr,
success: function(response) {
alert(response);}
I send this array over to PHP and the ajax test confirms its retrieved from a var_dump on the other side.
echo ($_POST['dataArr'][1]);
The problem occurs here when trying to output a particular item, in this case the 2nd item which may be "John" it'll instead output the 2nd character in the first item "r". This is appearing in the Ajax test window. I'm looking for the whole word instead.
Is it a syntax error or a problem with how the data is passed?
I think the problem is related to how you are sending your data in the ajax call.
Try this:
JS
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).html();
});
$.ajax({
url: "fiddle.php",
type: "POST",
data: dataArr, //Send just the array
success: function(response) {
alert(response);
}
});
PHP
var_dump($_POST['dataArr']);
It is because your array is getting converted to string form.
do JSON.stringify() at client side and json_decode at server side
like
in the ajax call
data: "dataArr="+JSON.stringify(dataArr),
and in the php code
$dataArr = json_encode($_POST['dataArr']);
var_dump($dataArr);

Splitting a JSON Array with JQuery that has been returned by PHP

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

variable in jquery function is null

I am having a problem with seeing one of my variables on a webpage. Here is what I have so far.
$(document).ready(function() {
$(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = '$("#ID").val()'
$.ajax({
type: "POST",
url: "test_wID.php",
data: "id",
success: function(data) {
$('#rightselection').html(data)
}
});
});
});
});
This is the jquery function I am using to take an ID entered into a form and use that ID with a bash script.
Here is the php.
<?php
//Get the ID from the HTML form and use it with the check chunk script.
$id = $_POST['ID'];
if (is_null($id)){
echo "$id is null";
}
echo "Selected test Game ID: ".$id;
//print shell_exec('/opt/bin/tester $id');
?>
I commented out the script because the variable is returning null, at this point I am just trying to make sure that I get the ID.
For completeness here is the form I'm using.
print "<p><h3>ID: <input type=\"text\" id=\"ID\" /></h3></p>";
#print "<br>";
print "<p><button id=\"CheckID\">Check ID</button></p>";
When i click the button I get the message in my div that the variable is null. So my question is am I missing something in the declaration? How is it that the var id is null?
Thanks for any help provided.
You should consider changing your jQuery code to:
$.ajax({
type: "POST",
url: "test_wID.php",
data: {id: $("#ID").val()},
success: function(data) {
$('#rightselection').html(data)
}
});
You mixed up strings and variable references at two points.
First, the statement var id = '$("#ID").val()' assigns just a string to your if variable and not the return value of the jQuery call. So just remove the ' here.
Second, the data parameter you're giving to the ajax() call again consists just of a string "id" and not the respective value. Here you need to change to {'id': id}.
So after correcting everything, your code should look like this:
$(document).ready(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = $("#ID").val();
$.ajax({
type: "POST",
url: "test_wID.php",
data: {'id': id},
success: function(data) {
$('#rightselection').html(data);
}
});
});
});
Sidenote: Try to put all ;, where they belong. This prevents some errors, which can be hard to track!
EDIT
As pointed out in the comment by #FlorianMargaine you only need one wrapper not two around your code.
Firstly, the two following snippets are equivalent:
$(document).ready(function() {
});
// Is equivalent to:
$(function() {
});
So your code does the same as:
$(document).ready(function() {
$(document).ready(function() {
});
});
Plain useless, right?
Secondly, this line is plain wrong:
var id = '$("#ID").val()';
You're passing a string to the id variable. $('#ID').val() is not evaluated. This is the equivalent of doing this in PHP:
$id = '$_POST["id"]';
Which is just wrong, right?
You want this:
var id = $('#ID').val();
By the way, this variable naming could be improved, the same goes for the HTML ID.
Thirdly, you're doing the same mistake in the data option of $.ajax:
data: 'id'
You're just passing a string to the data option. You want the value of the id variable.
Then, if you absolutely want a string, I don't recommend it. jQuery expects a special kind of string. You better pass an object. Like this:
data: {
id: id
}
Do you see why the variable naming is wrong? You can't differentiate the property from the value. If you had done the following:
var idValue = $('#ID').val();
You could use this:
data: {
id: idValue
}
Which is way more readable.
In your $.ajax call you need to do:
data : { id: id }
If you want to pass parameters in an AJAX call you need to pass a string similar to the GET string you see in urls. So something like: d=123&name=test
Change the line
var id = '$("#ID").val()'
To
var id = 'id=' + $("#ID").val();

POST, AJAX, and PHP : JSON submission

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

serialize function for string values to use in jQuery ajax datastring

how to sanitize user inputs that you gather by jquery .val() so you can write it in a dataString... in the example you see below when user writes
if some text that contains & the rest
of the comment doesn't seem to work
fine because it counts the rest as an
other variable to POST..
is there a sanitaziation or
serialization code? jQuery's
sanitize() function works on forms but
i want something that i can use
directly use on strings...
var id = $("some_id_value_holder_hidden_field").val();
var comment = $("#sometextarea").val();
var dataString = "id=" + id + "&comment=" + comment;
$.ajax({
type: "POST",
url: "write_comment.php",
data: dataString,
dataType: "json",
success: function(res) {
// Success
},
error: function(xhr, textStatus, errorThrown) {
// Error
}
});
Any suggestion will be much appreciated
Regards
Since you're using jquery, you can use the included Form plugin to serialize the array.
serialize() - Creates a url string from form fields (eg, someEle=someVal&anotherEle=anotherVal)
serializeArray() - Returns a key/value array of all the form elements (useful to know)
$.ajax({
url : 'write_comment.php',
type : 'post',
data : $('#form-element').serialize(),
success : function(data)
{
alert('yay!');
}
});
Edit: Edited to remove incorrect escape() part.
there is a built-in encodeUriComponent that does exactly what you're looking for. Besides that, you can provide an object in "data" field, in which case url encoding will be handled by jquery. In your example:
$.ajax({
type: "POST",
url: "write_comment.php",
data: { id: id, comment: comment},
etc...

Categories