GET key value from AJAX response - php

I'm making a cross domain call to a php which returns this:
response=2&count=15&id=84546379&firstname=adsa&emailstatus=
I want to pick out the values of response and id, but not sure how, my code is as follows:
**
xhr.request({
url: "../promo_getstate2.php",
method: "POST",
data: {
email: emailaddress,
country: country,
lang: lang,
source: '1312_XMAS_dly'
}
}, function(response){
getstate = response['response'];
regID = response['id'];
console.log(getstate)
console.log(regID)
})
but it's not geting those values. How do I do this?
The response is:
" response=2&count=15&id=84546379&firstname=adsa&emailstatus="
**

What you can do is create a params object of all parameters in the response as shown below:
function parseResponse(str) {
var arr = str.split("&");
var temp, params = [];
for(var i = 0; i < arr.length; ++i) {
temp = arr[i].split("=");
params[temp[0]] = temp[1];
}
return params;
}
var values = parseResponse("response=2&count=15&id=84546379&firstname=adsa&emailstatus=")
You can then access values as:
values['response']; // 2
values['id']; // 84546379

Code as that:
<Script language="javascript">
var vars=GetRequest("response=2&count=15&id=84546379&firstname=adsa&emailstatus=");
document.write(JSON.stringify(vars));
function GetRequest(v) {
var url = "?"+v;//location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
</script>
Then you can get the values. For example, the json of the result is
{"response":"2","count":"15","id":"84546379","firstname":"adsa","emailstatus":""}

Related

Load() not working to call a PHP template when submitting a form

I'm trying to load a php file into a div on submission of a form. At the moment everything fires bar this line $('#signupform').load('newsletter-signup-call.php');, I've just got a simple echo request in there and it doesn't fire. If I goto that template it works though.
Where am I going wrong? Could I possibly fire two Ajax calls (as that in itself works) but there seems to be issues with load.
<script>
$("#signupForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var email = $("#EmailAddress").val();
$.ajax({
type: "POST",
url: form.attr('action') + '?email=' + email,
data: form.serialize(),
beforeSend: function(){
$(".newsletter-loading").show().css({"display":"inline-block"});
},
success: function(data)
{
console.log(data); //data contain response from your php script
register_signup();
register_prefs();
(function() {
window.sib = {
equeue: [],
client_key: "xxx"
};
/* OPTIONAL: email for identify request*/
window.sib.email_id = email;
window.sendinblue = {};
for (var j = ['track', 'identify', 'trackLink', 'page'], i = 0; i < j.length; i++) {
(function(k) {
window.sendinblue[k] = function() {
var arg = Array.prototype.slice.call(arguments);
(window.sib[k] || function() {
var t = {};
t[k] = arg;
window.sib.equeue.push(t);
})(arg[0], arg[1], arg[2]);
};
})(j[i]);
}
var n = document.createElement("script"),
i = document.getElementsByTagName("script")[0];
n.type = "text/javascript", n.id = "sendinblue-js", n.async = !0, n.src = "https://sibautomation.com/sa.js?key=" + window.sib.client_key, i.parentNode.insertBefore(n, i), window.sendinblue.page();
})();
sendinblue.track('marketing');
$(".newsletter-loading").hide();
form.replaceWith("<br /><p>Thanks for signing up! You'll receive an email with your discount.</p>");
}
});
});
function register_prefs(){
var email = $("#EmailAddress").val();
Cookies.set('Address', email, { expires: 100000 });
$('#signupform').load('newsletter-signup-call.php');
}
function register_signup(){
ga( 'send', 'event', 'Newsletter Sign Up', 'submit' );
}
</script>
Try to console.log the response status to see what's going wrong
function register_prefs(){
//see if this function is triggered
console.log('register_prefs function triggered')
var email = $("#EmailAddress").val();
Cookies.set('Address', email, { expires: 100000 });
$('#signupform').load('newsletter-signup-call.php', function( response, status, xhr ){
console.log('Server response : ', response)//The serve response
console.log('Status Message : ', [xhr.status, xhr.statusText])//See the status of your request, if any error it should be displayed here
});
}
BUT, Why perform another server call with load, when your are already using ajax, you can return the html in the first call in a json object {Mydata: ..., MyHTML: ...} and just use $('#signupform').html(data.MyHTML) on success.
Also, not sure but I'm suspecting a malformed URL, try this instead '/newsletter-signup-call.php' or an absolute path just to be sure.

