Ajax Javascript Scope Issues - javascript

I am having a javascript scope issue I want to take the responce text from the ajax call and place it into a global variable. Then process the JSON in another function here is my code.
var JSONDATA = "not gatherd";
var ajaxCalls = (function(){
var ajaxer = {
defaults:{
url:"test.php",
DirectHTML: true,
element:"#ajaxerizer"
},
setup:function(setup){
var defaulLengther = this.defaults
for (var key in defaulLengther)
{
if(setup.hasOwnProperty(key))
{
this.defaults[key] = setup[key];
}
}
if(this.defaults.DirectHTML === false)
{
if (window.XMLHttpRequest) {
this.ajaxRequester = new XMLHttpRequest();
}
if (window.ActiveXObject) {
this.ajaxRequester = new ActiveXObject("Microsoft.XMLHTTP");
}
this.ajaxRequester.open('POST', this.defaults.url, true);
this.ajaxRequester.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.ajaxRequester.send();
}
this.callIt();
},
callIt:function(){
if(this.defaults.DirectHTML === true)
{
$(this.defaults.element).load(this.defaults.url);
}
if(this.defaults.DirectHTML === false)
{
this.ajaxRequester.onreadystatechange = function(){
if (this.readyState == 4) {
//This is where I have trouble
alert(this.responseText);
JSONDATA = this.responseText;//This is the data I want to process and use
alert(JSONDATA);
}
}
}
}
}
return ajaxer
})();
Here is the Index
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="simpleHtmlAjax.js"></script>
</head>
<body>
<div id="ajaxerizer">
<script>
ajaxCalls.setup({
url:"json.php",
DirectHTML: false,
});
alert(JSONDATA);
</script>
</div>
</body>
</html>
and the JSON data
<?php
$json = array("one" => 1,"two" => 2,"three" => 3,"four" => 4);
echo json_encode($json);
?>
Thank you for any help.

You're already including jQuery in your HTML, so why not just use jQuery's AJAX helper functions to automatically process the JSON data?
$.post("json.php", function (data) {
// do something with data, which should be a plain JS object:
// {"one":1, "two":2, "three":3, "four":4}
}, "json");

Related

why php results in HTML are undefined when using JavaScript

I need to get the IP of the client. I am able to get it through PHP variable
"$_SERVER['REMOTE_ADDR']". I get this ip from server side php to html page through AJAX request but when I want to use this IP value in JavaScript it is showing that the value is undefined.
any solution?
PHP code:
<?php echo $_SERVER['REMOTE_ADDR'];?>
HTML CODE:
<body onload='ip(); ip2();'>
<kbd id='ip' ></kbd>
JavaScript code:
function ip() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ip").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "ip.php");
xhttp.send();
}
function ip2() {
setTimeout(function () {
var ip = document.getElementById("ip").value;
alert(ip);
}, 1000);
}
First of all you should validate that you are getting the right response from your AJAX request by check that the result is certainly written to the element with id attribute "ip", and than instead of using:
var ip = document.getElementById('ip').value;
You should use Node.textContent to get the text content:
var ip = document.getElementById('ip').textContent;
Code example (without AJAX request):
function ip() {
document.getElementById('ip').innerHTML = '127.0.0.1';
}
function ip2() {
setTimeout(function () {
var ip = document.getElementById('ip').textContent;
console.log(ip);
}, 1000);
}
<body onload="ip(); ip2();">
<kbd id="ip" ></kbd>
You want your Ip Address in java script , so have to put ip address in that tag i think.
<?php $ip_address = $_SERVER['REMOTE_ADDR'];?>
<body onload='ip(); ip2();'>
<kbd id='ip' ><?php echo $ip_address; ?></kbd>
<?php echo $_SERVER['REMOTE_ADDR'];?>
<html>
<head>
</head>
<body onload='ip();'>
<div id='ip' ></div>
</body>
</html>
<script>
function ip() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ip").innerHTML =
this.responseText;
ip2(this.responseText);
}
};
xhttp.open("POST", "try.php");
xhttp.send();
}
function ip2(stringvalue) {
setTimeout(
function() {
var ip = document.getElementById("ip").value;
alert(stringvalue);
},2000);
}
</script>
run this code you might found what is the problem.

How to get HTML source with JavaScript?

