jquery $.get() not working on localhost - javascript

I'm trying to use jquery $.get() to obtain values from a server file.
Both files are currently on my machine in the /var/www directory (using linux).
I am aware of the cross-domain restriction for ajax, hence I placed the two files in /var/www.
The "client" file (f1.htm) is:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.9.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
$.get( "f11.htm", function( data, status ){ alert( "1" ); } );
/*
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","f11.htm",false);
xmlhttp.send();
alert( xmlhttp.readyState + " " + xmlhttp.status );
*/
alert( "2" );
</script>
</body>
</html>
while the "server" script (f11.htm) is simply:
<html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<head>
</head>
<body>
<?php
echo "server text";
?>
</body>
</html>
the client script ("f1.htm") gets stuck at the $.get() line. I've tried this with xmlhttprequest (which is commented), and it works. why is the $.get() line not working?.
TIA

You can try this code to examine the error function being returned instead of the shorthand $.get.
$.ajax({
type:'GET',
url: 'f11.htm',
data: {},
success: function(data) {
console.log(data);
}, error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});

Related

Google Distance Matrix API says: jQuery.Deferred exception: google is not defined | ReferenceError: google is not defined

I am using Google Distance Matrix API for my web application. When I tried loading the map, it shows me an error in the console log. I am new to the API and would appreciate any help. Many thanks! :)
Here is a screenshot of the errors in the console log
Below is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Carpark Demo Code</title>
<!--<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#400;600&display=swap" rel="stylesheet">-->
<style>
</style>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/json" src="https://maps.googleapis.com/maps/api/distancematrix/json?&key=AIzaSyAvlb7x4ZCfxvpxV90ha3g_YbaYfHPvfvk"></script>
<script>
$(function(){ // ready function
displayLiveData();
googleDistanceCalc();
});
function displayLiveData(){ // 1st Function - carpark details, address
$.ajax({
type: "GET",
url: 'https://maps.googleapis.com/maps/api/distancematrix/json?&key=AIzaSyAvlb7x4ZCfxvpxV90ha3g_YbaYfHPvfvk',
dataType: 'json'
})
.done(function(json) { /* same as ready function, when data finishes loading and do something after */
console.log("Successfully Loaded!");
})
.fail(function() {
console.log("Loading Error.");
});
}
</script>
</body>
</html>
Thanks for the help!

How to Use the JSON file in my HTML web page

I am trying to implement the following JSON file in my HTML page.
<html>
<head>
<title> test get</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
<script>
$(function() {
$.getJSON('json.json',function(data) {
$.each(data.quotes,function(key,value) {
alert( key+ "said by "+value);
});
});
});
</script>
</head>
<body>
</body>
</html>
Here is the JSON that i am working on.
{
"quotes": {
"hey there":"randomguy1",
"wassup":"randomguy2",
"coool":"randomguy3"
}
}
I have checked different tutorials and similar questions at stackoverflow still couldn't figure out the mistake.
Just fix your script code,
You MUST close the <script ...jquery> tag.
<html>
<head>
<title>test get</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(function () {
$.getJSON('json.json', function (data)
{
$.each(data.quotes, function (key, value) {
alert(key + "said by " + value);
});
});
});
</script>
</head>
<body> </body>
</html>
You can achieve it in a different manner. Use ajax to load a file content and parse it as a json.
$.ajax({
url : "helloworld.json",
success : function (data) {
//TODO parse string to json
}
});

got error when using javascript ajax json to retrieve php array

