how to handle json data in javascript - 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.
}
});

Related

How to solve Error 400 on html page post method

I have make a simple html file to get my data and add button to post data but however i am returning error 400
My get method are running fine with displaying the backend data out in the html but however post method i am returning some errors 400 due to my query which i not sure why is there any way i can prevent this error 400 ?
<!DOCTYPE html>
<html>
<head>
<title>Add recycables</title>
<!-- Stylesheet -->
<link rel="stylesheet" href="/">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id = "add"></div>
<P>Add recycables</P>
<p>name: <input type="text" id="name"></p>
<p>type:<input type="text" id="type"> </p>
<button id="add">Add</button>
</body>
<script>
$(document).ready(function(){
var $items = $('#add');
var $name = $('#name');
var $type = $('#type');
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/get",
method:"GET",
// In this case, we are going to use headers as
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:"RecyclableGet(0)",
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, item, xhr,textStatus) {
//console.log(data)
$.each(data, function(i, item){
$items.append('<li>name: '+item.Name +', type: '+ item.RecyclableType + '</li>');
});
},
error:function(xhr,textStatus,err) {
console.log(err);
}
});
$('#add').on('click', function(){
var addRecyclables = {
Name: $name.val,
RecyclableType: $type.val
}
})
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/post",
method:"POST",
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:`RecyclableAdd('${name}','${type}')`,
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, Newitem, xhr,textStatus){
$items.append('<li>name: '+Newitem.Name +', type: '+ Newitem.RecyclableType + '</li>');
},
error:function(xhr,textStatus,err) {
console.log(err);
}
})
})
</script>
</html>
Json file look like
my html on web

How do you make the response of an HTML form update the text on a page?

I have a form in HTML as follows. I am trying to make it so the response (a string) of this POST becomes the text with id="answer".
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"> </script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script src="form.js"></script>
</head>
<body>
<form id="myForm"
action="http://myserver.com/post-destination/"
method="post">
<p><label>Input: <br><textarea name="formInput"></textarea></label></p>
<p><input type="submit" value="Submit" /></p>
</form>
<p id="answer">?</p>
</body>
I am attempting to use the jQuery Form plugin in a file called form.js, which consists of:
$(document).ready(function() {
$('#myForm')
.ajaxForm({
target: "#answer"
});
});
What am I doing wrong here? I'm sure it's just something really dumb, and I know there are a lot of questions about HTML forms and jQuery, yet following them is proving unsuccessful. I just can't figure this out whatsoever as it's my first time attempting anything web-related. Thanks for the help!
You jQuery ajax calls appears to be incorrect. You can refactor it as below:
$(document).ready(function() {
$('#myForm').submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
// set the target data
console.log ('set the target data');
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
console.log ('server responded something else ...');
}
});
});
});
You could try this:
<head>
<script>
function text() {
var answer = document.getElementById("input").value;
document.getElementById("answer").innerHTML = answer;
}
</script>
</head>
<body>
<form id="myForm" action="http://myserver.com/post-destination/" method="post">
<p><label>Input: <br><textarea id="input" name="formInput"></textarea></label></p>
<p><input onClick="text()" type="submit" value="Submit" /></p>
</form>
<p id="answer">?</p>
</body>

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

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;
}
});

jquery post php send form data

I'm trying to send variables from 2 form elements to another PHP script, through jquery.
Not sure what I'm doing wrong, just can't get the variables sent to the other PHP script.
Tried with jquery serialize as well, didn't get that to work either.
Tried with serialize() command as well.
Any suggestions more than welcome.
Thanks!
When putting the data in url manually, the return is correct. Then in data I have +page, as:
$.ajax
({
type: "GET",
url: "agent_talktime_pag.load.php?txtDate=2007-03-04&zone=Hongkong",
data: "page="+page,
success: function(msg)
If I use " var datastring = $('#idForm').serialize(); " the return doesn't work.
The variables get passed in the url, but the issue seems that the page="+page isn't passed. Which makes the load script not work. I tried to add a hidden field in the form like:
<input type="hidden" name="page" value="+page">
But, seems it's not passed as expected by the load script. The +page becomes just a string, think in the $.ajax it functions as a counter?
Any ideas?
$(document).ready(function(){
$("#driver").click(function(){
var datastring = $('#testform').serialize();
function loading_show(){
$('#loading').html("<img src='../images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax
({
type: "GET",
url: "agent_talktime_pag.load.php?txtDate=2007-03-04&zone=Hongkong",
data: "page="+page,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
$(document).ready(function(){
$("#driver").click(function(){
var txtDate=$("#txtDate").val();
var zone=$("#zone").val();
var dataString = 'txtDate='+ txtDate + '&zone='zone;
});
function loading_show(){
$('#loading').html("<img src='../images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax ({
type: "GET",
url: "agent_talktime_pag.load.php",
data: dataString,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This is a pagination script using Jquery, Ajax and PHP
The enhancements done in this script pagination with first,last, previous, next buttons -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Pagination with Jquery, Ajax, PHP</title>
<script type="text/javascript" src="jquery/external/jquery/jquery.js"></script>
<script type="text/javascript" src="jquery/jquery-ui.min.js"></script>
<link rel="stylesheet" href="includes/jquery/jquery-ui.css">
<link type="text/css" rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div align="center" style="font-size:24px;color:#cc0000;font-weight:bold">Pagination with jquery, Ajax and PHP</div>
<form id="testform">
<input type="text" name="txtDate" id="txtDate">
<select id="zone" name="zone">
<option value="Hongkong">Hongkong</option>
<option value="EST">EST</option>
</select>
<input type="button" id="driver" name="submit" value="Search"/>
</form>
<div id="loading"></div>
<div id="container">
<div class="data"></div>
<div class="pagination"></div>
</div>
</body>
</html>
To send data you have to do as follows:
Error code:
var datastring = 'txtDate =' + txtDate + '& zone =' zone;
Code:
//Manual code
var datastring = {"name field" txtDate, "fieldname": zone} // zone = field values
otherwise:
var datastring = $('#idForm').serialize();
Code ajax:
$.ajax({
data: datastring, //date form
url: 'url',
type: 'get', //type
dataType: "html",
beforeSend: function () {
//code load
},
success: function (response)
{
//code
}
});
You shouldn't be posting data in the url as params. You should use data to map out your data fields that you're going to be sending:
type: "method",
data: {field1: field1, field2: field2}

Categories