How to list results from JSON using Ajax - javascript

I have my first Ajax code and I am a little bit confused how to get all values from certain
<html>
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>My first Ajax</title>
</head>
<body>
<script type="text/javascript">
$(submit).click(function getResults() {
return $.ajax({
type: "GET",
url: "https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
success: function(msg) {
// success
},
Error: function(x, e) {
// On Error
}
});
});
}
</script>
<input id="submit" name="submit" type="submit" value="Submit">
</input>
</body>
</html>
url. Following papers I have made code down below, but it does nothing to be honest. I would like to know how can I list certain data from this url?

There's many things you need to change (most of them are reference here: http://api.jquery.com/jquery.ajax/):
Use a newer version of jquery:
http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js
JS snipper should come after the element, as there's no element defined when JS executed
$(submit) is invalid. It should be $('#submit') as valid selector.
use evt.preventDefault() to prevent default browser behavior
url: you can't make request on another domain unless that url has enabled CORS (cross origin resource sharing), otherwise the request will work only on the same domain as your page. See an option on how to test locally: Jquery .ajax() local testing
async: true -> that's default so you can ommit
dataType -> that's fine if you expect JSON from server
contentType -> that's fine, but you don't send anything to the server, so it's not really needed
error: starts with lower letter
Here' the code updated:
<html>
<head>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>My first Ajax</title>
</head>
<body>
<input id="submit" name="submit" type="submit" value="Submit">
<script type="text/javascript">
$("#submit").click(function(evt) {
evt.preventDefault();
$.ajax({
type: "GET",
url: "https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: "false",
success: function(msg) {
// success
},
error: function(x, e) {
// On Error
}
});
});
</script>
</body>
</html>

try this:
$('#submit').click(function() {
$.getJSON(url,function(data){
// Do whatever you need
});
});

First of all, your script should be defined after input tag. Also, make sure you have proper headers to access the url or it will give error related to Access-Control-Allow-Headers.

use loop for-in
$(submit).click(function getResults() {
return $.ajax({
type: "GET",
url:"https://www.cs.kent.ac.uk/people/staff/lb514/hygiene/hygiene.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "true",
cache: "false",
success: function (msg) {
for (var i in data){
// data[i].something, etc
}
},
Error: function (x, e) {
// On Error
}
});
});

Related

How is the scope different for ajax methods

I'm trying to call a JS method that uses ajax and jQuery from a .js file. I have the JS method defined in a .htm file, and I have access to some, but not all of the defined methods
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/script.js">
function testingAjax() {
$.ajax({
type: "GET",
url: 'IISHander1.cs/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success on all frontiers");
},
error: function (e) {
alert("Something Wrong.");
}
});
}
</script>
and I have another script right under that which defines:
function testingScope() { alert("in Scope");}
I've tested both and I can only call testingScope. The other results in a method not found error. Why is this?
A script tag can't have both an src and code text inside it. When the src exists the textual code will be ignored
Change to
<script>
function testingAjax() {
$.ajax({
type: "GET",
url: 'IISHander1.cs/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("success on all frontiers");
},
error: function(e) {
alert("Something Wrong.");
}
});
}
</script>
<!-- moved below so you can call testingAjax() in this script -->
<script type="text/javascript" src="js/script.js"></script>

Send a Json object to server with javascript function

I try to send a json object to a distant server, but I didnt receive success message. please what's wrong with this code:
function sendSMS(){
var input = '{"header":"****","****":*****,"****":"*****"}';
var url = "https://**********&username=*****&password=*******";
jQuery.ajax({
type: "POST",
crossDomain:true,
url: url,
data: JSON.stringify(input),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(){
alert("success");
}
});
}
// html code
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript" src="sendSMS.js"></script>
</head>
<body>
<button onclick="sendSMS()">sendSMS</button>
</body>
</html>
Any help please.
You have to simple change your ajax call to this:
function sendSMS(){
var input = '{"header":"Ooredoo","msisdn":21620117297,"SMS":"Hello"}';
var url = "https://**********&username=*****&password=*******";
jQuery.ajax({
type: "POST",
crossDomain:true,
url: url,
data: JSON.parse(input),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(){
alert("success");
}
});
}
The main changes are JSON.stringify to JSON.parse this will help you to parse the JSON data into a JSON object, and the second change is the actual payload in which you missed a " at the end, just after Hello.
If you have any other question, just ask :)
Also I would recommend not to send the username and password as querystring parameter, use a POST request with a proper payload and last, if you can go through ssl

