Array from javascript to php with Ajax - Mootools - javascript

Actually i'm developing a timetable selector. Well now i'mt trying to send the values to the miscrosoft sql server database.
I'm using mootools, and i'm doing a request as Ajax to pass all values from javascript to php. My problem is that if i send each value individually, it is very slow. So i'm trying to send every values in a javascript object.
var myRequest = new Request.HTML({
url: "index.php?pagina=2087&",
method: "post",
data: 'transfer='+artigos_sessao,
onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
<?php saveData(); ?>
},
}).send();
artigos_sessao is my object with this format {'key':{'id':value,'sessao':value},...}.
And in PHP side i'm doing this
$array= $_POST['transfer'];
echo $array;
But always my $array variable is empty.
What i'm doing wrong?
Thanks.

You can pass a object into the data field of the Request. So my suggestion is to remove parameters from the url and just pass everything as a object in the data:
var myRequest = new Request.HTML({
url: "index.php",
method: "post",
data: {
'pagina': 2087,
'transfer': artigos_sessao
},
onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
<? php saveData(); ?> // this code is not in your question, i supose you have javascript here hopefully :)
},
}).send();

Related

How to pass json object values to php dinamically?

Hi I'm newbie in JSON and Ajax and my question is probably quite stupid but when learning, also the stupid questions are fundamental.
I need to pass two parameters via Ajax (giorno and periodo),
for example
'giorno' = 2017-05-10 and
'periodo' = 2:
$.ajax({
type:'POST',
data: JSON.stringify({
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
}),
contentType: "application/json; charset=utf-8",
dataType : 'json',
url:'http://www.rinnovipatenti.com/index2.php?a=prenotazione'
});
The JSON object passed perfectly and the result in Firebug Console is:
{"giorno":"2017-05-10","periodo":"2"}
If I try to manually copy and paste the object on the php page like this:
<?
$json = '{"giorno":"2017-05-10","periodo":"2"}'; //pasted manually
$json = json_decode($json, TRUE);
$giorno = $json['giorno'];
$periodo = $json['periodo'];
echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>
the two echoes show me the values. OK!
My problem start and stop here. I'm not able to bring the JSON object to be decoded.
I'm quite sure is a stupid solution but I don't know how to do that.
I need to create a function that wrap the Ajax call and then call the function in json_decode??
PS
I also tried to simply get the values with "$_POST['giorno']" etc.. instead of using JSON but without success.
Can someone help me please? Thank you for your patience.
UPDATE 10/05/2017
Hi I've followed your suggestions so I tried one time more to simplify the code like this:
$('input:radio[name=periodo]').change(function() {
var giorno = document.getElementById("dataselezionata").value; // from datepicker
var periodo = $('input:radio[name=periodo]:checked').val(); // from radio button
var post_data = ("giorno="+giorno+"&periodo="+periodo);
$.ajax({
type:'GET',
data: post_data,
url:"http://www.rinnovipatenti.com/prenota/prenotazione.php",
});
if (this.value == '1') {
$('#orario').show();
$('#orari-mattina').show();
$('#orari-pomeriggio').hide();
}
else if (this.value == '2') {
$('#orario').show();
$('#orari-pomeriggio').show();
$('#orari-mattina').hide();
}
using GET method instead of the POST one and in the PHP page prenotazione.php the code now is:
<?
$giorno = $_GET['giorno'];
$periodo = $_GET['periodo'];
echo"$giorno";
echo"$periodo";
?>
In Firebug console the parameters are ok
giorno 2017-05-10
periodo 2
the formatted link is:
http://www.rinnovipatenti.com/prenota/prenotazione.php?giorno=2017-05-10&periodo=2
the html console preview works correctly but the page don't.
I'm in the corner!
Is very strange. I have only one doubt: can I send data by GET/POST method to the same page where the data are collected?
In other word can the page foo.php send data to foo.php like a cycle without refresh?
And the ajax call could be wrapped inside the .change function or must be outside?
$.post( "http://www.rinnovipatenti.com/index2.php?a=prenotazione", {
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
} );
you do not need to stringify your JSON
on PHP side you just use
$giorno = $_POST['giorno'];
$periodo = $_POST['periodo'];
to get the values
you can use the following function. you have it already. it worked fine for me.
$('input:radio[name=periodo]').change(function() {
var giorno = '2017-05-15';
var periodo = '2';
$.post( 'http://www.rinnovipatenti.com/index2.php?a=prenotazione', {
giorno: giorno,
periodo: periodo
});
/*....*/
});
Method 2
You don't have to stringify the JSON object
$.ajax({
type:'POST',
data: {
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
},
contentType: "application/json; charset=utf-8",
dataType : 'json',
url:'http://www.rinnovipatenti.com/index2.php?a=prenotazione'
});
So you php code will be like this
<?
$giorno = $_POST['giorno'];
$periodo = $_POST['periodo'];
echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>
Method 2
If you want to stringify the JSON object then put it in a key
$.ajax({
type:'POST',
data: 'data='+JSON.stringify({
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
}),
contentType: "application/json; charset=utf-8",
dataType : 'json',
url:'http://www.rinnovipatenti.com/index2.php?a=prenotazione'
});
So you php code will be like this
<?
$json = $_POST['data'];
$json = json_decode($json, TRUE);
$giorno = $json['giorno'];
$periodo = $json['periodo'];
echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>
When you send application/json payload to php to access that payload use:
$json = json_decode(file_get_contents('php://input'), TRUE);
As mentioned in other comments and answers if you stay with $.ajax default form encoding and don't json stringify the data then use $_POST

JSON encode is not working properly in ajax function

I built an event to change product name that mix up with ajax and json encode
<div class="new-product-name"></div>
<div class="new-product-num"></div>
Then the script is
$(function(){
$.ajax({
method: "POST",
url: "fetch-product.php",
data: {keyword: 12}
}).done(function(msg){
$(".new-product-name").html(msg);
$.getJSON("fetch-product.php", function(data) {
$(".new-product-name").html(data.a);
$(".new-product-num").html(data.b);
});
});
});
in fetch-product.php
$query = "SELECT * FROM `product_details` WHERE id='". $_POST['keyword']."'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$name=$row["p_name"];
$num=$row["num"];
}
echo json_encode(array("a" => $name, $num));
Here product details is fetching correctly , even in $(".new-product-name").html(msg); it showing '{"a":"Product1", "b":"22"}', it is entering in to $.getJSON("fetch-product.php", function(data) { }
But data.a , data.b showing null.
why is data.a , data.b null ?I am spending too much time . Please help to solve this error .
I see no reason to make 2 calls to the PHP script.
If you add the dataType:json parameter jQuery will expect a JSONString back from the PHP and msg will be automatically converted to a javascript object.
$(function(){
$.ajax({
method: "POST",
dataType: "json", // new param
url: "fetch-product.php",
data: {keyword: 12}
})
.done(function(msg){
if ( msg.status == 1 ) {
$(".new-product-name").html(msg.a);
$(".new-product-num").html(msg.b);
} else {
$(".new-product-name").html(msg.info);
}
});
});
The other issue with your call to $.getJSON("fetch-product.php",..... was that this would issue a GET request, and therefore fill the $_GET array with any parameters. Your PHP code is not looking for parameters passed in the $_GET array!
Your PHP code as it was, was vulnerable to SQL Injection, so I have amended it to use Parameterised & Prepared statements.
You also need to consider the possibility that nothing is found by your query and return something to let the javascript know about that.
$query = "SELECT * FROM `product_details` WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('i', $_POST['keyword']);
$result = $stmt->execute();
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo json_encode(array( 'status'=> 1,
'a'=>$row["p_name"],
'b'=>$row["num"]);
} else {
echo json_encode(array('status'=>0,
'info'=>'No data found');
}
$.ajax({
method: "POST",
url: "fetch-product.php",
data: {keyword: 12}
}).done(function(msg){
$(".new-product-name").html(msg);
makes a POST to fetch-product and writes the value of msg into the product name element. Except that it should probably be msg.a since your code returns an object with the data inside the a property. You also need to set the dataType:json option so that jQuery knows the returned value from the server is an object and not a string.
However, you then make another request to the same URL, but using a GET request and without passing any parameters. Since your PHP tries to read values from POST requests only, this causes your query to return nothing, and thus your output of $name is empty. You then overwrite your product name element with this empty value.
Why you are making this second request to the same resource, but with the wrong settings, is a complete mystery. It is totally unnecessary. This code should do what you need in a single request:
$(function(){
$.ajax({
method: "POST",
url: "fetch-product.php",
data: {keyword: 12},
dataType: "json"
}).done(function(msg){
$(".new-product-name").html(msg.a);
$(".new-product-num").html(msg.b);
});
});
P.S. Your SQL is incredibly vulnerable to SQL Injection attacks. You should switch to using parameterised queries and prepared statements. Otherwise someone could send a malicious value in the "keyword" parameter and steal, destroy or otherwise corrupt your data. See http://bobby-tables.com/ for a humorous but very clear example of this sort of problem. Both the PDO and mysqli libraries for PHP provide easy ways to create prepared statements, and there are hundreds of examples of the syntax available online for you to follow.
As #Sirko already said, you are sending two requests:
$(function(){
$.ajax({ // First request, as planned
method: "POST",
url: "fetch-product.php",
data: {keyword: 12}
}).done(function(msg){
$(".new-product-name").html(msg);
// This will send an additional GET request to fetch-product.php without any parameters
$.getJSON("fetch-product.php", function(data) {
$(".new-product-name").html(data.a);
});
});
});
Remove the second request or replace the first with the second, if GET method is applicable it should work fine. Because the second request returns null the html of everything with the class .new-product-name will be empty ("").
If You want to make two php calls , then try This:
fetch-product.php
<?php
if($_SERVER['REQUEST_METHOD'] == 'GET' ){
$keyword = $_GET['keyword'];
}else{
$keyword = $_POST['keyword'];
}
$query = "SELECT * FROM `product_details` WHERE id='". $keyword."'";
$result = $conn->query($query);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$name=$row["p_name"];
$num=$row["num"];
}
echo json_encode(array("a" => $name, $num));
?>
Then the Script is
$(function(){
var data = {keyword: 12};
$.ajax({
method: "POST",
url: "fetch-product.php",
data: data
}).done(function(msg){
$(".new-product-name").html(msg);
$.getJSON("fetch-product.php",{keyword: 12}).done(function(data1) {
$(".new-product-name").html(data1.a);
});
});
});

Making Key Value pair for the form elements in JavaScript

I have a module where the forms created are dynamic. So the number of inputs can defer always. Also, the array key can also defer.
My current method of posting form is this:
name = form_options[option_1] value = 1
On submitting the form using POST, I get the form as array in $_POST, which looks like this.
form_options(
option_1 => 1
)
But, now I am trying to implement the same thing using AJAX. So, I would need a common module to get all form values.
I found a way to do it.
var objectResult = $('#options_form').serializeArray();
console.log(objectResult);
This gives me a result like this:
0: Object
name: "form_options[option_1]"
value: "1"
How can parse this result to get an array like $_POST array, which I can send as data in AJAX.
P.S: All the form elements have name field as form_options[key]
You should use this for get post data in PHP file.
// You can use like this
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: "POST", // Enter Request type GET/POST
url: 'action.php', // Enter your ajax file URL here,
dataType: 'json', // If you are using dataType JSON then in php file use die( json_encode($resultArray) );
data: objectResult, // Put your object here
beforeSend: function(){
alert('before');
},
error: function(data) {
console.log(data);
},
success: function(response){
console.log(response);
}
});
// In php file get values like this way
$_POST['form_options']
try like this,
In JQuery:
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: 'POST',
url: 'yoururl'',
data: objectResult ,
success:function(data){
alert(data);
}
});
In your php:
<?php echo var_dump($_POST);?>
You can use jquery serialize with ajax directly, there is no need to use serializeArray:
$.ajax({
type:"post",
url:"formHandleSkript.php",
data: $("#options_form").serialize(),
success: function(response){
$(".result").html(response);
}
});
For more information see http://api.jquery.com/serialize/

Passing array with Ajax to PHP script results in empty post

I want to pass an array from a HTML site to a PHP script using AJAX
JS
function selectPictures() {
//selected Pictures is my JS array
var jsonArray = JSON.stringify(selectedPictures);
var request;
request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {
data: jsonArray
},
cache: false
success: function () {
alert('OK');
}
});
}
HTML
href="selectedPictures.php" onclick="selectPictures();"
PHP
if (isset($_POST['data'])) {
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d) {
echo $d;
}
}
Actually I want to send the data to another HTML page and then include the PHP script, but I don't understand why this example does not even work. The $_POST['data'] is not set.
UPDATE
Ok, the Ajax post is actually working, as I see the HTTP request is successful BUT: I cannot access the variable instantly. I need to access the values of the passed array at once to execute another PHP script. When I want to do this, I get an undefined index error. Also at the time when the isset function is executed, it returns false (despite the successful HTTP request).
HTML
click
JS
$(function(){
$('#selectPictures').click(function(){
var jsonArray = JSON.stringify(selectedPictures);
var request = $.ajax({
url: "selectedPictures.php",
type: "POST",
data: {data: jsonArray},
cache: false,
success: function(data){alert(data);}
});
});
});
Use f12 in chrome to see errors, you forgot to add a comma after the "cache: false"