Display name one by one using JSON and AJAX

How to display name one by one using ajax. It seem that my FOR looping is not working to push name one by one. Is there any step that i miss? Can someone point me to where/what i did wrong.
var names = [];
var profiles = {};
var restURL = "fetch.php";
function refresh() {
$.ajax({
method: 'GET',
url:restURL,
success: function (result, status, xhr) {
for (var k in result) {
var name = result[k].name;
if (!profiles.hasOwnProperty(name)) {
names.push(name);
profiles[name] = result[k];
}
}
}
});
}
var namei = -1;
function nextName() {
namei++;
if (namei > names.length - 1) {
namei = Math.max(1, names.length - 10) - 1;
}
console.log(namei + '/' + names.length);
$('.texts li:first', '.jumbotron #atname').text(profiles[names[namei]].name);
$('.texts li:first', '.jumbotron #atdiv').text(profiles[names[namei]].division);
$('.jumbotron .tlt').textillate('start');
setTimeout(function () {
$('.jumbotron .tlt').textillate('out');
}, 5000);
}
fecth.php
$i=1;
while ( $row = mysql_fetch_assoc($rs) ) {
$response['result'][] = array(
'staffno' => $row['g_idm'],
'name' => $row['g_name'],
'division' => $row['g_div']
);
$i++;
}
echo json_encode($response);

Find and show the route of the closest markers using DirectionsService by Google Map API v3

