No return value from getJSON - javascript

The alert with "success" is not fired when i run this. I checked with firebug, and it tells me that ret is undefined. What does that mean?
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var ret = $.getJSON(URL, function(data, textStatus) {
alert("success");
});
}
EDIT:
this is the test.jsp btw
<%# page language="java" contentType="application/json; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.util.*, net.sf.json.JSONObject"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
response.setContentType("application/json");
JSONObject jo = new JSONObject();
jo.put("location", "1");
jo.put("name", "someUni");
out.println(jo);
out.flush();
%>
</body>
</html>

The AJAX call did not work. A few points to check, is the URL correct? Did you check the application server log to see if the call has ever reached. Can you check firebug for the HTTP code if the AJAX call is successful?
EDIT:
(Changed from text/json to application/json) Thanks Bergi
JSP:
<%# page contentType="application/json" %>
Java Servlet:
response.setContentType("application/json");

First check for ".jsp" file returning json data or not
Use one more parameter for callback
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
}
User like this
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var ret = $.getJSON(URL,"",function(data){
alert("success");
});
}

ret is scoped to your function, so only code inside your function can access it. My guess is that you don't have a web server running on port 8080 of your local computer or the URL is invalid for some other reason. Try .ajax if you want to get a callback on the error also (fiddle):
function checkUni() {
var URL = "http://localhost:8080/GradSchoolApp/test.jsp";
var ret = $.ajax(
{
url: URL,
success: function(data, textStatus) {
alert('success!');
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error "' + textStatus + '": ' + errorThrown);
}
});
}
You might want to check your json too, the getJson page warns that it will fail silently on inavlid json, including strict requirements like quoted property names, you can try just using .get and deserializing yourself.

Related

getJSON in Javascript

I am new to html and javascript.As far as i know the following code should give an alert when i press "Get JSON Data" button.But the page is not giving me any response.Any help is greatly appreciated.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<div></div>
</body>
</html>
I suspected that should be the Cross-domain issue. That is why I asked for the console log. you have couple of choices:
config the cross-domain headers from your servlet/backend response.
(ex: if you're using a Servlet:)
response.setHeader('Access-Control-Allow-Origin','*');
use jsonp call back
$.getJSON("http://example.com/something.json?callback=?", function(result){
//response data are now in the result variable
alert(result);
});
The "?" on the end of the URL tells jQuery that it is a JSONP
request instead of JSON. jQuery registers and calls the callback
function automatically.
use $.ajax with CORS enabled or with jsonp
ex:
$.ajax({
url: surl,
data: {
id: id // data to be sent to server
},
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback"
});
// Named callback function from the ajax call when event fired.
function jsonpcallback(rtndata) {
// Get the id from the returned JSON string and use it to reference the target jQuery object.
var myid = "#" + rtndata.id;
$(myid).feedback(rtndata.message, {
duration: 4000,
above: true
});
}
or else, download and configure "CORS.jar" in your server side which will allow the cross-domain requests.
HOW ?
Hope you can get some idea. follow which suits for you ..
Replace the JSON call with
$.getJSON("http://127.0.0.1:5000/2", function(result){
if (result.length == 0){
alert("nothing") ;
}
if (result.length){
alert("success") ;
}
// $("div").append(myObject);
}).fail(function( jqxhr, textStatus, error ) {
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err )
});
That way you can see what goes wrong. The javascript looks OK, I suspect it's a server issue.
You could also try getting back JSON from some random source, like http://1882.no/API/business/get/results.php?q=skole&page=0

Taking JSON information in another page on Javascript

