$.ajax not able to receive JSON HTTP Response - javascript

I am in newbie in JavaScript, JQuery and Ajax coding.
I am using JQuery $.ajax method to invoke asyn REST call.
Somehow I am not able to receive HTTP response JSON data.
I can see the below alert result.
alert(data) method result is [Object Object]
alert(data.toSource()) method result is ({"key1","value1"})
alert($.parseJSON(data)) method result is nothing
I have tested the below code in both firefox and chrome browsers.
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"</script>
</head>
<body>
<form id="foo">
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Send" />
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
<script>
$("#foo").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "resources/helloWorld",
type: "GET",
dataType: 'json',
success: function(data){
alert(data);
alert(data.toSource());
var r = $.parseJSON(data);
alert(r);
$("#result").html(data);
},
error:function(){
$("#result").html('there is error while submit');
}
});
});
</script>
</body>

From your post:
alert(data) -> [Object Object]
Right, alert() uses the string representation of the argument, and data is an object.
alert(data.toSource()) -> ({"key1","value1"})
Right, toSource() is a Gecko method that works as JSON.stringify.
alert($.parseJSON(data)) method result is nothing
Right, you are trying to parse an object.
What you want to do is something like perhaps:
success: function(data){
$("#result").html(data.key1);
}

Related

jQuery Ajax - Wrong response

I have a problem with jQuery ajax function:
var arrayIdEq = JSON.stringify(iditem);
$.ajax({
type: "POST",
url: "index.php",
dataType : 'text',
contentType: 'application/json; charset=utf-8',
data: {
arrayIdEq : arrayIdEq
},
success: function(answer) {
alert(answer);
},
complete: function() {
},
error: function(jqXHR, errorText, errorThrown) {
alert(jqXHR+" - "+errorText+" - "+errorThrown);
}
});
"arrayIdEq" contains number from 0 to 7, or string "EMPTY".
PHP code:
elseif(isset($_POST['arrayIdEq'])){
$answer = "my_answer";
return $answer;
After request, when success response come, alert show up... but here's the problem. Instead of "$answer" value, alert contains... HTML code from my main page!
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title> Medivia</title>
</head>
<body>
<h1>Medivia</h1>
<form action="index.php" method="POST">
<label>E-mail:<br><input type="text" name="mail" required></label>
<br>
<label>Hasło:<br><input type="password" name="pass" required></label>
<br>
<button name="login">Zaloguj się</button>
</form>
</body>
</html>
I have no idea what happend here. Could anybody explain to me what happend there? What did i do wrong?
Your answer variable in the success function will contain the complete output of your php script.
So when you call index.php and you do:
elseif(isset($_POST['arrayIdEq'])){
$answer = "my_answer";
return $answer;
}
The script will only exit if the return statement is called from the main script (not from within a function) but the output will be the output generated by the script until that point.
Your script should output - and not return - only what you want returned to the javascript.
Probably a separate script for ajax requests will be a more convenient solution than using the index.php file you use to build the complete page.

how to print data sent by ajax post method in javascript

I need to post data and display it also. I am using ajax post method. I am able to get the event Id where data is saved, but not able to display the data. I searched a lot and got some answer also. I tried it in my code, but didn't got the result. My code is:
<!DOCTYPE html>
<html>
<head>
<title>POST API</title>
<script type="text/javascript" src="http://ajax.googleapis.com /ajax/libs /jquery/1.2.6/jquery.js"></script>
</head>
<body>
<button id="btn1">Check HTTP POST</button>
<p>Display sample output from POST API:</p>
<p id="one" />wEventId :
<p id="two" />
<script>
$(document).ready(function() {
$("#btn1").click(function() {
$.ajax({
url: 'url',
dataType: 'json',
type: 'POST',
crossDomain: true,
contentType: 'application/json',
data: {},
success: function(data) {
console.log(data);
document.getElementById("two").innerHTML = data.result.wEventId;
},
failure: function(errMsg) {
console.log(errMsg);
}
var myData = data;
myData = new Array;
});
});
});
</script>
</body>
</html>
Anyone please help me how to modify the code to print the data saved. I have not given the url as it is an internal server and supposed not to disclose it. Thanks in advance.
First I need to know, what is the structure of your json data.
Assuming that it is in a format like given below:
{"field_A":"value_a","field_b":"value_b"}
your code where you are trying to print as innerHTML should be like this:
success: function(data)
{
console.log(data);
document.getElementById("two").innerHTML = data.field_A;
},
Try to adjust accordingly.
I am still surprised from where are you getting the result of data.result.wEventId

how to handle json data in javascript

I am using worldweatheronline api to access weather data,when a request is send it response by sending data in json.I want to display the weather information in html page
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<input type="text" id="in"></input>
<input type="hidden" id="keys" value="apikey"></input>
<button id="go">Search</button>
<script>
$(document).ready(function(){
$("#go").click(function(){
var apikey = $("#keys").val();
var q = $("#in").val();
jQuery.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?key=' + apikey + '&q=' + q,
success: function(response){
var obj = JSON.parse(response);
console.log(obj);
},
});
});
});
</script>
</body>
</html>
<html>
<head>
<title>weather app</title>
</head>
<body>
<form method="GET" action="http://api.openweathermap.org/data/2.5/weather">
<input type="hidden" name="key" value="apikeyneeded"></input>
<input type="text" name="q"></input>
</form>
</body>
</html>
Check this.
var apikey = jQuery('[name="key"]').val();
var q= jQuery('[name="q"]').val();
jQuery.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?key=' + apikey + '&q=' + q,
success: function(response){
var obj = JSON.parse(response);
console.log(obj);
},
});
add this line into the head tag to include jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
You can't use the JSON.parse that way. At first you must make a request to that API, then get a response and finally use the parse JSON.parse(response)
if you are interested I can help you to manage this using jQuery to request the json.
Use ajax method to get the data from openweathermap api.
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?key=apikey&q=delhi",
dataType: "jsonp", //Handle ajax cross domain
success: function (response) {
//the response already parsed.
}
});