Thanks for the help in this forum and i almost complete my assignment in searching the shortest route between a starting point and many markers. However, my distance measurment is simply adopting Haversine formula but it is not showing the true routing distance between two points. I am trying to combining the previous developed functions that have already been worked in Google Map to obtain the shortest distance between two point using the DirectionServices. From the following homepage, i found the method to calculate the distance of each route.
http://ratan.com.np/calculate-distance-location-longitude-latitude-google-maps-v3-route/
and I have checked my codes repeatedly but i still don't know why the code failed... it returned a syntax error 'unexpected token <'....
Can anyone help me to take a look on the code... to see any conceptual mistake in my revised program.... Many Many Thanks...
Click a button to call 'Submit2() function
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var origin = null;
var destination = null;
var markersArray = [];
var start_lat = null;
var start_long = null;
var end_lat = null;
var end_long = null;
var station_num = null;
var trig_name = null;
var total_dist;
var closest_dist;
var closest_marker;
var Submit2=function() {
var URL2="Search_nearest_trig_advanced.php"; //Call another PHP to load all markers in JSON format
$.ajax({
url: URL2,
type: "POST",
dataType: "json",
success: function(data){
$.each(data, function(i, item) {
start_lat = item.start_lat; //Return the Lat, Lng of the Starting point from Textbox
start_long = item.start_long;
station_num = item.station_num;
trig_name = item.trig_name;
end_lat = item.end_lat;
end_long = item.end_long;
origin = new google.maps.LatLng(start_lat, start_long); //Origin and Destination parameters are used for Google Direction Services
destination = new google.maps.LatLng(end_lat, end_long);
marker = new google.maps.Marker({
map: map,
position: destination,
icon: trigicon,
title: trig_name
})
markersArray.push(marker);
calcRoute2(); //find the total distance 'total_dist' for each route
if (total_dist > closest_dist) { //Replace the closest_marker by the one with shorter distance
closest_dist = total;
closest_marker.setMap(null);
closest_marker = marker;
}
});
},
error:function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
destination = closest_marker.getPosition();
calcRoute(); //the original method to show the route
};
Call the calcRoute() function to calculate the route distance
function calcRoute2() {
document.getElementById("directions_panel").innerHTML = "";
directionsDisplay = new google.maps.DirectionsRenderer({
'map': map,
'preserveViewport': false, //Google Map will change the zoom extent to match with the Direction route if set false
'draggable': true
});
var request = {
origin: origin,
destination: destination,
waypoints: waypoints,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
optimizeWaypoints: document.getElementById('optimize').checked,
avoidHighways: document.getElementById('highways').checked,
avoidTolls: document.getElementById('tolls').checked
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
computeTotalDistance(response);
}
});
directionsVisible = false;
}
function computeTotalDistance(result) {
var total_dist = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
total_dist += myroute.legs[i].distance.value;
}
total_dist = total_dist / 1000 // the distance output is converted to KiloMeter
}
The 'search_nearest_trig_advanced.php'
<?php
require_once "dbconnect.php";
require_once "hk1980.php";
$coor_x = $_POST['hk80_x'];
$coor_y = $_POST['hk80_y'];
/* Connect to the MySQL database. */
if (!($connection = # mysql_connect($remotehost, $username, $password)))
die("Connection failed");
if (!(mysql_select_db($database, $connection)))
die("Couldn't select testing database");
// Run the query on the connection
$sql_query = "Select station_num, trig_name, X(trig_xy_pos) as X_Coor, Y(trig_xy_pos) as Y_Coor From trig_station";
if (!($sql_result = # mysql_query($sql_query, $connection)))
die("Couldn't run query");
while ($row = # mysql_fetch_array($sql_result, MYSQL_ASSOC))
{
$start_east = floatval($coor_x);
$start_north = floatval($coor_y);
$hk1980_start = array($start_east, $start_north);
$end_east = floatval($row['X_Coor']);
$end_north = floatval($row['Y_Coor']);
$hk1980_end = array($end_east,$end_north);
$wgs84_start = hk1980_to_wgs84($hk1980_start[1],$hk1980_start[0],2);
$wgs84_end = hk1980_to_wgs84($hk1980_end[1],$hk1980_end[0],2);
$row_set[] = array("start_lat" => $wgs84_start[0], "start_long" => $wgs84_start[1], "station_num" => $row['station_num'],"trig_name" => $row['trig_name'],"end_lat" => $wgs84_end[0],"end_long" => $wgs84_end[1]);
}
echo json_encode($row_set);
?>
The DistanceMatrix does not return route turn-by-turn directions. You have to use the DirectionsService for that. So, what you want to do is pass your origin and destinations to the Matrix first and find the shortest route. After you found the shortest route pass that route to the directions service to get the turn-by-turn information.
If you need to cycle through many routes you may have to use a premium service. Google limits the free access to its services to prevent abuse.
Here is a working example of the concept
Relevant code:
function calculateDistances() {
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
origins: [origin], //array of origins
destinations: destinations, //array of destinations
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
//we only have one origin so there should only be one row
var routes = response.rows[0];
//need to find the shortest
var lowest = Number.POSITIVE_INFINITY;
var tmp;
var shortestRouteIdx;
var resultText = "Possible Routes: <br/>";
for (var i = routes.elements.length - 1; i >= 0; i--) {
tmp = routes.elements[i].duration.value;
resultText += "Route " + destinations[i] + ": " + tmp + "<br/>";
if (tmp < lowest) {
lowest = tmp;
shortestRouteIdx = i;
}
}
//log the routes and duration.
$('#results').html(resultText);
//get the shortest route
var shortestRoute = destinations[shortestRouteIdx];
//now we need to map the route.
calculateRoute(origin, shortestRoute)
}
}
//Calculate the route of the shortest distance we found.
function calculateRoute(start, end) {
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
If you are trying to get the driving distance to multiple locations and don't need the route, use the DistanceMatrix

Parse json data into variables and submit to a function on each iteration

I created a php script that generates the json response
this is the example of the output:
[[],{"idgps_unit":"2","lat":"40","lon":"40","name":"ML350","notes":"Andrew","dt":"2012-10-29 19:43:09","serial":"3602152","speed":"44","odometer":"208.49"},{"idgps_unit":"1","lat":"42","lon":"39","name":"unit1","notes":"fake unit 1","dt":"2012-10-18 18:16:37","serial":"12345","speed":"0","odometer":"0.16"}]
This is how I form the response in PHP:
$data[] = array();
foreach ($list->arrayList as $key => $value) {
$unit = new Unit();
$unit = $value;
//create array for json output
$data[] = array('idgps_unit' => $unit->idgps_unit, 'lat' => $unit->lat,
'lon' => $unit->lon, 'name' => $unit->name, 'notes' => $unit->notes,
'dt' => $unit->dt, 'serial' => $unit->serial, 'speed' => $unit->speed,
'odometer' => $unit->odometer);
}
echo json_encode($data);
Now, in JS I did this:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
success : function(data) {
var jsonData = JSON.parse(data);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: START
var C_longitude = 0;
var C_name = 0;
var C_idgps_unit = 0;
var C_serial = 0;
var C_speed= 0;
var C_notes= 0;
var C_dt = 0;
var C_time = 0;
var C_odometer = 0;
initialize(C_longitude,C_name,C_idgps_unit, C_serial,C_speed, C_notes, C_dt, C_time, C_odometer);
///PARSE VALUES AND SUBMIT TO A FUNCTION :: END
}
});
});
}
I need to parse the json reponce into values
Assuming that JSON.parse(data) only gets the associative array in the JSON response, you should be able to get the values in the JSON data like so:
var i = 1;
var C_longitude = jsonData[i]["lon"];
var C_name = jsonData[i]["name"];
Assuming that the first empty array is not removed by JSON.parse(), i = 1 would get the first batch of data and i = 2 would get the second.
The parsed JSON behaves the same way as if it was defined in JavaScript
If you put dataType: "json" in the ajax settings it will return you a json object than you don't need to parse it again. So this would look like:
function getCheckedUnits() {
jQuery(function($) {
$.ajax( {
url : "json.php?action=get",
type : "GET",
dataType: "json"
success : function(data) {
}
});
});
}
However you could also use your own option but than just use the parseJSON function so var jsonData = jQuery.parseJSON(data);

