webservice jquery function - javascript

In below code I tries to read book details form A url, but it does not display the output.In output screen while clicking ajax button, it will not enter in to the $(data).find("Book").each(function(){});
My code html:
<html>
<head>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.js" type="text/javascript" charset="utf-8"></script>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
function bodyload() {
alert("We are calling jquery's ajax function and on success callback xml parsing are done");
$.ajax({
url: 'http://www.edumobile.org/blog/uploads/XML-parsing-data/Data.xml',
dataType: 'application/xml',
timeout: 10000,
type: 'GET',
success: function(data) {
alert("inside success function");
$("#bookInFo").html("");
$("#bookInFo").append("<hr>"); * * // my code work until here after that i will not receive any book details in my web page.**
$(data).find("Book").each(function() {
$("#bookInFo").append("<br> Name: " + $(this).find("name").text());
$("#bookInFo").append("<br> Address: " + $(this).find("address").text());
$("#bookInFo").append("<br> Country: " + $(this).find("country").text());
$("#bookInFo").append("<br><hr>");
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error status :" + textStatus);
alert("Error type :" + errorThrown);
alert("Error message :" + XMLHttpRequest.responseXML);
$("#bookInFo").append(XMLHttpRequest.responseXML);
}
});
}​
</script>
</head>
<body>
<center><button onclick="bodyload()">Ajax call</button></center>
<p id="bookInFo"></p>
</body>
</html>
Please tell me why am not getting output.

I think that data parameter of success function is a js object parsed from xml, not the html\dom. You can't apply $() to it. Try
for(var i = 0; i < data.length; i++) {var name = data[i].name; etc...}
or
for(var prop in data){var name = data[prop].name; etc...}

Related

ReferenceError: $ is not defined when making Ajax api call in asp.net razor page

I am making a simple Ajax call to api/news in asp.net razor page file. API is working fine as it show all data when i access access it https://localhost:44364/api/news
i keep getting ReferenceError: $ is not defined and debugger points to $(document).ready(function () { line of code.
I even use simplified version of ajax call which is also mentioned below but i keep getting the same error.
When i remove .ajax call or comment all ajax error goes away.
Not sure what exactly is this error pointing to
<script>
function loadNewsData() {
$.ajax({
type: "GET",
url: "/api/news",
dataType: "json",
success: function (result, status, xhr) {
var table = $("<table><tr><th>Details</th></tr>");
table.append("<tr><td>Title:</td><td>" + result["NewsHeading"] + "</td></tr>");
table.append("</table>");
$("#message").html(table);
},
error: function (xhr, status, error) {
alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
}
});
}
$(document).ready(function () {
loadNewsData();
});
</script>
<script type="text/javascript">
function loadNewsData() {
$.ajax({
url: "/api/news",
type: "GET",
dataType: "json",
success: function (data) {
console.log(data);
},
error: function (error) {
console.log('Error ${error}');
}
});
}
$(document).ready(function () {
loadNewsData();
});
</script>
$ is not a dom variable. It is a third party library called jquery. you must add
the below script before using $ object.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
for reference

Get request -> Error: SyntaxError: Unexpected token < in JSON at position 4

I am trying to call a code behind method in my ASP.NET web forms project.
jQuery ajax call
<script type="text/javascript">
$(document).ready(function () {
$('#MainContent_minuteBooks').click(function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "MainView.aspx/GetPageTypes",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (response) {
console.log("--" + JSON.stringify(response));
}
});
});
});
</script>
Code behind c# method
[WebMethod]
public string GetPageTypes()
{
List<string> pages = new List<string>();
string html = "";
foreach(MinuteBookPage mbp in book)
{
if (!pages.Contains(mbp.Class)) { pages.Add(mbp.Class); };
}
foreach(string s in pages)
{
html += "<div class='page' style='border: solid 2px red'><p>" + s + "</p></div>";
}
Console.WriteLine(html);
return html;
}
I keep getting the error callback on my ajax call displaying
Request: [object Object]
Status: parsererror
Error: SyntaxError: Unexpected token < in JSON at position 4
I've already tried changing the dataType to text/html, results in the same issue. I've worked with ajax calls a lot in NETCORE so i'm not sure why this isn't working

An ajax call to a .net web api method with a valid XML response has the responseXML as undefined

I have a .net web api method that when open in the browser it returns a valid XML (http://localhost:49546/api/Products)
<ArrayOfProductModel><ProductModel><Color>Black</Color><DiscontinuedDate i:nil="true"/><ListPrice>1431.5000</ListPrice><ModifiedDate>2008-03-11T10:01:36.827</ModifiedDate><Name>HL Road Frame - Black, 58</Name><ProductCategoryId>18</ProductCategoryId><ProductId>680</ProductId><ProductModelId>6</ProductModelId><ProductNumber>FR-R92B-58</ProductNumber><SellEndDate i:nil="true"/><SellStartDate>2002-06-01T00:00:00</SellStartDate><Size>58</Size><StandardCost>1059.3100</StandardCost><Weight>1016.04</Weight></ProductModel> </ArrayOfProductModel>
When I try to call that method using AJAX the data is being shown as an [object XMLDocument] but the data.responseXML is undefined so I can not process the XML response to show it as a table.
<script type="text/javascript">
$(document).ready(function () {
getProducts();
});
function getProducts()
{
$.ajax({
url: 'http://localhost:49546/api/Products',
method: 'GET',
dataType: 'xml',
//contentType: 'application/xml; charset=utf-8',
success: function (data) {
alert("GetProducts successfully");
showProducts(data);
},
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
})
}
function showProducts(data)
{
alert(data);
alert(data.responseXML);
alert(data.responseText);
var i;
var xmlDoc = data.responseXML;
var table = "<tr><th>Nombre</th><th>ListPrice</th></tr>";
var x = xmlDoc.getElementsByTagName("ProductModel");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("ListPrice")[0].childNodes[0].nodeValue +
"</td></tr>";
}
//alert(data);
document.getElementById("prodTable").innerHTML = table;
}
</script>
Please let me know what is missing or wrong
Web API passes back JSON as the default data type. That's what you're getting in {"location":null}
If you want to pass back XML, check out this article: WebAPI to Return XML

cannot post $('#myid').val() via ajax post method

I cannot send the value of input type email via ajax post.i obtain the input value by
var email = $('#myid').val()
which is somemail#gmail.com.I can successfully alert this value but cannnot post the value.when i remove '#' from email,it successfully posts the value..
please check my code below.
<script type="text/javascript">
function forgotfunction(){
var email=$('#forgetpass').val();
alert(email);
$.post("forgetpass.php",
{
email:email
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
$('#modalLink').trigger("click");
});
}
</script>
Try instead this way:
function forgotfunction(){
var email=$('#forgetpass').val();
alert(email);
$.ajax({
type: "POST",
url: "forgetpass.php",
data: { email: email },
error: function(){ alert('Could not post email'); }
});
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
$('#modalLink').trigger("click");
});
}

