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>
Related
I have an AJAX call made with jQuery to a 500px API:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"/>
<script type="text/javascript">
$(document).ready(function(){
$('#myButton').click(function() {
$.ajax({
url: "https://api.500px.com/v1/photos?feature=editors&page=2&consumer_key=<your-consumer-key>",
dataType: 'jsonp',
type: 'GET',
success: function(result){
alert("success");
for(x in result.data){
$('#myHtmlList').append('<li><img src="'+result.data[x].image_url+'"></li>');
}
},
error: function(result){
alert("Error: "+result);
console.log(result);
}
});
});
});
</script>
The result of this code is the "Error" alert. If I copy and paste the same url in browser it works and returns the json with the images. I don't understand why the javascript call doesn't work.
I also don't understand why if I make the same code call to an Instagram API, for example:
url: 'https://api.instagram.com/v1/users/' + userId + '/media/recent'
dataType: 'jsonp',
type: 'GET',
data: {access_token: <your-access-token>},
it works.
When I am calling server method from AJAX call at that time showing 500 internal server error. And this error also happens sometimes only, while sometimes it is working fine.
I am really confused that what is going on that it is sometimes working and sometimes not working. In fact I didn't change anything after working the code but when I check second day it is coming this type of error.
Here is my code
<input type="button" id="btn_save" value="Save" class="button" />
$(document).on("click", "#btn_save", function (e) {
$.ajax({
type: "POST",
url: "schoolregistration.aspx/EntrySave",
data: JSON.stringify({ schoolName: $('#txt_schoolname').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function () {
document.getElementById("txt_schoolname").value = "";
alert("Error! Try again...");
}
});
});
function OnSuccess(response) {
document.getElementById("txt_schoolname").value = "";
alert(response.d);
}
[WebMethod]
public static string EntrySave(string schoolName)
{
//Here is the code
}
Sometimes working fine but sometimes not coming call in this entrysave method.
try this:
$.ajax({
type: "POST",
url: "schoolregistration.aspx/EntrySave",
data: { "schoolName": $('#txt_schoolname').val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function (data) {alert('ok');},
error: function () {alert('error');}
});
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
}
});
});
I am trying to get user information by using twitter api. The jquery code is below :
<script type="text/javascript">
function GetUser() {
$.ajax({
type: "GET",
url: "http://api.twitter.com/1/users/show.json?user_id=id&include_entities=true&callback=?",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
cache:true,
timeout:8000,
success: function (json) {
alert("Successfull");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
}
});
}
</script>
xhr.responseText:undefined
thrownError:[object Error]
And html code :
<input type="submit" value="Submit" onclick="GetUser();" />
First your URL is not correct. Instead of
user_id=id
in your URL you have to use a actual value for id (id is just placeholder in your case). For example:
user_id=82193320
which would give you the data for my twitter user (uwe_guenther) back.
You can easily lookup twitter ids here:
http://mytwitterid.com/
If you just want to lookup user data by screen name you could use:
screen_name=uwe_guenther
instead.
The Twitter API description can you find here:
https://dev.twitter.com/docs/api/1/get/users/show
I have attached a working example for looking up screen_name by user_id and user_id by screen_name here:
The jsFiddle with the following example can be found here: http://jsfiddle.net/uwe_guenther/EvJBu/
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<input id='userIdTextField' type='text' placeholder='user_id'/>
<input id='userIdSubmitButton' type="submit" value="Submit"/>
<div id='screenNameResultView'></div>
<br>
<input id='screenNameTextField' type='text' placeholder='screen_name'/>
<input id='screenNameSubmitButton' type="submit" value="Submit"/>
<div id='userIdResultView'></div>
<br>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src='main.js'></script>
</body>
</html>
main.js
$(document).ready(function (){
$('#userIdSubmitButton').click(function (){
var userId = $('#userIdTextField').val();
$.ajax({
type: "GET",
url: "http://api.twitter.com/1/users/show.json?user_id=" + userId + "&include_entities=true&callback=?",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
cache:true,
timeout:1000,
success: function (json) {
alert("Successfull: screen_name=" + json.screen_name);
$('#screenNameResultView').text("screen_name=" + json.screen_name);
console.log(json);
},
error: function () {
alert("No Result");
}
});
});
$('#screenNameSubmitButton').click(function (){
var screenName = $('#screenNameTextField').val();
$.ajax({
type: "GET",
url: "http://api.twitter.com/1/users/show.json?screen_name=" + screenName + "&include_entities=true&callback=?",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
cache:true,
timeout:1000,
success: function (json) {
alert("Successfull: user_id=" + json.id);
$('#userIdResultView').text("user_id=" + json.id);
console.log(json);
},
error: function () {
alert("No Result");
}
});
});
});
Your Url is wrong
<script type="text/javascript">
function GetUser() {
$.ajax({
type: "GET",
url: "http://api.twitter.com/1/users/show.json?user_id=id&include_entities=true&callback=?",//this is wrong
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
cache:true,
timeout:8000,
success: function (json) {
alert("Successfull");
},
error: function () {
alert("cant search");
}
});
}
</script>
Here is a workin example http://jsfiddle.net/kMgES/
$.ajax({
url: 'http://api.twitter.com/1/users/lookup.json?screen_name=noradio&callback=?',
type: 'GET',
dataType: 'json',
timeout: 8000,
success: function (data) {
alert(data[0].name);
},
error: function () {
alert("cant search");
}
});
In this example the search is done by screen name. Take a look at https://dev.twitter.com/docs/api/1/get/users/show for all possible options.
Consider using this for error handdling
error: function(XMLHttpRequest, textStatus, errorThrown){
// error handling
}
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.