So Ive check quite a lot of examples and quite a lot of tutorials but it is definitely not working out for me for some unknown reason.
Ive already checked Get JSON data from another page via JavaScript and it didnt work out for me.
So what I want to do is take some information from MySQL and use it on a Jscript function I am using on another .php, this means taking information retrieved from mysql (connect.php) to another file (test.php), but although the information is correctly retrieved from connect.php it is not moving to the other file.
These are my files.
connect.php
<?php
mysql_connect('localhost', 'root', '') or die (mysql_error());
mysql_select_db('dbexample') or die (mysql_error());
$data = mysql_query("SELECT * FROM lugares")
or die(mysql_error());
$arr = array();
while ($obj = mysql_fetch_object($data)) {
$arr[] = array('latt' => $obj->latt,
'lng' => $obj->long,
'nombre' => $obj->nombre,
'direccion' => $obj->direccion,
);
}
echo '{"users":'.json_encode($arr).'}';
?>
test.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript">
$.ajax({
type: "POST",
url:"connect.php",
async: true,
success: function(datos){
var dataJson = eval(datos);
for(var i in dataJson){
alert(dataJson[i].latt + " _ " + dataJson[i].lng + " _ " + dataJson[i].nombre);
}
},
error: function (obj, error, objError){
//avisar que ocurriĆ³ un error
}
});
</script>
</head>
<body>
<p>Super freak</p>
</body>
</html>
Any help will be greatly appreciated.
EDIT: I modified my script on test.php but something doesn't feel right; I'm losing it here :(
<script type="text/javascript">
$.ajax({
type: "POST",
url:"connect.php",
dataType: "JSON",
async: true,
success: function(datos){
var dataJson = $.parseJSON(datos);
$.each(dataJson, function(){
alert(dataJson.latt + "_"+ dataJson.lng);
}
},
error: function (obj, error, objError){
//avisar que ocurriĆ³ un error
}
});
</script>
Thanks!
there are two issues
your return type looks like json encoded in connect.php so add dataType: JSON in $.ajax
in test.php your success data should be json decoded to Jquery so you can use $.parseJson(data).
please refer this [example]: (http://www.jquerybyexample.net/2012/05/how-to-read-and-parse-json-using-jquery.html)
Try changing alert(dataJson[i].latt to alert(dataJson[i].users.latt
I may be wrong on this, but it looks like you never get inside the users item that you hardcoded into the response.
i see the problem
$.ajax is jquery element so
first include jquery.js file, then add document.ready inside this use $.ajax
the below example worked for me
this is your test.php
$(document).ready(function(){
//start ajax request
$.ajax({
url: "test.php",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var jsonData = $.parseJSON(data);
//now json variable contains data in json format
alert(jsonData.firstName);//access first array
alert(jsonData.series[0]);//access second array elements
}
});
});
your connect.php should return json encoded array:
$php_array = array('firstName'=>'Walter','lastName'=>'White', 'series'=>array('episode1','episode2'));
echo json_encode($php_array);

passing data from js file to php using jquery ajax

ajaxcheck.js
var val = "hai";
$.ajax(
{
type: 'POST',
url: 'ajaxphp.php',
data: { "abc" : val },
success :function(data)
{
alert('success');
}
}
)
.done(function(data) {
alert("success :"+data.slice(0, 100));
}
)
.fail(function() {
alert("error");
}
);
ajax.html
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" src="ajaxcheck.js"></script>
<title>ajax request testing</title>
</head>
<body>
</body>
</html>
ajaxphp.php
<?php
$v_var = $_POST["abc"];
print_r($_POST);
if(isset($_POST["abc"]))
{
echo $v_var;
}
else
{
echo "Data not received";
}
?>
When I run the ajax.html file ,I get success alert. But when I run ajaxphp.php file it shows notice like:
undefined index abc
Why is that the data is not received in $v_var ? where i am mistaking ?please help.
Actually the ajaxphp.php file is used to receive the data from the
post method and i will give response .
In First case by using ajax post method it will call to ajaxphp.php file.
In Second case your using direct file call without any post data(that's way it shows error)
Try this
var val = "hai"
$.post( "ajaxphp.php", {'abc':val}function( data ) {
alert( "Data Loaded: " + data );
});
jQuery expects an object as data, remove the double-quotes:
data: { abc : val }

Parsing xml data from a remote website

I would like to parse the xml data from a remote website http://services.faa.gov/airport/status/IAD?format=xml...But I was not able to parse the xml data and I am only getting error. But I was able to parse the JSON data from the same remote website http://services.faa.gov/airport/status/IAD?format=json. The code I have used to parse the xml data is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Aviation</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=xml",
dataType: "xml",
success: function (xml) {
result = xml.city;
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the city name" onclick=xmlparser() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
I was only getting the error as 'o Error' in the alert box since I have printed the error message. Anybody please helpout to parse the xml data from the remote website.
Note: I have also 'City' instead of 'city' but its not working...
Thanks in advance...
I don't believe that will work since the service is still returning xml. jsonp is expecting a n object literal as an argument to pass to the callback. I believe if you run this locally you'll realize there's no data being consumable in your success. Try this
$.ajax({
type: "GET",
url: "http://services.faa.gov/airport/status/IAD?format=json",
dataType: "jsonp",
success: function (data) {
document.myform.result1.value = data.city;
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
Here is the example for creating a proxy with asp.net mvc 3. I just created an action that returns a ContentResult which maps to a string but I define the content type as text/xml. This simply just makes a webrequest to the service and reads the stream in to a string to send back in the response.
[HttpGet]
public ContentResult XmlExample()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://services.faa.gov/airport/status/IAD?format=xml");
string xml = null;
using (WebResponse response = request.GetResponse())
{
using (var xmlStream = new StreamReader(response.GetResponseStream()))
{
xml = xmlStream.ReadToEnd();
}
}
return Content(xml, "text/xml");
}
Your xmlParser function will look like this:
<script type="text/javascript">
var result;
function xmlparser() {
$.ajax({
type: "GET",
url: "XmlExample",
dataType: "xml",
success: function (xml) {
result = $(xml).find("City").text();
document.myform.result1.value = result;
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
}
</script>
jQuery ajax's converts the data by using $.parseXML internally which removes the requirement for us to even call this in the success block. At that point you have a jQuery object that you can use it's default DOM functions to find the City Node.
Make sure to replace the XmlExample with the url that it maps to based on your controller.
The solution is quite simple (mentioned in Pekka's comment)
1.On your server add a file IAD_proxy.php
2.Put the following code inside it
header("Content-type: text/xml; charset=utf-8");
echo file_get_contents('http://services.faa.gov/airport/status/IAD?format=xml');
3.Change the url in your Ajax request to IAD_proxy.php.
In case you're using any other server-side language, try to implement the same idea.
Edit: Please read about Parsing XML With jQuery, here's what I've tried and it's working.
Javscript:
$.ajax({
type: "GET",
url: "IAD_proxy.php",
dataType: "xml",
success: function (xml) {
alert($(xml).find('City').text());
},
error: function (xml) {
alert(xml.status + ' ' + xml.statusText);
}
});
Here I tried it with document.write($(xml).find('City').text());

$.ajax not working properly on IE6

Basically, I have something like this:
$.ajax({
type: "GET",
url: "my_url",
cache: true,
success: function(data) {
/* code here */
},
dataType: 'json'
});
This code is working in all tested browsers (IE7/8, chrome, safari, firefox) but in IE6 the success function is not called.
I used Fiddler to see what's going on in the HTTP requests, and everything seems normal, I get the expected result as an HTTP answer but success doesn't seem to be called in IE6, same for onerror.
Any thoughts?
Try using complete instead of success. If it fires consistently then you can evaluate the status code to determine if it was successful...
$.ajax({
type: "GET",
cache: true,
complete: function(xhr) {
if(xhr.status != 200) {
throw "Error!";
return;
}
var data = xhr.responseText;
}
});
Are you sure it's not just a cache thing? Remove your browsers cache and test again.
A good test case would be getting rid of the 'cache' option, and also making it a POST request (since GET ajax calls are always cached in ie6).
You don't mention the server-side code you're using. I had some issues with jQuery AJAX calls in IE when using ASP.NET on the server side (a ashx handler). They went away when I read the request fully before starting to write the response (even though in my case I was using POST, not GET request, so the body of the request contained some data).
I wrote the following simple ASP.NET project to test your issue in IE6. However I'm unable to reproduce (IE6 SP2 running in virtual machine hitting IIS 7.5 shows the alert box from success handler properly). Could you try running it in your environment and reporting whether it works from IE6 for you?
Note: Sometimes when I cleared IE6 cache and commented out the "SetCacheability" line in ashx.cs, the first click on "Send" button would not show the success alert box, although subsequent clicks did show it. Maybe all you need is adding "no-cache" headers to the call response in your implementation?
file index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>AJAX GET test</title>
</head>
<body>
<input type="button" id="test" value="Send" />
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$("#test").click(function () {
$.ajax({
url: "Api.ashx?param=one",
cache: true,
type: "GET",
dataType: "json",
success: function (data) {
alert("Success, result = " + data.result);
},
error: function (request, status, err) {
alert("Error");
}
});
});
</script>
</body>
</html>
file Api.ashx
<%# WebHandler Language="C#" CodeBehind="Api.ashx.cs" Class="AjaxTest.Api" %>
file Api.ashx.cs
using System.Diagnostics;
using System.Text;
using System.Web;
namespace AjaxTest
{
public class Api : IHttpHandler
{
public bool IsReusable { get { return true; } }
public void ProcessRequest(HttpContext context)
{
var param = context.Request["param"]; // this flushes the request
Trace.WriteLine("Request: \"" + context.Request.RawUrl + "\", param: \"" + param + "\"", "** Debug");
context.Response.StatusCode = 200;
context.Response.ContentType = "application/json";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
context.Response.Write("{\"result\":\"" + param + "\"}");
}
}
}
What happens if you add a failure function, and alert out the responseText within there?
$.ajax({
type: "GET",
url: "my_url",
cache: true,
success: function(data) {
/* code here */
},
error: function(data) {
alert(data.responseText);
},
dataType: 'json'});
http://docs.jquery.com/Ajax/jQuery.ajax#options

Categories