how to save facebook access token after success

when user allow my app i receive this type of success url:
http://localhost/fbapp/app.php#access_token=AAAAALY8OpPABAM67auStdfgdfOdfgdfgdenqEt9QZCGD2a1h3iWFrhmNWqOf8l4a9RQ8tAJCM9y5QbYpsP6sT1g0ZCXDhtZCECZApGb&expires_in=6604
i am trying $_GET['access_token'] to save access token, but it's not working,
i want to know that how to get access token from this url..
From your use of $_GET, I'm assuming you are talking about PHP. Unfortunately, hash tags are never sent to the server. They only live on the client side so you need to use some javascript to then make a call to a PHP script.
Example:
<script type="text/javascript">
var HashSearch = new function () {
var params;
this.set = function (key, value) {
params[key] = value;
this.push();
};
this.remove = function (key, value) {
delete params[key];
this.push();
};
this.get = function (key, value) {
return params[key];
};
this.keyExists = function (key) {
return params.hasOwnProperty(key);
};
this.push= function () {
var hashBuilder = [], key, value;
for(key in params) if (params.hasOwnProperty(key)) {
key = escape(key), value = escape(params[key]); // escape(undefined) == "undefined"
hashBuilder.push(key + ( (value !== "undefined") ? '=' + value : "" ));
}
window.location.hash = hashBuilder.join("&");
};
(this.load = function () {
params = {}
var hashStr = window.location.hash, hashArray, keyVal
hashStr = hashStr.substring(1, hashStr.length);
hashArray = hashStr.split('&');
for(var i = 0; i < hashArray.length; i++) {
keyVal = hashArray[i].split('=');
params[unescape(keyVal[0])] = (typeof keyVal[1] != "undefined") ? unescape(keyVal[1]) : keyVal[1];
}
})();
}
$.ajax({
type: "POST",
url: '/store_access.php',
data: 'access_token='+escape(HashSearch.get('access_token'),
dataType: "html",
success: function(response) {
alert('Access Token Stored');
}
});
</script>
I found the HashSearch function here: Retrieve specific hash tag's value from url
Also, I assumed jquery on the post to your script, but you could use anything to make the call. You could even just add an image to the body with a url that includes the token.
You are using the client-side authentication auth URL instead of the server side URL which is why you are getting an access_token as part of the URL fragment instead of as a GET variable.
Remove response_type=token from your auth URL and then follow the Server Side Authentication.

Categories