How to use jQuery variable in PHP - 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;
});

Related

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 a image size variable using Javascript to a PHP page

I am trying to send a canvas drawing to the server using javscript.
Having a function such as :
function uploadPic() {
var imgData = document.getElementById("myCanvas").toDataURL();
window.location = "myPHPfile.php?imageData=" + imgData;
}
What would the best way to pass the imgData variable to the php page due to its large size.
Thanks in advance!
User post request to pass large data. You can use jQuery post method
$.post('myPHPfile.php', { imageData: imgData }, function(data) {
// completed
});
Or create and post form:
function uploadPic() {
var imgData = document.getElementById("myCanvas").toDataURL();
var form = document.createElement('form');
form.method = "POST";
form.action = "myPHPfile.php";
var hidden = document.createElement('input');
hidden.type = 'hidden';
hidden.name = 'imageData';
hidden.value = imgData;
form.appendChild(hidden);
document.body.appendChild(form);
form.submit();
}

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

Javascript + Load AJAX function on page load + Pass Javascript vars to PHP

I have again a little problem with a javascript (i am a real noob regardin that). This time I would like to load an AJAX function on page load in order to save some javascript variables to php sessions. I figured out thats the best way to pass javascript vars to php. If there is a better way (besides cookies), dont hesitate to let me know :)
For now I would like to:
-pass javascript variables to an external php page on page load
-save variables in php
-use the php variables without pagereload
Here is my script so far:
$(document).ready(function () {
function save_visitor_details() {
$(function() {
var visitor_country = geoip_country_name();
var visitor_region = geoip_region_name();
var visitor_lat = geoip_latitude();
var visitor_lon = geoip_longitude();
var visitor_city = geoip_city();
var visitor_zip = geoip_postal_code();
var dataString = 'visitor_country='+ visitor_country +'&visitor_region='+ visitor_region +'&visitor_lat='+ visitor_lat +'&visitor_lon='+ visitor_lon +'&visitor_city='+ visitor_city +'&visitor_zip='+ visitor_zip;
$.ajax({
type: "POST",
url: "inc/visitor_details.php",
data: dataString,
success: function(res) {
alert ("saved");
//$('#result').html(res);<-- should contain variables from inc/visitor_details.php
});
}
});
return false;
}
});
Thanks in advance!
Edit: I changed it a little and got it to work by adding the javascript variables into a hidden form, submit the form with the ajax script above and save variables into php session array at the backend php file.Thanks any1 for your time!!!
I don't really understand what is the question here. But here are a few advices.
rather than serializing the data yourself, you should rather let jQuery do that for you:
$.post('inc/visitor_details.php', {country: geoip_country_name() /* stuff */}, function(data) {
alert('ok!'); alert(data);
});
be aware that, by passing data to your server using Javascript, users can send whatever data they want, including fake data. So handle it with care.
Then entire process may looks like this:
/* javascript */
$(document).ready(function() {
function save_visitor_details() {
$.post('inc/visitor_details.php', {
country: geoip_country_name(),
region: geoip_region_name(),
lat: geoip_latitude(),
lon: geoip_longitude(),
city: geoip_city(),
zip: geoip_postal_code()
}, function(data) {
/* do whatever you want here */
alert(data);
}, 'json');
}
save_visitor_details();
});
/* PHP */
<?php
$keys = array('country', 'region', 'lat', 'lon', 'city', 'zip');
$output = array();
foreach($keys as $key) {
do_some_stuff($_POST[$key]);
$output[$key] = $_POST[$key];
}
header('Content-type: text/plain; charset=utf-8');
echo json_encode($output);
?>
JavaScript:
var http = createRequestObject() ;
function createRequestObject(){
var obj;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
obj = new ActiveXObject("Microsoft.XMLHTTP");
}else{
obj = new XMLHttpRequest();
}
return obj;
}
function sendReq(str){
http.open('get', str);
http.onreadystatechange = handleResponse;
http.send(null);
}
sendReq("someurl?var=yourvar");
Php:
$var = $_GET['var']; // use some security here.

Jquery get all input values and create an array (with names)

Hay guys, I'm doing some work where i have a large collection of forms. Seems these aren't 'posted' the traditional way (i.e using a submit button). I need a way to collect all the names and values of all form data when clicking a link (document.location is then used for redirects).
I want names to stay intact so that i can used a simple PHP script to work with the data.
any suggestions?
Might I suggest Serialize Form to JSON:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
and then you can do:
var formArray = $("#myform").serializeObject();
$.fn.valuesArr = function()
{
var a = [];
jQuery.each(this, function(i, field){
a.push($.trim(field.value));
});
return a;
}
USE:
var myArr = $('input', $parentJQelem).valuesArr();
You could use something like my submit helper as a base
function submit(form) {
var form = $(form);
$.ajax(
{ data: $.param( form.serializeArray()),
dataType:'script',
type:'post',
url: form.attr("action")});
}
instead of a 'serializeArray()' i would use 'serialize()' and instead of posting it using ajax you could do whatever you want.
Sorry, dont have more time right now, but hopefully this snippet helps you.
cletus's answer is the best one in terms of efficency.
This is however another working solution that does not rely on JSON:
//this is my object I will fill my array with
function myObject(name, value)
{
this.name = name;
this.value = value;
}
var arr = $.map(
$('span'), function (item) {
var $item = $(item); //no need to $(item) 2 times
return new
myObject(
$item.attr("name"), //name field
$item.text() //value field
);
}
);
arr will be an array of myObject, each of them containing a name property and a value property.
Use your selector instead of $('span').
but all this functions dont work witch array names in inputs.
example -
this is correct for submit post form but when serialize i get
form[type[]]:2
this is not correct - i need - form[type][]:2

Categories