Getting PHP variable to jquery script file by AJAX call

So basically i have two files. 1 is my php file and it creates tables with some variables when it's called, and second file is jquery script file that makes that call. My script file:
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
$('#results').html(data);
}
});
and it works fine by printing my results.
My php file is echoing data that should be printed in my results div.
Question is how to get some PHP data variables and be able to use them in my jquery file without actually echoing them ??
Like i said in my comment to your question, a way to do that is by echoing the variables on a script tag, so you can access in javascript.
<script>
var PHPVariables;
PHPVariables.VariableName1 = '<?=$phpVariableName1?>';
PHPVariables.VariableName2 = '<?=$phpVariableName2?>';
PHPVariables.VariableName3 = '<?=$phpVariableName2?>';
</script>
And you could use those values accessing PHPVariables.VariableName1 on the javascript.
You can do this by echoing all the data you want like so peiceofdata§anotherpeice§onemorepeice§anotherpeice then you can use php's explode function and use § for the "exploding char" this will make an array of all the above data like this somedata[0] = peiceofdata somedata[1] = anotherpeice and so on.
the explode function is used like this
explode('§', $somestringofinfoyouwanttoturnintoanarray);
you can then echo the relevent data like so
echo data[0];
which in this case wiill echo the text peiceofdata.
write this type of code in ajax file
var data =array('name'=>'steve', date=>'18-3-2014');
echo jsonencode(data);
//ajax call in this manner
$.ajax({
type: 'POST',
data: pass data array,
url: ajaxfile url,
success: function(data) {
var data = $.parseJSON(data);
$('#name').html(data.name);
$('#date').html(data.date);
}
});
Use json format, and in this json add your data variables :
PHP :
$arr = array('var1' => $var1, 'var2' => $var2, 'var3' => $var3);
echo json_encode($arr);
Javascript :
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
data = JSON && JSON.parse(data) || $.parseJSON(data);
$('#results1').html(data.var1);
$('#results2').html(data.var2);
}
});

Categories

Resources