OpenWeather API - Pulling JSON data out

I'm writing a little JavaScript to pull information from JSON that contains name, longitude, latitude and openweather API call. What I need is to get the API information out of the API call into the HTML page so you can get the weather forecast for each information. I have the two elements working separately but can't work out how to get them working together.
Help please? :-)
Sample API Weather from d.weather
api.openweathermap.org/data/2.5/forecase?lat=50.8609&lon=-0.08014&&units=metric
HTML page for pulling the openweather JSON data
<html>
<head>
<title>Weather</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-1.7.min.js" ></script>
<script src="http://code.jquery.com/ui/1.7.0/jquery-ui.js" ></script>
<script>
function getWeather(callback) {
var weather = 'http://api.openweathermap.org/data/2.5/forecast?lat=51.5072&lon=0.1275&units=metric';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
// get data:
getWeather(function (data) {
console.log('weather data received');
console.log(data.list[0].weather[0].description);
console.log(data.list[0].weather[0].main);
});
getWeather(function (data) {
document.write('weather data received');
document.write('<br>');
document.write(data.list[0].weather[0].description);
document.write('<br>');
document.write(data.list[0].weather[0].main);
document.write('<br>');
document.write(data.list[0].main.temp);
document.write('<br>');
document.write(data.list[0].main[0].dt_txt);
document.write('<br>');
});
</script>
</body>
</html>
Html page for pulling the JSON data
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<!-- Javascript -->
<script type="text/javascript">
function loadUrl(newLocation){
window.location = newLocation;
return false;
}
</script>
<script type="text/javascript">
$(document).ready(function (){
$("#btn382").click(function(){
/* set no cache */
$.ajaxSetup({ cache: false });
$.getJSON("weather.json", function(data){
var html = [];
/* loop through array */
$.each(data, function(index, d){
html.push("Team : ", d.Teams, ", ",
"Long : ", d.Long, ", ",
"Lat : ", d.Lat, ", ",
"Weather : ", d.Weather, "<br>");
});
$("#div381").html(html.join('')).css("background-color", "orange");
}).error(function(jqXHR, textStatus, errorThrown){ /* assign handler */
/* alert(jqXHR.responseText) */
alert("error occurred!");
});
});
});
</script>
<!-- HTML -->
<a name="#ajax-getjson-example"></a>
<div id="example-section38">
<div>Football weather</div>
<div id="div381"></div>
<button id="btn382" type="button">Team location</button>
</div>
weather.json
{
"Teams":"Wycombe Wanderers",
"Long":-0.800299,
"Lat":51.6306,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=51.6306&lon=-0.800299&mode=html"
},
{
"Teams":"Livingston",
"Long":-3.52207,
"Lat":55.8864,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=55.8864&lon=-3.52207&mode=html"
},
{
"Teams":"Brighton and Hove Albion",
"Long":-0.08014,
"Lat":50.8609,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=50.8609&lon=-0.08014&mode=html"
},
I have the basics that should help you on your way. It's a mashup of your two pages.
First I amended your getWeather function to call for the weather rather than the forecast. It accepts a city parameter and appends that parameter to the data before the callback is called.
function getWeather(city, callback) {
var url = 'http://api.openweathermap.org/data/2.5/weather';
$.ajax({
dataType: "jsonp",
url: url,
jsonCallback: 'jsonp',
data: { q: city },
cache: false,
success: function (data) {
data.city = city;
callback(data);
}
});
}
Here, in lieu of your teams JSON I made one up in the form of a JS object, with Arsenal and Liverpool and their corresponding cities as the data. The function loops over the object, extracts the city name and passes it to getWeather. The data is returned and appended to the div.
$(document).ready(function () {
$("#btn382").click(function () {
var teams = {
arsenal: { city: 'london' },
liverpool: { city: 'liverpool' }
};
for (var team in teams) {
var city = teams[team].city;
getWeather(city, function(data) {
var html = [];
html.push('<div>')
html.push('City: ', data.city, ', ');
html.push('Lat: ', data.coord.lat, ', ');
html.push('Lon: ', data.coord.lon, ', ');
html.push('Weather: ', data.weather[0].description);
html.push('</div>')
$("#div381").append(html.join('')).css("background-color", "orange");
});
}
});
});
Hopefully this will give you a few ideas about how to tackle this project.
See it working here.
I have made a complete example. For me this worked:
HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<meta charset="utf-8">
<title>jQuery Ajax</title>
<link rel="stylesheet" href="css/ajx-json-styles.css">
<script>
function displayParsedData(data){
/* Working with the 'data' object (not string) here, now we can access the different properties available.*/
text = '<b>Name: </b>' + data.list[0].name + '<br/>';
text += '<b>message: </b>' + data.message + '<br/>';
text += '<b>Current Temperature: </b>' + data.list[0].main.temp + ' F<br/>';
text += '<b>Weather Conditions: </b>' + data.list[0].weather[0].description + '<br/>';
$('#parsed_json').append(text);
}
</script>
<script>
function test1() {
getWeather(function (data) {
$("#raw_json").html('<h2>callback</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>');
displayParsedData(data);
});
}
function getWeather(callback) {
var weather = 'http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258';
$.ajax({
dataType: "jsonp",
url: weather,
success: callback
});
}
</script>
<script>
function test2() {
$.ajax({
url: 'http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258',
type: 'GET',
dataType:"jsonp",
success: function(data) {
$("#raw_json").html('<h2>$.ajax</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>');
displayParsedData(data);
},
error: function(jqXHR, textStatus, error) {
alert( "error: " + jqXHR.responseText);
}
});
}
</script>
<script>
function test3() {
$.getJSON('http://openweathermap.org/data/2.1/find/city?lat=8.2924495&lon=-62.7373258&callback=?', function(data) {
$("#raw_json").html('<h2>getJSON</h2><pre>' + JSON.stringify(data, null, 2) + '</pre>');
displayParsedData(data);
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
});
}
/*$.getJSON('http://openweathermap.org/data/2.1/find/city?lat=13.3428&lon=-6.2661&cnt=10&callback=?', function(data) { console.log(data); });*/
</script>
<script>
$(document).ready(function (){
$("#btn382").click(function(){
/* set no cache */
$.ajaxSetup({ cache: false });
$.getJSON("weather.json", function(data){
for (var team in data) {
var html = [];
html = '<div class="item"><b>Team: </b>' + data[team].Teams + '<br/>';
html += '<b>Lat: </b>' +data[team].Lat + '<br/>';
html += '<b>Lon: </b>' + data[team].Lon + '<br/>';
html += '<b>Weather: </b>' + data[team].Weather + '<br/></div>';
$("#div381").append(html);
}
})
.error(function(jqXHR, textStatus, errorThrown){ /* assign handler */
/* alert(jqXHR.responseText) */
alert("error occurred!");
});
});
});
</script>
</head>
<body>
<div id="example-section38">
<div>Otra fuente</div>
<div id="div381"></div>
<button id="btn382" type="button">Team location</button>
</div>
<div id="raw_json"></div>
<div id="parsed_json"></div>
<button onclick="test1();">callback</button>
<button onclick="test2();">$.ajax</button>
<button onclick="test3();">getJSON</button>
</body>
</html>
weather.json
[
{
"Teams":"Wycombe Wanderers",
"Lon":-0.800299,
"Lat":51.6306,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=51.6306&lon=-0.800299&mode=html"
},
{
"Teams":"Livingston",
"Lon":-3.52207,
"Lat":55.8864,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=55.8864&lon=-3.52207&mode=html"
},
{
"Teams":"Brighton and Hove Albion",
"Lon":-0.08014,
"Lat":50.8609,
"Weather":" api.openweathermap.org/data/2.5/weather?lat=50.8609&lon=-0.08014&mode=html"
}
]
ajx-json-styles.css
#raw_json {
border:1px solid #333;
background-color:#ccc;
padding: 2em;
word-wrap: break-word;
margin-bottom: 2em;
width: 40%;
float: left;
}
#parsed_json {
padding:2em;
border: 1px solid blue;
width: 40%;
float: right;
}
h2 {
margin:0;
padding:0;
}
.item{
padding-bottom: 0.25em;
padding-top: 0.25em;
background-color: #E9BB18;
border: 1px solid white;
}
why don't you use xml instead of json it's easy to parse, i use it in my website weathercase , try api provider yr.no

Categories

Resources