Passing a js array to PHP - php

Why can't I access my array through $_POST in PHP? I'm trying to use the jQuery $.post method. Here is the corrected code with your suggestions:
My javascript:
<script type="text/javascript">
var selectedValues;
var serializedValues;
$("td").click(function() {
$(this).toggleClass('selectedBox');
// map text of tds to selectedValues
selectedValues = $.map($("td.selectedBox"), function(obj) {
return $(obj).text();
});
serializedValues = JSON.stringify(selectedValues);
// $.post('/url/to/page', {'someKeyName': variableName}); //exemple
$.post('handler.php',
{'serializedValues' : serializedValues},
function(data) {
//debug
}
);
});
</script>
My php:
<?php
if(isset($_POST['serializedValues'])) {
var_dump($_POST['serializedValues']);
$originalValues = json_decode($_POST['serializedValues'], 1);
print_r($originalValues);
}
?>

You should serialize your array into json string:
serializedValues = JSON.stringify(selectedValues)
And pass it to php. And then decode with json_decode:
$originalValues = json_decode($_POST['serializedValues'], 1);
http://php.net/manual/ru/function.json-decode.php

On a side note; your javascript could be refactored into something a bit more simple
$("td").click(function() {
$(this).toggleClass('selectedBox');
// map text of tds to selectedValues
var selectedValues = $.map($("td.selectedBox"), function(obj) {
return $(obj).text();
});
// $.post('/url/to/page', {'someKeyName': variableName}); //exemple
$.post('handler.php',
{'serializedValues' : JSON.stringify(serializedValues)},
function(data) {
//debug
}
);
});

Related

Passing 2 datas from AJAX to PHP