My html page is suppose to retrieve the array from the php page and alert the first element in the array. But when I run the html, got the following error, "Uncaught TypeError: Object function (E,F){return new o.fn.init(E,F)} has no method 'parseJSON' " in the console window. I tried to use jQuery.parseJSON(json_data) instead of $.parseJSON(json_data) but still got the same error. How can I fix this?
script.js:
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array =jQuery.parseJSON(json_data);
var rec = data_array[0];
alert(rec);
alert("GOOD");
},
error: function() {
alert("BAD");
} });
}
newcal.html:
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" href="demo.css">
<body onload="getArr();">
<div id="rounded"><div id="main" class="container">
<div id="pageContent">
Hello, this is the default content
</div>
</div>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
</html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
parseJSON was added in jQuery 1.4.1 (in 2010)
You are using jQuery 1.3.2 (from 2009), which is too old.
The current version of jQuery 1.x is 1.11 (released this year).
Use a more recent version of jQuery.
You should also tell the browser that you are sending it JSON instead of claiming that your JSON is HTML. (PHP defaults to claiming that anything it outputs through a web server is HTML)
<?php
header("Content-type: application/json");
$output = array("cat","dog");
echo json_encode($output);
?>
Then let jQuery parse it automatically:
success: function(data_array){
// Remove the following line. It will be parsed automatically.
// var data_array =jQuery.parseJSON(json_data);
var rec = data_array[0];

server side scripting in to javascript

i am try to get latitude and longitude value from ip address
after getting lat and lng value POST in to php file using AJAX and generate new xml file
this is my html file:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function getlg(){
var lan=geoip_latitude();
var lng=geoip_longitude();
var gen = $('#Sex').val();
var date = $('#date').val();
$.ajax({
type: "POST",
url: "http://localhost/SVN/trunk/home/url.php?lat="+lan+"&lng="+lng+'&radius'+$('#radius1').val(),
contentType: "text/html",
success: function(token) {
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
}
</script>
<body>
<div id="region"><h5></h5></div>
Enter Radius: <input type="text" id="radius1"></input>
<input type="button" id="filter"onclick="getlg()" value="Go">
</body>
</head>
</html>
this is my php file:-
<?php
function convertNodeValueChars($node) {
if ($node->hasChildNodes()) {
foreach ($node->childNodes as $childNode) {
if ($childNode->nodeType == XML_TEXT_NODE) {
$childNode->nodeValue = iconv('utf-8', 'ascii//TRANSLIT', $childNode->nodeValue);
}
convertNodeValueChars($childNode);
}
}
}
$url='http://services.gisgraphy.com/geoloc/search?lat='.$_GET['lat'].'&lng='.$_GET['lng'].'&radius='.$_GET['radius'];
$doc = new DOMDocument();
$doc->load($url);
$doc->save('General.xml');
?>
in this file i am try to Get lat and long and radius from html ajax function and getting one new xml file with help of url.
but its take so much time if radius is biggest.
i want to try this php code in java script dont like server side scripting.
please help me out with this...
thanks...
try this:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://j.maxmind.com/app/geoip.js" ></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function myFunction(){
var lan=geoip_latitude();
var lng=geoip_longitude();
var gen = $('#Sex').val();
var date = $('#date').val();
var location = "http://services.gisgraphy.com/geoloc/search?lat="+lan+"&lng="+lng+'&radius'+$('#radius1').val();
document.write('Link text');
}
</script>
<body>
<div id="region"><h5></h5></div>
<input type="text" id="radius1" onchange="myFunction()"></input>
</body>
</head>

YQL JSON script not returning?

I have a script here, copied pretty much directly off this. Why doesn't the code, listed below, return anything?
ajax.html:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html dir="ltr" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Cross-Domain Ajax Demo</title>
</head>
<body>
<div id="container">
<form>
<p><label>Type a URL:</label><input type="text" name="sitename" id="sitename"/></p>
<p><input type="submit" name="submit" id="submit" value="Make Cross Domain Ajax request"</p>
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="cross-domain-requests.js"></script>
<script type="text/javascript">
$('form').submit(function() {
var path = "www.google.com";
requestCrossDomain(path, function(results) {
$('#container').html(results);
});
return false;
});
</script>
</body>
</html>
cross-domain-requests.js:
// Accepts a URL and a callback function to run.
function requestCrossDomain( site, callback ) {
// If no URL was passed, exit.
if ( !site ) {
alert('No site was passed.');
return false;
}
// Take the provided URL, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=cbFunc';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, cbFunc );
function cbFunc(data) {
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}
(I'm relatively new to scripting and Ajax, so I apologise in advance if I do anything stupid.)
Try changing the callback in var yql to callback=? and the select statement to 'from xml' like this:
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';

Categories

Resources