I need to get the distance between two points from JavaScript to PHP using Google Maps. Below is my function to get the distance and post no problems. Now, how can I send the arrays (i.e. volunteerDist and tvid) to another php file (i.e. distanceToDb.php) and what should be the code of my distanceToDb.php to get these data? Thanks! Actual codes is highly appreciated.
<?php
function getFDistance(lat, lng, vlat, vlng, vid) {
var eventlocation = new GLatLng(lat, lng);
var volunteerDist = new Array();
var tvid = new Array();
var volunteerlocation;
for(i=0;i<lat.length;i++) {
tvid[i] = vid[i];
volunteerlocation = new GLatLng(vlat[i], vlng[i]);
volunteerDist[i] = (Math.round((eventlocation.distanceFrom(volunteerlocation) / 1000)*10)/10);
}
$.ajax({
type: 'POST',
url: "distanceToDb.php",
data: {tvid: tvid, volunteerDist: volunteerDist},
success: function(data){
alert("Successful");
},
dataType: "json"
});
}
?>
I've passed arrays and objects using JSON in javascript, let's say through a jquery.post call:
$.ajax({
type: 'POST',
url: "distanceToDb.php",
data: {tvid: tvid, volunteerDist: volunteerDist},
success: successfunction,
dataType: "json"
});
Then, in the php file you just do this:
$js_data_arr = json_decode($_POST['data']);
Related
I would search for the solution, but I don't know what exactly do I have to search.
The task is to grab texts with ID's (#ftext_1,..._2,..._3,..._4) in html file and send them to php file. After some manipulation with texts in php file I have to insert them back into their ID's in html file.
Here is the code:
var text_1_Replace = $('#ftext_1').text();
var text_2_Replace = $('#ftext_2').text();
var text_3_Replace = $('#ftext_3').text();
var text_4_Replace = $('#ftext_4').text();
$('#ID').on('click', function(){
var text= {
ftext_1: text_1_Replace,
ftext_2: text_2_Replace,
ftext_3: text_3_Replace,
ftext_4: text_4_Replace
}
var targetFile = 'ajax/file.php';
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text),
contentType: 'application/JSON'
}).done(function(data) {
console.log(data);
});
});
How do I edit .done function to place new texts in their old ID's(#ftext_1,..._2,..._3,..._4)? The variable with texts array is $result.
so the answer is :
}).done(function(data) {
var text = JSON.parse(data);
var text1 = text.ftext_1;
var text2 = text.ftext_2;
var text3 = text.ftext_3;
var text4 = text.ftext_4;
$('#ftext_1').text(text1);
$('#ftext_2').text(text2);
$('#ftext_3').text(text3);
$('#ftext_4').text(text4);
So, the last update for the topic: The real and nice answer is:
.done(function(data) {
var text = JSON.parse(data);
$.each(text, function(i, val){
$("#" + i).text(val);
});
This code is the solution to my question in this topic. Thank you all, who responded!
The best for you would be send named property that looks like this
$.ajax({
method: 'post',
url: targetFile ,
data: {data: text},
dataType: "json",
success: function(response){
$.each(response, function(element){
$("#"+element.name).text(element.text);
});
}
});
Then in your php you could easily iterate data from post
<?php
$data = $_POST['data'];
$response = [
];
foreach($data as $elementName => $text){
// some text management
$response[] = ['name' => $elementName, 'text' => $text];
}
return json_encode($response);
When you change your received values in php you put them in an array so that you
can call it later easily
PHP
$values = array("one"=>5,
"two"=>"something",
"three"=>$something);
echo json_encode($values);
You need to add
dataType:'json'
in Jquery since you're returning json
JQuery
$.ajax({
method: 'post',
url: targetFile ,
data: JSON.stringify(text), # or data: {"value1":value,"value2":value2},
contentType: 'application/JSON',
dataType:'json',
success: function(response){
console.log(response.one); #Will console 5
console.log(response.two); #Will console "something"
console.log(response.three); #Will console whatever $something holds in php
}
});
You can call it however you want it (response) or (mydata)...
And then you just type response.yourdata (that you declared in php)
I'm trying to use a PHP Array to get long and lat values from a database, and put these onto a map using gmaps.js.
So far, I have created the array in PHP, and echoed this onto my page to confirm the correct values are being displayed.
$data = array();
$data['latitude'] = array($lat);
$data['longitude'] = array($lng);
echo json_encode($data);
So $data is the array, with the values I want inside.
I then want to use jQuery to get the data from json encode, put these into the map marker locations and display the markers like so:
$.ajax({
type: "POST",
url: "phppage.php",
dataType: "JSON",
success: function(data) {
$.each(data, function(key, value) {
poi_marker = {
marker: {
lat: data.latitude,
lng: data.longitude,
}
}
}
poi_markers.push(poi_marker);
});
map.addMarkers(poi_markers);
}
});
I get no errors in my console (using firefox and firebug), the map displays but no markers are shown.
I don't think that you're code is actually doing what you think that it is doing. See this fiddle for what is actually happening with your loop.
If you store the array differently on the PHP side, it'll be easier to loop through multiple markers in JS. Also, I don't think gmaps.js needs that extra 'marker' key in the object.
New PHP
$data = array();
$data[] = array(
'latitude' => $lat
,'longitude' => $long
);
echo json_encode($data);
New JS
var poi_markers = []; // make sure you declare this before using it. if you already declare it somewhere else, don't use this line
$.ajax({
type: "POST",
url: "phppage.php",
dataType: "JSON",
success: function(data) {
$.each(data, function(key, value) {
var poi_marker = {
lat: value.latitude,
lng: value.longitude
}
poi_markers.push(poi_marker);
});
map.addMarkers(poi_markers);
}
});
You might be having trouble because you specify dataType: "JSON" but (atleast in the code you posted) you don't change the header on the php side. You may need to add this line to the top of phppage.php
header("Content-Type: application/json", true);
Where I learned everything I know about gmaps.js
I suppose that the data retrieved successfully as needed
$.ajax({
type: "POST",
url: "phppage.php",
dataType: "JSON",
success: function(data) {
$.each(data, function(key, value) {
map.addMarker{
lat: data.latitude,
lng: data.longitude
}
}
}
});
Check This
From a datapicker i send 2 dates to a php.
I'm trying to print a group of value from json to use in a statistic.
$.ajax({
url: 'calctimestat.php',
method: 'POST',
data: {dateone:dateOne,datetwo:dateTwo},
success: function(data)
{
var obj = jQuery.parseJSON(data);
console.log(JSON.stringify(obj));
}
});
Ajax callback returns into log:
[{"dt":"2014-06-04","qt":"0"},{"dt":"2014-06-05","qt":"0"},{"dt":"2014-06-06","qt":"0"},{"dt":"2014-06-07","qt":"0"},{"dt":"2014-06-08","qt":"0"}]
I tried with:
var date = "dt"
console.log(JSON.stringify(obj.date));
var quantity = "qt"
console.log(JSON.stringify(obj.quantity));
But always returns undefined. I need to have something like this:
[0,0,0,0...]
and
[2014-06-04,2014-06-05,2014-06-06,2014-06-07...]
the author of the question clearly does not need an answer, but maybe the direction of its solution will help others.with this return, to get two arrays, as described in the requirement, it is enough to iterate through the values of objects in the array and get their values by key, decomposing them into the corresponding arrays.
/* IF Ajax callback data = [{"dt":"2014-06-04","qt":"0"},{"dt":"2014-06-05","qt":"0"},{"dt":"2014-06-06","qt":"0"},{"dt":"2014-06-07","qt":"0"},{"dt":"2014-06-08","qt":"0"}]
*/
$.ajax({
url: 'calctimestat.php',
method: 'POST',
data: {dateone:dateOne,datetwo:dateTwo},
success: function(data)
{
var obj = jQuery.parseJSON(data);
var result = [];
var result1 = [];
for(var i in obj)
{
result.push(obj[i]['qt']);
result1.push(obj[i]['dt']);
}
console.log(JSON.stringify(result));
console.log(JSON.stringify(result1));
}
});
These are the two arrays which are sent from ajax call to php
var mycol=new Array();
var mycolval=new Array();
var inputs = document.getElementsByTagName("input");
for (var i = 1; i < inputs.length; i++)
{
if($("#"+inputs[i].id).val().length>0)
{
flag=true;
mycol=inputs[i].id;
mycolval=$("#"+inputs[i].id).val();
}
}
And this is the string
var string = $('#search_input').val();
I have tried the following code but it doesn't seem to work.
Please help me come up with solution.
$.ajax({
url: "anding.php",
type: "POST",
dataType: 'json',
data: JSON.stringify(mycol:mycol,mycolval:mycolval,string:string),
success: function(response){}
});
Your code syntax is wrong
data: JSON.stringify(mycol:mycol,mycolval:mycolval,string:string),
should be
data: JSON.stringify({mycol:mycol,mycolval:mycolval,string:string}),
You might want also want to specify the content type since you're sending JSON
contentType: 'application/json',
then you can access you data
$postdata = json_decode(file_get_contents("php://input"), true);
$mycol = $postdata['mycol'];
though I am skeptical you actually want to send json but rather url encoded key value pairs so you can access them via $_POST['mycol'] etc, if so use
data: {mycol:mycol,mycolval:mycolval,string:string},
instead.
Also
$("#"+inputs[i].id).val()
could be simplified into
inputs[i].value
I'm having some difficulties to correctly retrieve Twitter data using jsonp search.json.
When I fetch the data only once, it works perfectly with this piece of code :
function getTweets(){
$.ajax({
url: 'http://search.twitter.com/search.json',
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'tw_callback',
data: 'q=<?php echo urlencode($twitter_search); ?>+-RT&rpp=100'
});
}
function tw_callback(jsonp){
for( key in jsonp['results'] ) {
var tweet = jsonp['results'][key]['text'] ;
var from = jsonp['results'][key]['from_user'];
var avatar = jsonp['results'][key]['profile_image_url'];
tw_container.push([tweet,from,avatar]);
}
}
But when I try then to refresh this data every xx seconds, using setInterval:
setInterval(function () { getTweets(); }, 1000*interval_tourniquet);
It unfortunately doesn't work. I'm having this error:
NOT_FOUND_ERR: DOM Exception 8: An
attempt was made to reference a Node
in a context where it does not exist.
basically, I got this every time I try to call my getTweets() function inside another function... :(
Other solution I tried :
function getTweets(){
$.ajax({
url: 'http://search.twitter.com/search.json',
type: 'GET',
dataType: 'jsonp',
data: 'callback=tw_callback&q=<?php echo urlencode($twitter_search); ?>+-RT&rpp=100'
});
}
This way it works perfectly with my own jsonp api on another server, but Twitter returns me my callback twice:
tw_callback(tw_callback({results...
And the jsonp string is not interpreted..
Any clue on this, any hint?
Thanx a lot!
Try to rewrite your function with the following, more simple, way.
function getTweets(){
$.ajax({
url: 'http://search.twitter.com/search.json?q=<?php echo urlencode($twitter_search); ?>&rpp=100&callback=?',
dataType: 'jsonp',
success: function(){
for( key in jsonp['results'] ) {
var tweet = jsonp['results'][key]['text'] ;
var from = jsonp['results'][key]['from_user'];
var avatar = jsonp['results'][key]['profile_image_url'];
tw_container.push([tweet,from,avatar]);
}
}
});
}