Weather.asmx web service from JavaScript- No output returns

I call http://wsf.cdyne.com/WeatherWS/Weather.asmx web service from JavaScript. And I pass data ZIP code as 10007(Hard coded). Want to get some output data. But when I run the code success message come as alert and then alert pop up says none. Seems there is no data returned. Can anyone edit the code to return proper output?
<html>
<head>
<title>Calling Web Service from jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnCallWebService").click(function (event) {
$.ajax({
type: "POST",
url: "http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "10007",
success: processSuccess,
error: processError
});
});
});
function processSuccess(data, status, req) { alert('success');
if (status == "success")
$("#response").text($(req.responseXML).find("Result").text());
alert(req.responseXML);
}
function processError(data, status, req) {
alert('err'+data.state);
//alert(req.responseText + " " + status);
}
</script>
</head>
<body>
<h3>
Calling Web Services with jQuery/AJAX
</h3>
<input id="btnCallWebService" value="Call web service" type="button" />
<div id="response" ></div>
</body>
</html>
Did you enabled CORS
themessage i am getting when i tested in firebug is as below
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP. This can be fixed by moving the resource to the same domain or enabling CORS.
these links might help you
http://enable-cors.org/client.html
Firefox setting to enable cross domain ajax request
Try This
$.ajax({
url: "URL",
dataType: "json",
data: {term: request.term},
success: function(data) {
alert(data);
var dData = JSON.parse(data);
alert(dData.Name); //get your stuff
}
});

AJAX - Cross-domain don't work

I was reading many things about that the json is great replacement for XMLHttpRequests. I tried it and it don't works:
$.ajax({
crossDomain: true,
url: settingsURL,
type: "POST",
dataType: 'JSONP',
parseAsHtml: true, cli: 'help',
success: function(data) {
data=$(data).find('div#TestDivContent');
$('#TestDivContent').append(data);
},
error: function() {
$('#TestDivContent').append("<p>Can't Connect</p>");
}
});
and im getting...
Uncaught SyntaxError: Unexpected token <
Please Check the code below that is working like a charm in Cross Domain ().
if You Have control of both the Domains i.e., Domain1.com & Domain2.com
//Ajax Script in Domain1.com
//No Conflict is the code snippet from my sample code You can delete it if not required no issues
<script type="text/javascript">jq1102 = jQuery.noConflict( true );</script>
<script type="text/javascript" >
function jsonp(n){
//GET Response is Here
alert(n);
}
jq1102(function(){
jq1102.ajax({
type: "GET",
dataType: "jsonp",
url: 'http://domain2.com/ClientSiteApi/',
crossDomain: true,
complete: function(data){
//Any Action You Like to Trigger After Complete
},
error: function(jqXHR, textStatus, ex) {
//Nothing to Change Here
}
});
})
</script>
Response from Domain2.com
echo 'jsonp("hello")'; //You Can place JSON string in replace of the Hello String

Ajax request to JSON not working?

I am trying to get some data from an API that provides JSON responses. I am brand new to all this. Can someone look at my code and tell me if there is a syntax reason it won't work? I want to hit the button and have an alert pop up containing the data sent back from the request. I think this is the most basic programming thing you can do, and I cannot seem to get it to work.
<head>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'http://openapi.etsy.com/v2/teams/8787?api_key=********&fields=name',
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data)
{
alert(data)
}
})
</script>
</head>
<body>
<button onClick="$.ajax()">Run Code</button>
</body>
</html>
I rewrote your code:
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
function doStuff() {
$.ajax({
type: 'GET',
url: 'http://openapi.etsy.com/v2/teams/8787?api_key=********&fields=name',
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data)
{
alert(data)
}
});
}
</script>
</head>
<body>
<button onClick="doStuff()">Run Code</button>
</body>
</html>
Add an event handler unobtrusively with jQuery to button using an id.
<head>
</head>
<body>
<button id="button">Run Code</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$('#button').click(function(e){e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://openapi.etsy.com/v2/teams/8787?api_key=********&fields=name',
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data)
{
alert(data)
}
})
});
</script>
</body>
</html>
Yes, there are several problems:
You are using jQuery, but you are not loading it.
You try to invoke the call when the page loads.
The onclick event handler tries to invoke $.ajax() call incorrectly (it does not have any parameters).
This is probably all.

Categories

Resources