Can't get the json value by getjson from google map api

Can't get the json value by getjson from google map api
HTML
<html>
<head>
</head>
<body>
<input data-mini="true" data-theme="a" id="search" name="search" placeholder="Search for Restaurants" type="search">
<input data-inline="true" id="submit" onclick="getRestaurants()" type="submit" value="Go">
</body>
</html>
JS
function getRestaurants()
{
var search=$("#search").val();
var prestring="restaurant+in+";
var jsonRList="https://maps.googleapis.com/maps/api/place/textsearch/json?query="+prestring+search+"&key=API_KEY";
var xmlRList="https://maps.googleapis.com/maps/api/place/textsearch/xml?query="+prestring+search+"&key=API_KEY";
alert(jsonRList);//working
//NOT working
$.getJSON(jsonRList, function (data) {
alert(data.results[0].name);//returns nothing
alert("hello2");//returns nothing
});
//working
var data = '{"name": "abc","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json.phoneNumber[0].number);
alert("hello3");//working
//NOT working
$.ajax({
url: 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=kolkata&key=API_KEY',
dataType: 'jsonp',
success: function(data){
alert(data);//returns nothing
alert("ajax");//returns nothing
}
});
alert("hello4");//working
//Not working
$(document).ready(function(){
$("submit").click(function(){
$.getJSON( jsonRList, function( data ) {
alert(data);//returns nothing
alert("hello5");//returns nothing
});
});
});
}
Inside $.getjson or $.ajax not executing anything.
Another approach that is not working
$("button").click(function() {
....
https://jsfiddle.net/sphakrrokr/r9xbctnr/
Two reasons I could identify for you not getting a response from Places API -
1) You are using data type JSONP instead of JSON while the API will return results in JSON format.
2) Even though you wish to use JSONP and not JSON, you did not implement a callback in order to parse results into JSONP.
For normal use case, I would recommend to use JSON over JSONP.
Check these resources for difference between the two:
Relevant question 1
Relevant question 2
Official docs

XML Parsing remote server

I have followed some tutorials on how to parse XML from remote websites and came across the wonderfully articulated question and answer in stackoverflow.
However even after following the question, following program is not working.
<!DOCTYPE html>
<html>
<head>
<title>Aviation</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.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).find("City").text();
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>
The website which I am trying to parse is same.
US FAA
Also I want to develop it as stand alone application i.e. Just HTML interacting with the remote website.
As mentioned, you can (need to) use jsonp because faa.gov apparently forgot to add the appropriate header to their API responses.
By the way - always prefer json over xml with Javascript - it's so much nicer to work with.
// ask faa.gov to add the HTTP header "Access-Control-Allow-Origin: *" to their response
// then you can use this
// jQuery.getJSON('http://services.faa.gov/airport/status/IAD?format=json');
jQuery.ajax({
url: 'http://services.faa.gov/airport/status/IAD?format=json',
dataType: 'jsonp',
success: function (data) {
document.myform.result1.value = data.city;
}
});

Categories