I am trying to get HTML source with JavaScript:
Why this does not work?:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function MyGetHTML()
{
$.get("www.example.com/test1.html", function(data){
return data;
});
}
</script>
</head>
<body>
test 30.9.2015
<script>
alert(MyGetHTML());
</script>
</body>
</html>
(Below, i'm assuming that you need to get content from filen IN your source, from the same origin of your page.)
Your code doen't works because the the return of your MyGetHTML method is the get request itself, and the success callback of your request returns the data.
You could do:
function MyGetHTML(){
$.get("www.example.com/test1.html", function(data){
//alert(data);
//or use console.log() instead.
console.log(data);
});
}
And then
MyGetHTML(); //This will log your data after the succesfull request.
Further reading: https://api.jquery.com/jquery.get/
Hint on your use case:
A simple tutorial from Tuts+ on making simple ajax requests.
With pure JS:
load('test.html', function(xhr) {
document.getElementById('container').innerHTML = xhr.responseText;
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
Or with jquery library
$('#container').load('test.html');
Because you're returning to the get not the function itself. Try like this:
function MyGetHTML()
{
var datum = '';
$.get("www.example.com/test1.html", function(data){
datum = data;
});
return datum;
}

Adding a loading text while an AJAX function is executing

I've been trying to add a loading text that would display while an AJAX function is being executed for a long while now, and all of my attempts (which includes using the ajaxStart and ajaxStop, among other things) haven't been working at all. Any help is appreciated!
Here is the webpage that the script in question is located on, if you want to see it in action. The way it works is that you enter in a url and the function will grab the meta tags of that URL.
Meanwhile, here is the relevant HTML, Javascript, and PHP:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Keywords Grabber</title>
<script src="ajax.js"></script>
<script>
function display(content) {
document.getElementById("displaydiv").innerHTML = content;
}
window.onload = function () {
document.getElementById("btn1").onclick = function () {
var url = document.getElementById("txt1").value;
doAjax("metatags.php", "url=" + url, "display", "post", 0);
}
}
</script>
</head>
<body>
http://<input type="text" id="txt1" value="" />
<input type="button" id="btn1" value="Get Keywords" />
<h3>Keywords Received:</h3>
<div id="displaydiv"></div>
</body>
</html>
JavaScript
function getXMLHttpRequest() {
try {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
return new ActiveXObject("Msml2.XMLHTTP");
}
}
catch(e) {
return new XMLHttpRequest();
}
}
function doAjax(url, query, callback, reqtype, getxml) {
var myreq = getXMLHttpRequest();
myreq.onreadystatechange = function () {
if (myreq.readyState == 4) {
if (myreq.status == 200) {
var item = myreq.responseText;
if (getxml == 1) item = myreq.responseXML;
eval(callback + '(item)');
}
}
}
if (reqtype.toUpperCase() == "POST") {
requestPOST(url, query, myreq);
} else {
requestGET(url, query, myreq);
}
}
function requestGET(url, query, req) {
var myRandom = parseInt(Math.random()*99999999);
if (query == '') {
var callUrl = url + '?rand=' + myRandom;
} else {
var callUrl = url + '?' + query + '&rand=' + myRandom;
}
req.open("GET", callUrl, true);
req.send(null);
}
function requestPOST(url, query, req) {
req.open("POST", url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(query);
}
PHP
<?php
$tags = #get_meta_tags('http://'.$_REQUEST['url']);
$result = $tags['keywords'];
if(strlen($result) > 0) {
echo $result;
} else {
echo "No keywords metatag is available.";
}
?>
something like this
<div id="loading" style="display:none;">loading</div>
Javascript
$('#loading').css('display', 'block');
$.post(url, {}, function(data){
$('#loading').css('display', 'none');
});

Passing response from multiple XMLHttpRequests to div

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>

JavaScript + Querystring + div

How to load content in to a html page. please note IM not allowed to use php or C. Only javascript and html.
for example
load Page B in to Page A
http:myweb.com/index.html?load=pageb
thank you.
Issue an AJAX request to Page B
Get the contents using responseText
Display the contents inside a div using innerHTML property.
If you can use a js framework then I would suggest jQuery and #marcgg's answer will do it.
Just plain JavaScript:
<html>
<head>
<script>
function getUrlVars() {
var map = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
map[key] = value;
});
return map;
}
function createRequestObject() {
var ro;
// Mozilla, Safari,...
if (window.XMLHttpRequest) {
ro = new XMLHttpRequest();
if (ro.overrideMimeType) {
ro.overrideMimeType('text/xml');
// See note below about this line
}
// IE
} else if (window.ActiveXObject) {
try {
ro = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ro) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
return ro;
}
function sndReq(param,server,handler) {
//location.href = server+"?"+action; //uncomment if you need for debugging
http = createRequestObject();
http.open('GET', server, true);
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
http.onreadystatechange = handler;
http.send(param);
}
handler_function = function()
{
if(http.readyState == 4)
{
if (http.status == 200)
{
document.getElementById("your_div_element").innerHTML = http.responseText;
}
else
{
alert('There was a problem with the request.');
}
}
}
</script>
</head>
<body>
<div id="your_div_element"></div>
<script>
var getvars= getUrlVars();
sndReq(null, getvars['action'], handler_function);</script>
</body>
</html>
html:
//Page A
<html>
<head><title>Page A</title></head>
<body>
<div id="pageB"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pageB').load('pageb.html')
});
</script>
</body>
</html>
Using jQuery:
$.ajax({
type: "POST",
url: "http://some.com/page.html",
success: function(msg){
alert( "here's your data: " + msg );
jQuery("#yourDivID").html(msg);
}
});
http://docs.jquery.com/Ajax/jQuery.ajax
edit: added how to put it into a div

Categories