How to Communicate between PHP and JavaScript - php

I wrote a JavaScript function to convert GeoJson data to WKT format. It works when i get the input value in the javascript code directly. But I don't know how to get the input from the php and send it back.
Here is the php code:
<?php
$geojson=file_get_contents("clipfeature.geojson");
$WKT = $_POST['wkt'];
echo ($WKT);
?>
So it gets geojson data from a file and I want to receive the converted WKT code from the Javascript function.
Please help me finish the JavaScript Code:
function converttoWKT (){
$.ajax({
type: "GET",
url: "readJson.php",
contentType: "application/json"
}).done(function (data) {
var JSONObject = How to give the value from PHP to this Variable;
var coordinate = JSONObject.features[0].geometry.coordinates;
var type= JSONObject.features[0].geometry.type;
var coordinate1 = "";
var coordinate2 = "";
for (var i=0; i< coordinate[0].length; i++) {
coordinate1= coordinate[0][i][0]+" "+coordinate[0][i][1];
coordinate2=coordinate1+","+coordinate2;
}
var WKT= "\""+ type + "((" + coordinate2;
WKT=WKT.substring(0,WKT.length-1);
WKT=WKT+"))\""
sendback ( );
});
function sendback(){$.post("readJson.php",
{'wkt':How to send the value of var WKT back to php 'wkt'
});
}

Basically:
var jsVar= "<? echo $myVariable_value_goes_in_here; ?>";
or, as mentioned above:
var JSONObject = <? echo json_encode($WKT); ?>;
// this NEED TO BE json, otherwise syntax error in JS!

Since you already know your return data will be JSON, you can just use $.getJSON() for convenience. This is a $.get() request paired with JSON.parse(). With $.getJSON(), the JSON is parsed on response. To send the data back, just use use jQuery's $.post().
Here's an edited version of your code.
function converttoWKT() {
$.getJSON('clipfeature.geojson', function(data) {
var coordinate = data.features[0].geometry.coordinates;
var type = data.features[0].geometry.type;
var coordinate1 = '';
var coordinate2 = '';
for(var i = 0; i < coordinate[0].length; i++) {
coordinate1 = coordinate[0][i][0] + ' ' + coordinate[0][i][1];
coordinate2 = coordinate1 + ',' + coordinate2;
}
var WKT = '"' + type + '((' + coordinate2;
WKT = WKT.substring(0, WKT.length - 1);
WKT = WKT + '))"'
sendback(WKT);
});
};
function sendback(data) {
$.post('readJson.php', {
'wkt': data
});
};

Related

Hot to get PHP variables in JSON format and refresh by AJAX

I have a device which export data in XML format.
And I would like to display this data on my webpage + refresh every second by ajax.
So my PHP file is:
<?php
$xml=simplexml_load_file("http://admin:pass#192.168.0.109/st0.xml") or die("Error: Cannot create object");
echo json_encode($xml);
exit();
this will display:
{"out0":"1","out1":"1","out2":"1","out3":"1","out4":"1","out5":"1","out6":"1","di0":"up","di1":"up","di2":"up","di3":"up","ia0":"473","ia1":"166","ia2":"359","ia3":"187","ia4":"4326","ia5":"1832","ia6":"36","ia7":"198","ia8":"6","ia9":"234","ia10":"-600","ia11":"246","ia12":"-600","ia13":"0","ia14":"0","ia15":"65952","ia16":"0","ia17":"854000","ia18":"1000","ia19":"192","freq":"5008","duty":"500","pwm":"0","sec0":"27","sec1":"17","sec2":"20","sec3":"1","sec4":"1481894628"}
So now I know how to display whole data and refresh, but I do not now how to put every data in separete div, ex. to display only interesting part:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
setInterval(function() {
$("#load_results").load("get_xml.php");
}, 1000);
});
</script>
</head>
<body>
<div id = "load_results"></div>
</body>
</html>
You have 2 situations:
Either you know the format of the JSON and you can build a DOM
structure using jQuery (for example) in the exact format you want
with the exact data you have.
For that you will have to access the object properties of the JSON object so for instance:
$("#load_results").load("get_xml.php");
becomes:
$.get( "get_xml.php", function( data ) { // retrieves the JSON from that file using AJAX
var parsedJSON = JSON.parse(data); // we convert the JSON string into a Javascript object
var formattedString = 'Our OUT0 is ' + parsedJSON.out0 + '<br>'; // we access the data in the Javascript object as for all Javascript objects, see http://www.w3schools.com/js/js_objects.asp
formattedString = formattedString + 'Our ia12 is ' + parsedJSON.ia12; // and so on
$('#load_results').html(formattedString);
});
Either you don't know the format or
you don't care at all. In this case the situation is simpler, you
can use a JSON prettifying tool for JavaScript such as the one
implemented here: http://jsfiddle.net/unLSJ/ (by someone else than me, cheers to him).
For the option 2 this would be the library:
// Library
window.jsonPrettifier = {
replacer: function(match, pIndent, pKey, pVal, pEnd) {
var key = '<span class=json-key>';
var val = '<span class=json-value>';
var str = '<span class=json-string>';
var r = pIndent || '';
if (pKey)
r = r + key + pKey.replace(/[": ]/g, '') + '</span>: ';
if (pVal)
r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>';
return r + (pEnd || '');
},
prettyPrint: function(obj) {
var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg;
return JSON.stringify(obj, null, 3)
.replace(/&/g, '&').replace(/\\"/g, '"')
.replace(/</g, '<').replace(/>/g, '>')
.replace(jsonLine, library.json.replacer);
}
};
After you added this library somewhere inside your code, you can replace
$("#load_results").load("get_xml.php");
with
$.get( "get_xml.php", function( data ) { // retrieves the JSON from that file using AJAX
var parsedJSON = JSON.parse(data);
$('#load_results').html(window.jsonPrettifier.prettyPrint(parsedJSON));
});
and you will obtain a pretty printed JSON.

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

parseJSON to JSON rsponse in jquery-ajax not working

I am new to AJAX using jquery. I have a json response as below:
[{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}]
And my ajax file is :
function(result){
$('#resdiv').html(result);
console.log(result);
var json_obj = $.parseJSON(result);//parse JSON
alert(json_obj);
var output="<ul>";
for (var i in json_obj)
{
output+="<li>" + json_obj[i].customer_name + "</li>";
}
output+="</ul>";
$('#resdiv1').html(output);
}
Though I can view the JSON response in div id resdiv, the div id resdiv1 is empty ! Also alert(json_obj); does not alerts anything ! Whats wrong with the file ?
NB: I am learning from Zuch Tutorial
You dont need to parse the json again.Simply do a iteration and try like this
var json = [{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}];
var output="<ul>";
$.each(json,function(key,val){
output+="<li>" + val.customer_name + "</li>";
});
output+="</ul>";
console.log(output);
See DEMO
check this out
// Need to parse if string.
var result = '[{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}]';
var json_obj = $.parseJSON(result);//parse JSON
// No need to parse
var json_obj = [{"customer_name":"Customer A"},{"customer_name":"Customer B"},{"customer_name":"Customer C"}];
Also check this
// if undefined, you don't have resdiv1 div or you have call function before your div render.
alert($('#resdiv1').html());
Can you try this
function(result){
$('#resdiv').html(result);
console.log(result);
var json_obj = $.parseJSON(result);
//parse JSON alert(json_obj);
var output="<ul>";
$.each(json_obj,function(key,val){
output+="<li>" + val.customer_name + "</li>";
console.log(key+":::"+val);
});
output+="</ul>";
$('#resdiv1').html(output);
}

jQuery Json + jQuery onChange

I am using php to talk to a mysql database then encoding the associative array with json_encode. That much I know is working, I can call the php directly and see the json result.
With jQuery I am using onChange on a dropdown to call the php function and to get the results.
I think I have problems with the jQuery and json, but I have looked through multiple posts and cannot find a good answer.
Here is the code I am using. How do I get to the json array? I have tried data['ele'], data.ele, data[0] and all return undefined.
$('#itemDD').change(function(data){
alert("Changing");
askServer(function(data){
alert("!" + data['retailListPrice']);
//spin through the data and put the results in workingQuote
});
});
function askServer(callback)
{
var selItem = $('#itemDD').val();
var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo";
alert(strUrl);
jQuery.ajax({
url:strUrl,
success:callback,
dataType: "json"
});
}
});
PHP
$sql="SELECT *
FROM items
WHERE modelNum='" . $selectedModel . "'";
$result = mysql_query($sql,$conn) or die("Error" . mysql_error());
while(($resultArray[] = mysql_fetch_assoc($result)) || array_pop($resultArray));
echo json_encode($resultArray);
You using array and mysql_fetch_assoc. So to get the data, use data[0]['rowName'] or data[0].rowName
try this (note: object/array format is diffrent in JS):
function askServer()
{
var selItem = $('#itemDD').val();
var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo";
alert(strUrl);
$.get(strUrl, function(data){
alert(data.retailListPrice);
});
}
Inside change event just call the askServer() function and declare it outside of change event, like
$('#itemDD').change(function(data){
//...
askServer();
});
and your askServer() function
function askServer()
{
var selItem = $('#itemDD').val();
var strUrl = "getItemList.php?item=" + selItem + "&action=itemInfo";
$.get(strUrl, function(data){
$.parseJSON(data);
alert(data.retailListPrice);
});
}

OPTIONS request being made for $.ajax

I have the following code which,currently im running on my local machine.I am making a call to a php script called getxml.php,which should send the contents of an xml file as the response.
But,instead of a GET request, in Firebug i see that an OPTIONS request is being made, like
OPTIONS getxml.php . I think im not making a cross domain Ajax request,but still am facing this problem . Any way to fix this ?
var employee_list = new Object;
$(function(){
$.ajax({
type:"GET",
url:"http://localhost/projectname/getxml.php",
datatype:"xml",
success: function(xml){
$(xml).find('employee').each(function(){
var name_text = $(this).find('name').text();
var url_text = $(this).find('url').text();
employee_list[name_text] = url_text;
$('<li></li>').html(name_text + ' (' + url_text + ')').appendTo('#update-target ol');
});
} //closing function
}); //closing $.ajax
}); //closing $(
getxml.php
<?php
//Send the xml file as response
header('Content-type: text/xml');
readfile('employee_results.xml');
?>
Thank You
Make sure getxml.php exists. OPTIONS usually means you have a slight misspelling.
change datatype to dataType and see if that fixes your problem. The rest of the code looks right.
edit: also, I'm not a PHP pro, but I wrote a map application which uses a similar approach. To return xml, I used:
header("Status: 200");
header("Content-type: text/xml");
echo file_get_contents($q,0); /*$q is the query/filename*/
exit();
I remember reading somewhere that header("Status: 200"); was required.
edit: Here is how I've done the same thing. I hope this helps.
/* call ajax method to retrieve earthquakes */
$.ajax({
type: "GET",
url: "../getxml.php?q=" + xmlLocation,
dataType: "xml",
success: function(xml){
$(xml).find('entry').each(function(){
/* Retrieve all needed values from XML */
var title = $(this).find('title').text();
var summary = $(this).find('summary').text();
var coord = $(this).find('georss\\:point').eq(0).text();
if(!coord){var coord = $(this).find('point').text();};
var points = coord.split(' ');
var latitude = parseFloat(points[0]);
var longitude = parseFloat(points[1]);
var htmlString = "<div class=\"infowindow\"><b>" +
title + "</b>" + "<p>" + summary + "<br></div>";
var myLatlng = new google.maps.LatLng(latitude,longitude);
var marker = new google.maps.Marker(
{
position: myLatlng,
map: map,
title: title
});
markers[markers.length] = marker;
addInfoWindow(marker, map, htmlString);
$('#output').text("Showing " + markers.length + " earthquakes");
});/* end each */
}
}); /* end $.ajax */
The php file is exactly as I posted above, but with "security" to respond only to ajax requests.

Categories