Passing response from multiple XMLHttpRequests to div - javascript

I am querying a PostGIS database based on where a user clicks on a google map. I am then parsing the JSON response into a googleMaps infoWindow. This has been working great but I'd now like to query multiple urls and use those responses to fill in the infoWindow. Below is an example of the functions I've used that work great. Note: please disregard the url provided as I just made it up for this example.
var clickLoc;
function queryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var loUrl = 'http://www.myspatialdataset.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = clickResponse;
try {
req.open("GET", loUrl, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = clickResponse;
req.open("GET", loUrl, true);
req.send();
}
}
}
function clickResponse(){
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
var clickPingBack = JSON.parse(req.responseText);
var loResponse = clickPingBack;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
fillWithClicked(loResponseParsed);
}
else
{
var loResponseParsed=' other';
fillWithClicked(loResponseParsed);
}
}
}
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(loResponseParsed){
infowindow.setContent(loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
How could I now do this for multiple url requests and pass those responses to the same, fillWithClicked function that fills in the infoWindow?
The code below is obviously wrong but may better explain what I am trying to do i.e. multiple URLS and filling the infoWindow with the response from two url requests. This sometimes works but is totally wrong
var clickLoc;
function distQueryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var distUrl = 'http://www.myspatialdataset.com/sql/?q=select%20district%20from%20mt_elk%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
distReq = new XMLHttpRequest();
distReq.onreadystatechange = loQueryAct(clickLoc);
try {
distReq.open("GET", distUrl, true);
} catch (e) {
alert(e);
}
distReq.send(null);
} else if (window.ActiveXObject) { // IE
distReq = new ActiveXObject("Microsoft.XMLHTTP");
if (distReq) {
distReq.onreadystatechange = loQueryAct(clickLoc);
distReq.open("GET", distUrl, true);
distReq.send();
}
}
}
function loQueryAct(clickLoc){
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var loUrl = 'http://www.myspatialdataset.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
if (window.XMLHttpRequest) { // Non-IE browsers
loReq = new XMLHttpRequest();
loReq.onreadystatechange = distClickResponse;
try {
loReq.open("GET", loUrl, true);
} catch (e) {
alert(e);
}
loReq.send(null);
} else if (window.ActiveXObject) { // IE
loReq = new ActiveXObject("Microsoft.XMLHTTP");
if (loReq) {
loReq.onreadystatechange = distClickResponse;
loReq.open("GET", loUrl, true);
loReq.send();
}
}
}
function distClickResponse(){
if (distReq.readyState == 4 && loReq.readyState == 4) { // Complete
if (distReq.status == 200 && loReq.status == 200) { // OK response
var distPingBack = JSON.parse(distReq.responseText);
var distResponse = distPingBack;
var loPingBack = JSON.parse(loReq.responseText);
var loResponse = loPingBack;
if (distResponse.rows.length>0)
{
var distResponseParsed=distResponse.rows[0].district;
}
else
{
var distResponseParsed=' other';
}
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
}
distFillWithClicked(loResponseParsed,distResponseParsed);
}
}
var infowindow = new google.maps.InfoWindow;
function distFillWithClicked(distResponseParsed,loResponseParsed){
infowindow.setContent(distResponseParsed+loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}

I figured it out. Using getJSON instead of XMLHttpRequest was the key. I know this could be cleaner but it does work.
var clickLoc;
function queryAct(event){
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var toFillArray=Array();
var loUrl='http://www.mypostgis.com/sql/?q=select%20ownercateg%20from%20stew_owners%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
var distUrl='http://www.mypostgis.com/sql/?q=select%20district%20from%20mt_elk%20where%20ST_Intersects%28the_geom,%20ST_GeomFromText%28%27POINT%28'+clickLng+'%20'+clickLat+'%29%27,4326%29%29';
$.getJSON(loUrl,function(tmpLoDat){
if (tmpLoDat.rows.length>0)
{
var tempCat=tmpLoDat.rows[0].ownercateg;
toFillArray.push(tempCat);
}
else
{
var tempCat='other';
toFillArray.push(tempCat);
}
otherFunction(toFillArray,distUrl);
})
}
function otherFunction(toFillArray,distUrl){
$.getJSON(distUrl,function(tmpDistDat){
if (tmpDistDat.rows.length>0)
{
var tempDist=tmpDistDat.rows[0].district;
toFillArray.push(tempDist);
}
else
{
var tempDist='Other';
toFillArray.push(tempDist);
}
fillWithClicked(toFillArray);
})
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(toFillArray){
infowindow.setContent(toFillArray[0]+toFillArray[1]);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}

If you want the data to grow your element, let's try something like that :
function fillWithClicked(loResponseParsed){
document.getElementById("regulations").innerHTML += loResponseParsed;
}
If the calls of your function are not in the same page, you'll need to use a cache file and a user_id (session id, cookie id or IP adress...):
// js & jquery for example
function fillWithClicked(loResponseParsed,user_id)
{
$.post('cachecreate.php',{content:loResponseParsed,user_id:user_id},
function()
{
$.get('cachefile_'+user_id+'.html',
function(data)
{
document.getElementById("regulations").innerHTML=data;
});
});
}
// cachecreate.php for example
<?php
$cache = "cachefile_".$_POST['user_id'].".html";
ob_start();
if(file_exists($cache))
{
include($cache);//or readfile(); i forgot...
echo "<hr/>".$_POST['content'];// Strip <hr/> for JSON
}
else
{
echo $_POST['content'];
}
$page_content=ob_get_contents();// if JSON needed : json_encode($page_content);
ob_end_clean();
file_put_contents($cache, $page_content);// PHP 5+ function
?>
I hope that it may help you, or bring you to the solution.
EDIT regarding your new details
Try something like this (I lighten your code...).
With this you can add as multiple urls as you want.
var clickLoc;
function queryAct(event)
{
clickLoc=event.latLng;
var clickLat=clickLoc.lat();
var clickLng=clickLoc.lng();
var url=Array();
var data=null;
url['loUrl'] ="url1";
url['distUrl'] ="url2";
url['otherUrl'] ="urlx";
for(page in url)
{
data+=getJSON(page);
}
fillWithClicked(data);
}
function getJSON(url)
{
if (window.XMLHttpRequest)
{req = new XMLHttpRequest();}// Non-IE
else if (window.ActiveXObject)
{req = new ActiveXObject("Microsoft.XMLHTTP");}// IE
if(req)
{
req.open("GET", url, true);
req.send(null);
req.onreadystatechange = function() {
if(req.readyState == 4)
{
if (req.status == 200)
{ // OK response
var clickPingBack = JSON.parse(req.responseText);
var loResponse = clickPingBack;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
return loResponseParsed;
}
}
}
}
}
var infowindow = new google.maps.InfoWindow;
function fillWithClicked(loResponseParsed)
{
infowindow.setContent(loResponseParsed);
infowindow.setPosition(clickLoc);
infowindow.open(map);
}
EDIT -> External domain files
httpRequest doesn't work with files in another domain.
You can use one of those solutions, I may use the second for me.
PHP Solution
// In your js file, change the urls like this
url['url_x'] ='myphppage.php?url=url_x_to_parse';
// myphpage.php script that displays the content of the external file
<?php
if(isset($_GET['url'])) {
header("Content-type: text/json");
echo file_get_contents(urldecode($_GET['url']));
}
?>
JQUERY solution (better one)
// change the name of getJSON function cause jquery uses the same name...
function getURLcontent(url)
{
$.get(url,function(data){
var clickPingBack = JSON.parse(data.responseText);
var loResponse = clickPingBack;
loResponse=data;
if (loResponse.rows.length>0)
{
var loResponseParsed=loResponse.rows[0].ownercateg;
}
else
{
var loResponseParsed=' other';
}
return loResponseParsed;
});
}
download jquery library http://code.jquery.com/jquery-1.7.1.min.js
include jquery plugin in the head of your page with <script src="jquery-1.7.1.min.js"></script>

Related

Send and process FormData

I've been struggling for hours with following code without success. In my html I have several inputs (type=text, type=date and selects), and a button calling a js function: onclick=SendNewData().
The JS function is something like the following:
function SendNewData() {
var MyData1=document.getElementById("id1").value;
var MyData2=document.getElementById("id2").value;
var MyData3=document.getElementById("id3").value;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open('POST', 'Handler.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("FormNuevaCom").innerHTML = xmlhttp.responseText;
}
}
var data = new FormData;
data.append('DATA1', MyData1);
data.append('DATA2', MyData2);
data.append('DATA3', MyData3);
xhr.send(data);
}
and the Handler.php is something like the following:
if(isset($_POST['DATA1'])) {
$MyVar=$_POST['DATA1'];
echo "Hi there! ".$MyVar." received...";
}
I canĀ“t get any response. Anyone can spot the problem?

Trigger `PHP` file using JS

I have 3 files, one HTML, PHP and JS. I have a button in HTML and I want to trigger the PHP file when it's clicked, through Javascript. I tried the following code, but for some reason it gives me the error message every time:
JavaScript
function getOutput() {
getRequest(
'create_json.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
<button id="submit" onclick="getOutput()">Submit</button>
<div id="output">waiting for action</div>
<?php
function get_data(){
$connect=mysqli_connect("localhost", "root", "root", "openingpage");
$query="SELECT * FROM created_list ";
$result=mysqli_query($connect, $query);
$list_data=array();
while($row=mysqli_fetch_array($result)){
$list_data[]=array(
'ModelID' => $row["ModelID"],
'ImageID' => $row["ImageID"],
'ListID' => $row["ListID"]
);
}
return json_encode($list_data);
}
$file_name=date('d-m-Y').'.json';
if(file_put_contents($file_name,get_data())){
echo $file_name.' file created';
}
else{
echo 'There is some error';
}
?>
I'm always getting the "Bummer: there was an error!" message. Why can't I get it . I checked the code more than 100x times but can't find whats going wrong in this code.
Thanks in advance.

changing the text of a button in ajax

I Have list confirmation buttons generated dynamically using PHP.When I click a button i want it change to "approved".But it is not doing so?Nothing changes though the query is submitted successfully.Any help please.Here is my js code snippet:
function appr ($ref) {
var job_id= $ref;
var resp;
var buttons=$('.confirm');
buttons.click(function(){
var $this=$(this);
$this.text=('approved');
});
if (window.XMLHttpRequest) {
resp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
resp = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "job_id="+job_id
resp.open("POST",
"approve.php",
true);
resp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
resp.send(data);
resp.onreadystatechange = display_data;
function display_data() {
if (resp.readyState == 4) {
if (resp.status == 200) {
document.getElementById("myDiv").innerHTML=resp.responseText;
} else {
alert('Request not successful.');
}
}
}
}
you can do it like that
$this.html("approved");

How do I have the text and xml files open in a new window/tab?

Here is the code. I am fairly new to JavaScript and I'm learning more every day. This code is from an example from a textbook. Thank you for your responses. Another question I'd like to ask is how can I display the returned text in an unordered list? Would that be something to include in the html side of things or can it be done within the JavaScript file?
window.addEventListener("load",initAll,false);
var xhr = false;
function initAll() {
document.getElementById("makeTextRequest").addEventListener("click",getNewFile,false);
document.getElementById("makeXMLRequest").addEventListener("click",getNewFile,false);
}
function getNewFile(evt) {
makeRequest(this.href);
evt.preventDefault();
}
function makeRequest(url) {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
if (xhr) {
xhr.addEventListener("readystatechange",showContents,false);
xhr.open("GET", url, true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}
function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {
var outMsg = getText(xhr.responseXML.getElementsByTagName("choices")[0]);
}
else {
var outMsg = xhr.responseText;
}
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
function getText(inVal) {
if (inVal.textContent) {
return inVal.textContent;
}
return inVal.text;
}
}
By the looks of it, you are making an AJAX request and are receiving XML.
In this case, I would:
Open up a new page with window.open()(returns a new Window object)
And then change the document.body.innerHTML of that new page to the XML you have
If you had a webpage that held the XML(maybe the server you are requesting to has one), you can just do:
window.open("page.xml");

window.location not firing after ajax event

I'm not sure if this is related to an ajax call or not. I'm very new to Ajax, and so I suspect it is the cause.
I run the following javascript:
function GetXmlHttpObject() {
"use strict";
var objXMLHttp = null;
if (window.XMLHttpRequest) {
objXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
objXMLHttp = new window.ActiveXObject("Microsoft.XMLHTTP");
}
return objXMLHttp;
}
function delete_director(i) {
"use strict";
var r, url;
r = window.confirm("Are you sure you want to disable this director");
url = "ajax.php?task=director&event=delete&UserId=" + i;
if (r === true) {
mdata = new GetXmlHttpObject();
if (mdata === null) {
alert("Browser does not support HTTP Request");
return;
}
mdata.open("GET", url, true);
mdata.send(null);
}
}
And that calls into the following php function:
function deletedirector()
{
$UserId=mysql_real_escape_string($_GET['UserId']);
$query = "update tbl_users set IsDisabled='1' where UserId=".$UserId;
$result = mysql_query($query) OR die('Cannot perform query!');
if ($result) {
error_log("a");
?><script type="text/javascript">window.location='index.php?task=director&success=Director Successfully Deleted.'</script><?
} else {
error_log("b");
?><script type="text/javascript">window.location='index.php?task=director&error=Director Deletion Failed.'</script><?
}
}
The db shows that the director was deleted, and "a" prints in the error log, but the window.location never fires.
The user experience is that the browser prompts for confirmation, and after that - nothing. A javascript console shows now error.
Any ideas?
You already return new object (of XMLHttpRequest API) with function, so you don't need new here
...
if (r === true) {
mdata = GetXmlHttpObject();
...
and try to use onreadystatechange like this
mdata.onreadystatechange = function(){
if (mdata.readyState === 4) {
alert("some text");
} else {
alert(mdata.status);
}
};

Categories