Trying this but getting nothig
function getWeather() {
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'JSON',
success: function(data)
{
$('#jsonp-results').html(JSON.stringify(data));
},
error: function(e)
{
alert(e.message);
}
});
return data; //The JSON response whould be in this so that I can take this and can do some operation
}
On clicking button it should return the JSON
<body>
<button onclick="getWeather();">Get Weather</button>
</body>
Expected example JSON:
{"coord":{"lon":-0.13,"lat":51.51},"sys":{"type":1,"id":5168,"message":0.0287,"country":"GB","sunrise":1415603442,"sunset":1415636293},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"base":"cmc stations","main":{"temp":284.99,"pressure":1003,"humidity":76,"temp_min":283.75,"temp_max":286.15},"wind":{"speed":5.1,"deg":210},"clouds":{"all":75},"dt":1415624678,"id":2643743,"name":"London","cod":200}
I am not getting the mistake I have done.
EDIT
Tried with this from snippets given here:
<!DOCTYPE html>
<html>
<body>
<p id="temp"></p>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script language="javascript" type="text/javascript">
function getWeather() {
data_Json = {};
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function(data) {
//alert(JSON.stringify(data));
data_Json = data;
//alert("Weather Report: "+data_Json);
},
error: function(e) {
alert(e.message);
}
});
return data_Json;
}
function temp() {
//getWeather();
var obj = JSON.stringify(getWeather());
//alert("Got"+JSON.stringify(obj));
//alert(JSON.stringify(getWeather()));
//document.getElementById("temp").innerHTML = obj.main.temp;
alert("Temp : "+obj);
}
</script>
</body>
<body>
<button onclick="getWeather();">Get Weather</button>
<button onclick="temp();">Temperature</button>
</body>
</html>
It returned {}
Not returned the JSON (the return defined in getWeather)
Not the temperature (in get element by id part)
Remove contentType from your request and it will work fine.
Since this is a cross origin request, you cannot set contentType.
Following is the error you will see in your console -
XMLHttpRequest cannot load http://api.openweathermap.org/data/2.5/weather?q=London. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
Also the statement return data; will fail as variable data is not available in that context.
You can use the below code for your purpose -
function getWeather() {
weatherJson = {};
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
dataType: 'JSON',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
weatherJson = data;
},
error: function(e) {
alert(e.message);
}
});
return weatherJson;
}
You can try this solution
function getWeather() {
data_Json = {};
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
dataType: 'JSONP',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
data_Json = data;
},
error: function(e) {
alert(e.message);
}
});
return data_Json; }
For Edit Part:-
<!DOCTYPE html>
<html>
<body>
<p id="temp"></p>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function getWeather() {
data_Json = {};
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function (data) {
data_Json = JSON.stringify(data);
},
error: function (e) {
alert(e.message);
}
});
alert(data_Json);
return data_Json;
}
function temp() {
var obj = getWeather();
alert("Temp : " +obj);
}
</script>
<button onclick="getWeather();">Get Weather</button>
<button onclick="temp();">Temperature</button>
</body>
Hi See this,
function getWeather() {
var returnData="";
$.ajax({
type: "GET",
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'JSON',
success: function(data)
{
$('#jsonp-results').html(JSON.stringify(data));
returnData=data;
},
error: function(e)
{
alert(e.message);
}
});
return data; //The JSON response whould be in this so that I can take this and can do some operation
}
Do you actually have an element with id="jsonp-results" in your html?
Some hints to simplify:
You don't need to specify a jsonp callback if you are not using jsonp
Synchronous calls are not nice because they block, you should avoid that and they aren't even supported for cross-domain calls (which your case is)
Simplified example:
function getWeather() {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?q=London",
dataType: 'JSON',
success: function(data) {
$('#jsonp-results').html(JSON.stringify(data));
},
error: function(e) {
alert(e.message);
}
});
}
<body>
<button onclick="getWeather();">Get Weather</button>
<div id="jsonp-results"></div>
</body>
After your comment: It certainly works:
http://codepen.io/anon/pen/MYgXzd
You must have something wrong in your setup.
Related
My JSON data is available in browser console. But i cannot display data in template.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '<?php echo_uri("clients/session_details") ?>',
type: 'GET',
dataType: 'json',
success: function(response) {
var data = JSON.parse(response);
$("#result").html(data[0].rx-byte);
}
});
});
</script>
Based on the JSON data you provided, it seems like you are trying to display the rx-byte value in the HTML template. Here's a code sample that will do that:
$(document).ready(function () {
$.ajax({
url: '<?php echo_uri("clients/session_details") ?>',
type: 'GET',
dataType: 'json',
success: function (response) {
$("#result").html(response[0]["rx-byte"]);
}
});
});
I have been hacking away at this for too long, as I'm painstakingly introducing ajax to speed my django app. I have no prior experience so. I have a dropdown list that I'm using as a notification viewer and using the {%for loop%} to populate. They all share the same id but unique names - their record ids. I'm trying to click the notification and then load the corresponding records by passing's it's ID to my views.py file. Below is code for my hackish attempt which has failed to be fruitful and taken way to much time.
<script>
function openNotification(){
$('#ntfy').click(function(e) {
var acc = $(this).attr('name');
$.ajax({
type: "GET",
url: "{% url 'my_app:notifications' %}",
dataType: "json",
async: true,
data:{csrfmiddlewaretoken :'{{ csrf_token }}',
'acc':acc},
success: function(){
alert("yo yoyo");
if (data.status == "success"){
window.location.href = data.url;
}
else{
alert("error occured");
}
}
});
});
}
</script>
And the html looks like this.
<a href="#" onclick="openNotification()" name="{{alert.1.docnum}}_{{alert.0.accountid}}" id="#ntfy">
Please assist.
<a href="#" data-docnum="{{alert.1.docnum}}" data-accountid="{{alert.0.accountid}}" class="ntfy">
===========================================
<script>
$('.ntfy').on('click',function(e) {
var docnum = $(this).attr('data-docnum'); // or $(this).data('docnum')
var accountid = $(this).attr('data-accountid'); // or $(this).data('accountid')
data = {
"csrfmiddlewaretoken":$("input[name='csrfmiddlewaretoken']").val(),
"docnum":docnum,
"accountid":accountid
}
$.ajax({
type: "GET",
url: "{% url 'rznbldbt_app:notifications' %}",
dataType: "json",
async: true,
data:data,
success: function(data){
alert("yo yoyo");
if (data.status == "success"){
window.location.href = data.url;
}
else{
alert("error occured");
}
}
});
});
</script>
Another way is :
<a href="#" onclick="openNotification({{alert.1.docnum}},{{alert.0.accountid}});">
===========================================
<script>
function openNotification(docnum,accountid)
{
data = {
"csrfmiddlewaretoken":$("input[name='csrfmiddlewaretoken']").val(),
"docnum":docnum,
"accountid":accountid
}
$.ajax({
type: "GET",
url: "{% url 'rznbldbt_app:notifications' %}",
dataType: "json",
async: true,
data:data,
success: function(data){
alert("yo yoyo");
if (data.status == "success"){
window.location.href = data.url;
}
else{
alert("error occured");
}
}
});
}
</script>
It won't go to a new browser tab, is my code wrong?
function getWaterMeterList() {
// alert("ON");
var BillingPeriod = $('#BillingPeriod').val();
$.ajax({
url: '/DataEntryWater/WaterMeterAlphaListReport',
type: 'POST',
data: { 'BillingPeriod': BillingPeriod },
dataType: 'json',
success: function (a) {
$(location).attr('href', a)
a.preventDefault();
},
error: function (err) {
}
});
}
What you're looking for might be:
window.open('http://stackoverflow.com/', '_blank');
And in your code:
function getWaterMeterList() {
// alert("ON");
var BillingPeriod = $('#BillingPeriod').val();
$.ajax({
url: '/DataEntryWater/WaterMeterAlphaListReport',
type: 'POST',
data: { 'BillingPeriod': BillingPeriod },
dataType: 'json',
success: function (a) {
var win = window.open('http://stackoverflow.com/', '_blank')
if(win) {
win.focus(); /if tab is open, change focus there.
}
},
error: function (err) {
// do stuff here
}
});
}
Please see the code below:
<script type="text/javascript" src="Javascript/json2.js"></script>
<script type="text/javascript" src="Javascript/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetData() {
$.ajax({
type: "POST",
url: "JSONExample.aspx/GetPerson",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(),
//async: false,
failure: function (response) {
alert('there was an error counting possibles')
}
});
function OnSuccess() {
return function (response) {
alert(response.d);
}
}
}
GetData()
</script>
I believe response.d returns the desterilized JSON. How do I see the JSON so that I can desterilize it myself into a .NET Object?
Try replacing this code with yours, If you have printed the array in json format on this URL JSONExample.aspx/GetPerson
If you have not printed the array in json then below code will not work.
<script type = "text/javascript">
function GetData() {
$.ajax({
type: "POST",
url: "JSONExample.aspx/GetPerson",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(response),
//async: false,
failure: function (response) {
alert('there was an error counting possibles')
}
});
function OnSuccess(response) {
return function (response) {
var data = JSON.parse(response);
console.log(data);
}
}
}
GetData()
</script>
You will be able to see the response in console of your developer tool.
Try with this:
<script type="text/javascript" src="Javascript/json2.js"></script>
<script type="text/javascript" src="Javascript/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetData() {
$.ajax({
type: "POST",
url: "JSONExample.aspx/GetPerson",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
//async: false,
failure: function (response) {
alert('there was an error counting possibles')
}
});
function OnSuccess(data) {
alert(data);
}
GetData()
</script>
Also, you can debug information with the developper tools of your Internet browser (F12 by default).
I get an with no description from ajax:
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'http://www.ouzhat.com/madad/api/adsapi',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
},
error: function (x,y,z) {
alert(x+'\n'+y+'\n'+z);
}
});
});
</script>
This is my webapp method code:
public JsonResult get() {
return new JsonResult() {
Data=ADS.SelectAll(),
JsonRequestBehavior=JsonRequestBehavior.AllowGet
};
}
It is cross domain issue (Please read on internet about it for further clarification).
if ajax and service file is on same domain then remove http://www.ouzhat.com from URl and provide local reference.
Another way is to add header [ header("Access-Control-Allow-Origin: *"); (example of PHP)] to your service file.