I am using the IMDb API v2.0 located here and I decided to test it. I can't. I think it's beacuse of cross-browser AJAX request from external sites.. but I don't know any other way. For example, here's a test at imdbapi avatar
See? Here's my code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>IMDB api</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#movie').keyup(function() {
var yourMovie = $("#movie").val();
$("#debug").append("You are searching for ... "+yourMovie+"\n");
dataString = "t=Avatar";
$.ajax({
type: "GET",
url: "http://www.imdbapi.com/",
cache: false,
data: dataString,
success: function(html){
//$("#more").after(html);
alert("Success!");
}
});
});
});
</script>
</head>
<body>
<form action="#" method="get" enctype="text/html" >
<input type="text" id="movie" maxlength="50" />
</form>
<div id="other">
Trigger the handler
</div>
<br />
<textarea id="debug" style="width: 500px;height:150px;border:1px solid black;font-face:typewriter;"></textarea><br />
<textarea id="more" style="width: 500px;height:150px;border:1px solid red;font-face:typewriter;"></textarea>
</body>
</html>
I am using Google Chrome.
Here's what worked for me:
<script type="text/javascript">
$(document).ready(function()
{
$('#movie').keyup(function() {
var yourMovie = $("#movie").val();
$("#debug").append("You are searching for ... "+yourMovie+"\n");
dataString = "callback=?&t=Avatar";
$.getJSON('http://www.imdbapi.com/', dataString, function(html){
//$("#more").after(html);
alert("Success!");
});
});
});
</script>
Replace:
$.ajax({
type: "GET",
url: "http://www.imdbapi.com/",
cache: false,
data: dataString,
success: function(html){
//$("#more").after(html);
alert("Success!");
}
});
With
$.getJSON('http://www.imdbapi.com/?' + dataString, function(json_data){
alert(JSON.stringify(json_data));
});
It is a cross domain AJAX call, therefore you need a callback. jQuery makes this really easy, just add ?callback=? to your url.
url: "http://www.imdbapi.com/?" + dataString + "&callback=?"
Skip the data = dataString in this case, makes it easier (I find).
Try this, and continue on it further:
$.getJSON("http://www.imdbapi.com/?" + dataString + "&callback=?").success(function(data){
console.log(data); // will contain all data (and display it in console)
})
This is the same as:
$.ajax({
type: "GET",
url: "http://www.imdbapi.com/?"+dataString+"&callback=?",
dataType: 'JSONP'
success: function(data){
console.log(data);
}
You can run cross domain Ajax with jQuery. Set the crossDomain option at the call site:
http://api.jquery.com/jQuery.ajax/
crossDomain(added 1.5)Boolean Default: false for same-domain requests,
true for cross-domain requests If you wish to force a crossDomain
request (such as JSONP) on the same domain, set the value of
crossDomain to true
Edit-
Actually, what exactly is your problem? I tried this and it returns Json properly.
http://jsfiddle.net/7VcUJ/
Response example:
HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Content-Type:
text/html; charset=utf-8 Expires: -1 Server: Microsoft-IIS/7.0
X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Mon, 02 Apr
2012 22:28:14 GMT Content-Length: 618
{"Title":"Avatar","Year":"2009","Rated":"PG-13","Released":"18 Dec
2009","Genre":"Action, Adventure, Fantasy, Sci-Fi","Director":"James
Cameron","Writer":"James Cameron","Actors":"Sam Worthington, Zoe
Saldana, Sigourney Weaver, Michelle Rodriguez","Plot":"A paraplegic
marine dispatched to the moon Pandora on a unique mission becomes torn
between following his orders and protecting the world he feels is his
home.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw##._V1_SX320.jpg","Runtime":"2
hrs 42
mins","Rating":"8.1","Votes":"386930","ID":"tt0499549","Response":"True"}
Add a callback parameter to the URL to use JSONP:
dataString = "t=Avatar&callback=?";
Using a $ will cause jQuery to auto-generate a callback function for you and handle the response automatically.
Recommended reading: What is JSONP all about?
Related
I'm trying to run an AJAX Webservice request on a VB ASP.NET page.
When the page loads, I'm trying to call the webservice but I get a 500 error in the console.
My WebService file looks like this:
<System.Web.Script.Services.ScriptService()>
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")>
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
<ToolboxItem(False)>
Public Class usrDataSave
Inherits System.Web.Services.WebService
<WebMethod()>
Public Function saydata(abc As String)
MsgBox(abc)
Return abc
End Function
My ASP.NET page looks like this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "usrDataSave.asmx/saydata",
data: "hello_world",
contentType: "application/json",
datatype: "json",
success: function(responseFromServer) {
alert(responseFromServer.d)
}
});
});
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
I expect the page to load and a message box to popup server side that says 'hello_world' as well as the web browser to create a popup that says the same. However, this does not happen as I get a 500 error instead.
I've tried to fix this by using different versions of jQuery as well as enabling requests in the web.config file like this:
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
This doesn't work and I still get that "the server responded with a status of 500" in the web browser console. No errors are logged within the application's debug console.
How can I fix this?
Ok, assuming both pages are in the SAME folder - at the same level?
Then this should work:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: usrDataSave.asmx/saydata
data: "{abc: 'hello_world'}",
contentType: "application/json",
datatype: "json",
success: function (responseFromServer) {
alert(responseFromServer.d)
}
});
});
</script>
Note how your data has to match your parmaters..
So, say you have this:
<WebMethod()>
Public Function saydata(abc As String, def as string) as string
MsgBox(abc)
Return abc & " " & def
End Function
And note how we set the function as string - you should give the function a type - in this case "string".
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "WebService1.asmx/saydata",
data: "{abc: 'hello', def: 'world'}",
contentType: "application/json",
datatype: "json",
success: function (responseFromServer) {
alert(responseFromServer.d)
}
});
});
</script>
Edit:
Follow up question was how to return more then one value?
Well, the easy way? Create a structure or class - let the built in serialization convert that to a json string for you.
So our web method could say be this:
Structure Hotel
Dim FirstName As String
Dim LastName As String
Dim HotelName As String
End Structure
<WebMethod()>
Public Function GetHotel() As Hotel
Dim MyHotel As New Hotel
MyHotel.FirstName = "Albert"
MyHotel.LastName = "Kallal"
MyHotel.HotelName = "Banff Springs Hotel"
Return MyHotel
End Function
I often use a struct in place of a class - since then I just shove it in right before my web method as per above.
Now, lets drop in a button on the page - and js function to call this:
eg:
<asp:Button ID="cmdHotel" runat="server" Text="Get Hotel"
OnClientClick="GetHotel();return false;" />
<script>
function GetHotel() {
$.ajax({
type: "POST",
url: "WebService1.asmx/GetHotel",
data: "{}",
contentType: "application/json",
datatype: "json",
success: function (r) {
s = "FirstName = " + r.d.FirstName + "\n"
s = s + "LastName = " + r.d.LastName + "\n"
s = s + "Hotel Name = " + r.d.HotelName
alert(s)
}
});
}
And when we run, we get/see this:
So, you can often just return a simple string. But, if you create a structure server side, then you can quite much reference the result client side as a js object as per above.
I am making a simple chrome application that calls my REST API to retrieve some basic user information in the JSON format. I have the below which in chrome developer tab preview shows to be working, connecting and retrieving what ever I put in my request.
My question is how do I go about dynamically showing on my html page what ever is retrieved?
Ideally I what to just show certain fields only from my response. I.e. just the Name, Location, Contact number as variables I can use throughout my page.
Any pointers would be great. Thanks
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Connect to API</title>
<style>
img {
height: 100px;
float: left;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
var authorizationToken = "xxxxxxxxxxxxxx";
function myapiRequest(endpoint, method, options) {
$.ajax($.extend({}, {
type: method,
dataType: "json",
success: function(json) {
items = json;
},
url: "https://api.myapi.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.myapi+json;version=2"
}
},
options));
}
myapiRequest('/users/0H5G?include%5B%5D=contact_methods&include%5B%5D=teams'); // this will be a variable soon
</script>
</body>
</html>
Response 200 OK
{"user":{"name":"john smith Jsmith","email":"john smith #xxxxxxx.com","time_zone":"Asia/Hong Kong","phone":"0123456",}}
$.ajax({
type: 'GET',
url: 'https://jsonplaceholder.typicode.com/posts/1',
success: function(response) {
// if your response is in JSON format, you can access response keys
// in the following format (both ways give same result)
var title = response.title; // OR var title = response['userId']);
// ...and then append to the DOM (your HTML) by selecting the
// element you want to append to, and using the append method
$('div.append-to-me').append(title);
},
error: function(error) {
console.log('not implemented');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="append-to-me"></div>
Hello there I am totally new to ASP.NET and learning it to my own. I am good at Java J2EE (Struts2 Framework)! I know how can i update or change any control/text inside any div element using struts2 and ajax code.
My Problem
Actaully, I'm trying to do the same thing in ASP.NET just for the learning! Suppose that I have a Default.aspx page with the javascript and ajax methods as:
<head runat="server">
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript">
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "text/html;charset=utf-8",
success: function(msg) {
$("#changer").html(msg);
}
});
}
</script>
<title>Untitled Page</title>
</head>
<body>
<div id="changer">//this is the div i want to update it using ajax
Hello Old Text
</div>
<input type="button"id="but" value="Hello Changer" onclick="Change()"/>
</body>
and suppose that I have my temp.aspx as:
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<div id="changer">
Hello New Text
</div>
</body>
I just want to know if this is possible in ASP.NET because with Java I am familiar with such an operation but I don't know why this is not working in case of ASP.NET!
Any hints or clues are favorable for me, Please don't mind for my question because I am totally new to ASP.NET but I am good at Java
Thanks in Advance!
dataType must define as html like this;
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "html",
success: function(msg) {
$("#changer").html(msg);
}
});
}
From jQuery Docs;
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
Additionally, you can inspect errors using error.
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "html",
success: function(msg) {
$("#changer").html(msg);
},
error: function(xhr, status, err) {
console.error(status, err.toString());
}
});
}
This is not related to ASP.NET or other web frameworks. It is just related to jQuery and Javascript. jQuery didn't recognise this "text/html;charset=utf-8". If you didn't use dataType, the ajax request worked successfully. It is just verification and result is interpreted according to dataType. For example, you are returning a JSON and the mime type of the your endpoint is not json (considering its mime type is html) just changing of the dataType as "JSON" you can parse the result as object.
I wrote a little script, in first example, I set dataType as HTML and in other example, I set dataType as JSON.
You could add a generec handler called Temp.ashx wich return the new text.
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello New Text");
}
In your ajax call you need to specify you are expecting a text.
<script type="text/javascript">
function Change() {
$.ajax({
type: "GET",
url: "temp.ashx",
dataType: "text/plain",
success: function(msg) {
$("#changer").html(msg);
}
});
}
</script>
I was reading several posts about this, and make some changes to my code but no luck.
Can anyone look into this, to see what's going on here? Or perhaps another way to do what I need (retrieve city, state by a zip code using ziptastic)
The code works fine in Chrome (http://jsfiddle.net/7VtHc/117/)
html
<asp:TextBox ID="txtZipCode" runat="server"></asp:TextBox>
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
<asp:TextBox ID="txtState" runat="server"></asp:TextBox>
script
<script src="http://code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("input[id$='txtZipCode']").keyup(function () {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.getziptastic.com/v2/US/" + el.val(),
cache: false,
dataType: "json",
type: "GET",
success: function (result, success) {
$("input[id$='txtCity']").val(result.city);
$("input[id$='txtState']").val(result.state);
}
});
}
});
});
</script>
Thanks,
Actual issue in your code is showing "No Transport" error in ajax error call back. add this line jQuery.support.cors = true; would solve your problem
Try this below code in IE and other browser.
<html>
<head>
<script type='text/javascript' src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function() {
jQuery.support.cors = true;
$("#zip").keyup(function() {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.getziptastic.com/v2/US/" + el.val(),
cache: false,
dataType: "json",
type: "GET",
success: function(result, success) {
$("#city").val(result.city);
$("#state").val(result.state);
}
});
}
});
});
</script>
</head>
<body>
<p>Zip Code: <input type="text" id="zip" /></p>
<p>City: <input type="text" id="city" /></p>
<p>State: <input type="text" id="state" /></p>
</body>
</html>
Check out these links:
CORS
No Transport error
The issue is IE8 doesn't support the Cross Origin Resource Sharing (CORS) XHR, so you can't do a cross domain ajax call with the native XHR or jQuery's $.ajax.
For IE8, Microsoft decided to come up with their own cross domain XHR instead of using the CORS XHR, which is called XDomainRequest, so you'll have to implement that to support IE8 users. An example usage can be found in this answer.
Alternatively, you could proxy the cross domain request through your local server side, making the external request a server to server situation, which won't be subject to Same Origin Policy.
Your request look fine but if it's a IE8 then you probably have a problem with header of file that you are loading, it have to be application/json
PHP example
header('Content-Type: application/json');
Very simple, add the following line on your page:
<meta http-equiv="X-UA-Compatible" content="IE=edge;chrome=1" />
Just trying to learn using ajax with appengine,started with the post method,but it does not work.
This is my HTML Code for the page
<html>
<head>
<title> Hello </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var data={"name":"Hola"};
$(document).ready(function(){
$('#subbut').click(function(){
$.ajax({
url: '/test',
type: 'POST',
data: data,
success: function(data,status){
alert("Data" + data +"status"+status);
}
});
});
});
</script>
</head>
<body>
<form method="post" action="/test">
<input type="submit" id="subbut">
</form>
<div id="success"> </div>
</body>
</html>
Here goes my python code to render the above html code , its handler is /test1
from main import *
class TestH1(Handler):
def get(self):
self.render('tester.html')
And this is the python script to which AJAX request must be sent to,handler is /test.
from main import *
import json
class TestH(Handler):
def post(self):
t=self.request.get('name')
output={'name':t+" duck"}
output=json.dumps(output)
self.response.out.write(output)
Expected behavior is that when i click on submit button,i get an alert message saying "Hola duck" , get nothing instead.
Any help would be appreciated as i am just starting with AJAX and Jquery withGAE
At first, I suppose you should suppress default behavior of form submitting when you press submit button by adding "return false" to the .click function. But I suppose it would be better to use just
<input type="button" id="subbut">
instead (even without form).
Then you should add "dataType: 'json'" to your ajax call to tell jQuery what type of data you expect from server. Doing this you will be able to get response data by property names like "data.name". So:
var data={"name":"Hola"};
$(document).ready(function(){
$('#subbut').click(function(){
$.ajax({
url: '/test',
type: 'POST',
data: data,
dataType: 'json',
success: function(data,status){
alert(data.name);
alert("Data" + data +"status"+status);
}
});
return false;
});
});
and it would be better if you set appropriate content type header to your response:
response.headers = {'Content-Type': 'application/json; charset=utf-8'}
self.response.out.write(output)