Ajax request to JSON not working? - javascript

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.

Related

Return resulting json from github API on html file

I have this html code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div id="result" style="color:red"></div>
</div>
</body>
<script>
$(document).ready(function(){
$.ajax({
url: "https://api.github.com/users/Microsoft",
type: 'GET',
dataType: 'json',
success: function(res) {
$('#result').html(res)
}
});
})
</script>
Whenever I try to see the result on my browser it just shows an empty blank page.
I just need to return the API result and show it on html.
Any ideas?
The AJAX callback makes res an object. When you using .html() the argument must be a string. If you want to see the object represented on the page, use JSON.stringify():
$.ajax({
url: "https://api.github.com/users/Microsoft",
type: 'GET',
dataType: 'json',
success: function(res) {
$('#result').html(JSON.stringify(res))
}
});

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>

How to list results from JSON using Ajax

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

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

FormData Object not submitting via jQuery AJAX call

I'm using this script to get all values from a form, in order to prepare it for an ajax request:
function saveDataAjax(){
var fd = new FormData();
var inputs = document.getElementsByTagName('input');
for(i=0;i<inputs.length;i++) {
fd.append(inputs[i].name, inputs[i].value);
}
$.ajax({
url: '/edit.php',
data: fd,
type: 'POST',
dataType: 'html',
success: function(data){
alert(data);
}
});
}
However I'm getting a Type error from jQuery, and if I alert fd['inputname'] I get undefined, so I guess I must be doing something wrong somewhere...
Firefox debuggers tells me this: NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: Illegal operation on WrappedNative prototype object # http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js:2
Add the following to the AJAX call:
processData: false,
contentType: false,
So it looks like:
$.ajax({
url: '/edit.php',
data: fd,
type: 'POST',
processData: false, //Add this
contentType: false, //Add this
dataType: 'html',
success: function(data){
alert(data);
}
});
This is probably not the reason, but just wanted to point it out: i is global here. The idea in JS is towards global abatement. Should probably be var i=...
this page help you ...:)
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous">
</script>
</head>
<body>
<form method="post" id="fileinfo" enctype="multipart/form-data">
file <input type="file" name="slug"><br>
<input type="button" id="uploadBTN" value="Stash the file!"></input>
</form>
<script type="text/javascript">
$(document).ready(function()
{
$('#uploadBTN').on('click', function()
{
var form = $('form').get(0);
console.log(form);
var fd = new FormData(form);
fd.append('user_id',4);
fd.append('user_media_category_id',1);
//console.log(fd);
fd.append("user_", "This is some extra data");
$.ajax({
url: 'http://localhost/yii2/azstudio/project/api/web/v1/user-media/new',
type: 'POST',
data: fd,
success:function(data){
console.log(data);
},
error:function(data){
console.log(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>
</body>
</html>

Categories

Resources