I have a problem regarding on how to get the value of the array variable passed by .post in jquery into my php page
this is my jquery code:
minDate = [];
hoursWork = [];
empId = [];
$('.minDate').each(function() {
minDate.push($(this).val());
});
$('.hoursWork').each(function() {
hoursWork.push($(this).val());
});
$('.empId').each(function() {
empId.push($(this).val());
});
$.post('rtInsert.php', { minDate: minDate, hoursWork: hoursWork, empId: empId }, function(data) {
alert(data);
});
How can I get the passed data in my rtInsert.php
i tried
$minDate = $_POST['minDate'];
$empId = $_POST['empId'];
$workHours = $_POST['hoursWork'];
now how will i get the individual value of the array because all the 3 variables is an array
All I know is a single array using foreach() but
what if there are 3 arrays passed
Is there any idea how I can get it or how can I passed into single array.
Thanks in Advance.
You can use the JSON.stringify(data); to turn them into JSON and prase it on the server side as this; $data = json_decode($json);.
Your code will then become this:
var minDate = [];
var hoursWork = [];
var empId = [];
$('.minDate').each(function() {
minDate.push($(this).val());
});
$('.hoursWork').each(function() {
hoursWork.push($(this).val());
});
$('.empId').each(function() {
empId.push($(this).val());
});
$.post('rtInsert.php', { minDate: JSON.stringify(minDate), hoursWork: JSON.stringify(hoursWork), empId: JSON.stringify(empId) }, function(data) {
alert(data);
});
And your server side ccode:
<?php
$mindate = json_decode($_POST['minDate']);
$hourswork = json_decode($_POST['hoursWork']);
$empid = json_decode($_POST['empId']);
foreach($mindate as $k=>$val)
{
$date = $val;
$work =$hourswork[$k];
$id =$empid[$k];
//...
}
?>
Related
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;
});
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`
})
})
})
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
}
);
});
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
}
);
});
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');
});
});
});