So I'm trying to pass 2 datas from AJAX to PHP so I can insert it in my database but there seems to be something wrong.
My computation of the score is right but it seems that no value is being passed to my php file, that's why it's not inserting anything to my db.
AJAX:
<script type = "text/javascript" language="javascript">
$(document).ready(function() {
$("#finishgs").click(function(){
var scoregs = 0;
var remarkgs = "F";
var radios = document.getElementsByClassName('grammar');
for (var x=0; x<radios.length; x++){
if (radios[x].checked) {
scoregs++;
}
else
scoregs = scoregs;
}
if (scoregs >= 12){
remarkgs = "P";
}
else{
remarkgs = "F";
}
});
});
$(document).ready(function() {
$("#GTScore").click(function(event) {
$.post(
"dbinsert.php",
{ scoregs:scoregs , remarkgs: remarkgs},
function(data){
$('#inputhere').html(data);
}
);
});
});
PHP:
if( $_REQUEST["scoregs"] || $_REQUEST["remarkgs"]) {
$scoregs = $_REQUEST['scoregs'];
$remarkgs = $_REQUEST['remarkgs'];
}
There is an extra closing bracket );, you should remove. Try this:
$(document).ready(function() {
$("#GTScore").click(function(event) {
event.preventDefault();//to prevent default submit
$.ajax({
type:'POST',
url: "dbinsert.php",
{
scoregs:scoregs ,
remarkgs: remarkgs
},
success: function(data){
$('#inputhere').html(data);
}
});
});
And in php, you need to echo the variable or success/fail message after you insert data into the database:
echo $scoregs;
echo $remarkgs;

How to use jQuery variable in PHP

Im using a MVC in PHP and I have this script created in my form page to validate three text boxes. When these three text boxes contain a value my php code in my controller asks Google Map Api for the closest directions based on the input of these three fields.
In my script I have the variable "direccion" which is what I need to pass to the controller using PHP but im not sure how to accomplish this.
Script Code (View):
jQuery(document).ready(function () {
var direccion="";
var flag = false;
jQuery(".validation").change(function () {
flag = true;
jQuery(".validation").each(function () {
if (jQuery(this).val().trim() == "") {
alert("false");
flag = false;
}
});
if (flag==true) {
var calle = jQuery("#ff_elem295").val();
var municipio = jQuery("#id_municipio option:selected").text();
var provincia = jQuery("#id_provincia option:selected").text();
direccion = calle +","+ municipio +","+ provincia;
direccion = direccion.replace(/\s/g,'+');
//alert(direccion);
}
});
jQuery.ajax({
url: "index.php?option=com_cstudomus&controller=saloninmobiliarios&task=calcularDistancias",
data : direccion,
dataType : 'html'
}).done(function(){
var data = data;
});
});
PHP Code (Controller):
function calcularDistancias(){
$valor = JRequest::getVar('direccion');
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address='. $valor .'&sensor=false';
$data = file_get_contents($url);
$data_array = json_decode($data,true);
$lat = $data_array[results][0][geometry][location][lat];
$lng = $data_array[results][0][geometry][location][lng];
......
}
data property in the object passed to jQuery.ajax is an object.
data : { direccion: direccion }
Then you can access the value of direccion in your controller as a request parameter.
In the if condition put your ajax request like
if(flag == true) {
jQuery.ajax({
url: "index.php?option=com_cstudomus&controller=saloninmobiliarios&task=calcularDistancias",
data : {direction : direccion},
dataType : 'html'
}).done(function(){
var data = data;
});
}
In addition the retrieved data are missing in your code, don't forget to put data in done function :
.done(function(){
var data = data;
});
To
.done(function(data){
var data = data;
});

How to use loop for multiple arrays imported from Database

In server side I give table data from MySql and I send it with json_encode to JQuery:
<?php
include 'DB.php';
$result20 = mysql_query("SELECT * FROM Gallery WHERE Section = 'Chosen' AND ID = 19");
$array20 = mysql_fetch_row($result20);
$result19 = mysql_query("SELECT * FROM Gallery WHERE Section = 'Chosen' AND ID = 19");
$array19 = mysql_fetch_row($result19);
$data = array();
$data['Div20'] = $array20;
$data['Div19'] = $array19;
echo json_encode($data);
?>
json_encode export this arrays: {"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]}
but, in client side I need use a loop for use all arrays in events. When I use for, it's not work with multiple arrays, how to do it?
$(function() {
$.get('data.php' ,function(response)
{
var data = jQuery.parseJSON(response);
var array;
for(array in data)
{
var ImageID = data.array[0];
var ImageSrc = data.array[1];
$('#'+ImageID ).click(function(){
//some codes
})
}
})
})
Try this
$(function() {
$.get('data.php' ,function(response) {
var data = jQuery.parseJSON(response);
$.each( data, function( key, value) {
var ImageID = value[0];
var ImageSrc = value[1];
$("#"+ImageID ).click(function(){
//some codes
})
})
})
It will work if you add # to your imageid like,
$('#'+ImageID ).click(function(){
//some codes
});
I've tried some code for you,
var json={"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]};
for(div in json){
ImageID=json[div][0];
ImageSRC=json[div][1];
$('#'+ImageID)
.attr('src',ImageSRC)
.click(function(){
alert(this.src);
});
}
Demo
Replace .array with [array] in your for loop:
for(array in data)
{
var ImageID = data[array][0];
var ImageSrc = data[array][1];
}
"array" is not an attribute of your json object, it's just an argument of your for ... in loop. So you must use it as a dynamic value. Moreover you missed using a # to target properly the element id.
var data = {"Div20":["Image20","20.jpg"],"Div19":["Image19","19.jpg"]};
for(array in data)
{
var ImageID = "#"+data[array][0];
var ImageSrc = data[array][1];
$(ImageID).on("click",function(){
//some codes
});
};
Avoid using $.each() loop as someone recommended above, jQuery loops are usually slower than native loops.
Try this..
$(function() {
$.get('data.php' ,function(response)
{
var data = jQuery.parseJSON(response);
$.each(data,function(k, v){
var ImageID = v[0];
var ImageSrc = v[1];
$('#'+ImageID ).click(function(){
//some codes`enter code here`
})
})
})

Passing js array to PHP [duplicate]

Why can't I access my array through $_POST in PHP? I'm trying to use the jQuery $.post method. Here is the corrected code with your suggestions:
My javascript:
<script type="text/javascript">
var selectedValues;
var serializedValues;
$("td").click(function() {
$(this).toggleClass('selectedBox');
// map text of tds to selectedValues
selectedValues = $.map($("td.selectedBox"), function(obj) {
return $(obj).text();
});
serializedValues = JSON.stringify(selectedValues);
// $.post('/url/to/page', {'someKeyName': variableName}); //exemple
$.post('handler.php',
{'serializedValues' : serializedValues},
function(data) {
//debug
}
);
});
</script>
My php:
<?php
if(isset($_POST['serializedValues'])) {
var_dump($_POST['serializedValues']);
$originalValues = json_decode($_POST['serializedValues'], 1);
print_r($originalValues);
}
?>
You should serialize your array into json string:
serializedValues = JSON.stringify(selectedValues)
And pass it to php. And then decode with json_decode:
$originalValues = json_decode($_POST['serializedValues'], 1);
http://php.net/manual/ru/function.json-decode.php
On a side note; your javascript could be refactored into something a bit more simple
$("td").click(function() {
$(this).toggleClass('selectedBox');
// map text of tds to selectedValues
var selectedValues = $.map($("td.selectedBox"), function(obj) {
return $(obj).text();
});
// $.post('/url/to/page', {'someKeyName': variableName}); //exemple
$.post('handler.php',
{'serializedValues' : JSON.stringify(serializedValues)},
function(data) {
//debug
}
);
});

how to pass a php array to javascript array using jquery ajax?

I followed other reslted question but still unable to solve this problem. I want to store the values of an array from php into an array of js. I tried myself butr getting indefined value in all the cases i tried
Plese anyone let me know where i am wrong
my Php code
<?php
$var=5;
$myArray = array();
while($var<10){
$myArray[]=$var;
$var++;
}
echo json_encode($myArray);
?>
and the js code
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array(); var i= 0;
jQuery.getJSON("phparray.php", function(data) {
while(i<5){
res[i]=data.i;
i++;
}
});
});
jQuery("#result").html(res[0]);
});
also treid this js
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array();
var i= 0;
jQuery.getJSON("phparray.php", function(data) {
jQuery(data).each(function(key, value) {
res[i]=value;
i++;
});
});
jQuery("#result").html(res[0]);
});
Try below code
<?php
$var=5;
$myArray = array();
while($var<10){
$myArray[]=$var;
$var++;
}
$dataarray=array("myarray"=>$myArray);
echo json_encode($dataarray);
?>
Jquery
jQuery(document).ready(function(){
jQuery("#previous").click(function(){
var res = new Array();
jQuery.getJSON("phparray.php", function(data) {
var i= 0;
while(i<data.myarray.length){
res[i]=data.myarray[i];
i++;
}
jQuery("#result").html(res[0]);
});
});
});
The problem with your code is you are updating the result before the JSON has been loaded. There is also no reason to copy every item in the array in this case just set res = data (although the above example of sending back an associative array or JS object is good practice).
PHP
<?php
for($var=5; $var<10; $var++){
$myArray[]=$var;
}
echo json_encode($myArray);
JavaScript
$(document).ready(function() {
var res;
$("#result").bind('update', function() {
$("#result").html(res[0]);
});
$("#previous").click(function(){
$.getJSON("phparray.php", function(data) {
res = data;
$("#result").trigger('update');
});
});
});

Categories