Make cross-domain ajax JSONP request with jQuery - javascript

I would like to parse JSON array data with jquery ajax with the following 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">
<head>
<title>Sample</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var result;
function jsonparser1() {
$.ajax({
type: "GET",
url: "http://10.211.2.219:8080/SampleWebService/sample.do",
dataType: "jsonp",
success: function (xml) {
alert(xml.data[0].city);
result = xml.code;
document.myform.result1.value = result;
},
});
}
</script>
</head>
<body>
<p id="details"></p>
<form name="myform">
<input type="button" name="clickme" value="Click here to show the first name" onclick=jsonparser1() />
<input type="text" name="result1" readonly="true"/>
</form>
</body>
</html>
My JSON data is:
{"Data": [{"Address":"chetpet","FirstName":"arulmani","Id":1,"LastName":"sathish","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"ramaraj","Id":3,"LastName":"rajesh","City":"chennai"},{"Address":"ramapuram","FirstName":"yendran","Id":3,"LastName":"sathi","City":"chennai"}],"Code":true}
But i am not getting any output...anybody please help out...

Concept explained
Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.
This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Summary
Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.
If you have reqested with query string
?callback=my_callback_method
then, your server must response data wrapped like this:
my_callback_method({your json serialized data});

You need to use the ajax-cross-origin plugin:
http://www.ajax-cross-origin.com/
Just add the option crossOrigin: true
$.ajax({
crossOrigin: true,
url: url,
success: function(data) {
console.log(data);
}
});

Your JSON-data contains the property Data, but you're accessing data. It's case sensitive
function jsonparser1() {
$.ajax({
type: "GET",
url: "http://10.211.2.219:8080/SampleWebService/sample.do",
dataType: "json",
success: function (xml) {
alert(xml.Data[0].City);
result = xml.Code;
document.myform.result1.value = result;
},
});
}
EDIT Also City and Code is in the wrong case. (Thanks #Christopher Kenney)
EDIT2 It should also be json, and not jsonp (at least in this case)
UPDATE According to your latest comment, you should read this answer: https://stackoverflow.com/a/11736771/325836 by Abdul Munim

Try
alert(xml.Data[0].City)
Case sensitivly!

you need to parse your xml with jquery json parse...i.e
var parsed_json = $.parseJSON(xml);

alert(xml.data[0].city);
use xml.data["Data"][0].city instead

use open public proxy YQL, hosted by Yahoo. Handles XML and HTML
https://gist.github.com/rickdog/d66a03d1e1e5959aa9b68869807791d5

Related

i am new to ajax and jquery so i dont know what is wrong in my code

I am a beginner in coding and am learning ajax but my code is not working can anyone tell me what is wrong in my code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "demo.txt", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
this is demo.txt
<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
this is my console error
enter image description here
This is how your URL can use ajax, because Ajax has cross domain restrictions
If you are using vscode editor, you can download the "live server" plug-in and right-click in HTML to open the web page
Pls follow the documentation provided at
jQuery.ajax() | jQuery API Documentation
It should work fine when you include in the same order.
Little information about Ajax. Why do we use ajax, Ajax is mostly used for sending data from Javascript to the Back-end server. Lets say if you want to get the user input from front-end and you want to store the data in your database. Ajax comes to help.
Example of a simple ajax function with passing user data (namely data1 and data2):
$.ajax({
type: "post",
data: {
user_data1 : data1,
user_data2 : data2,
},
url: YOUR_FUNCTION_PATH,
success: function(data){
// After success passing data to YOUR_FUNCTION
// Handle what you do next
},
error: function (request, status, error) {
// Error of passing data to YOUR_FUNCTION
// Debug to see what is wrong
}
});
Then in your YOUR_FUNCTION and if you sending data to PHP function,
$user_data1 = $_POST['user_data1'];
$user_data2 = $_POST['user_data2'];
If you are using the old one, CodeIgniter, it is pretty simple to get the data.
$user_data1 = $this->input->post('user_data1');
$user_data2 = $this->input->post('user_data2');
Your URL may need to start with localhost, for example: http://localhost :8080

jQuery Knob and POST request from JavaScript

How to form a standard POST request with a parameter with JavaScript and jQuery Knob?
Here is what I got:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="jquery.knob.min.js"></script>
</head>
<body>
<input type="text" data-angleoffset=-125 data-anglearc=250 data-fgcolor="#66EE66" value="50" class="dial">
<script>
$(".dial").knob({
'release' : function (sendpostresp) {
$.ajax({
url: "publish.php", //the page containing php script
type: "POST", //request type
success: function (result) {
alert(result);
}
});
}
});
</script>
</body>
</html>
I need to save the value of the knob on release. The PHP part waits for the POST and saves the value to a database, and it works.
In my opinion, my code should send the current value of knob to the PHP script with POST. But I see no parameters in console, just an empty POST response.
Unfortunately, the official jQuery Knob docs don’t provide sufficient instructions. Please, help me with code examples, how to send the current value from the jQuery knob through POST?
You just need to add a data property to your ajax request. It could look like this:
$(".dial").knob({
'release' : function (sendpostresp) {
$.ajax({
url: "publish.php", //the page containing php script
type: "POST", //request type
data: {
foo: sendpostresp
},
success: function (result) {
alert(result);
}
});
}
});
According to Knob docs, the parameter in the 'release' callback function is the current value of the dial. Simply stick that into your data object on the ajax request and it will be sent to your server-side code that handles the request

How to display a json data from a existing url using ajax call

I Am new in working with json and jquery. I am trying to study the basics of json and jquery by working on some example. So I use existing json data in http://api.androidhive.info/contacts for my example. I want to display this data in my HTML page. My code is:
<html>
<head>
<title>jQuery Ajax Example with JSON Response</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked.");
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php
type: "GET",
dataType: 'json', // Choosing a JSON datatype
success: function (msg) {
alert("ajax worked.");
JsonpCallback(msg);
},
})
function JsonpCallback(json)
{
for (var i in json.contacts) {
$('#wines').append('contacts: ' + json.contacts[i] + '<br/>');
}
}
return false; // keeps the page from not refreshing
});
});
</script>
</head>
<body>
<form method="post" action="">
<button value="all" type="submit">Get!</button>
</form>
<div id="wines">
<!-- Javascript will print data in here when we have finished the page -->
</div>
</body>
</html>
can any one please give me some brief introduction to JSON and how it's working ?
Thanks in advance.
You are iterating the JSON wrong, in your case since you are using jQuery (as mentioned) you can use the $.each(json, callback); helper fron jQuery, you can see the documentation here Jquery $.each documentation
For an example implementation I've created this JSFIDDLE LINK
for you. Have a great day ahead. Don't forget that JSON means
Javascript Object Notation
It's an object.
$.each(jsonData.contacts, function(k, v)
{
console.log(v.name);
$('#name').append('<li>'+v.name+'</li>');
});
jQuery
Am try to study the basics of json and jquery
Is a Javascript library with lots of very usefull methods. If you want to create a dynamic website it is very recommended to look into jQuery. There are many site with great explanation on what jQuery can do. As far as your example is concerned: There is an issue when passing variables/data from one framework to another or even when simply storing data. Here comes JSON.
JSON
Or JavaScript Object Notation (JSON) is used to solve exactly that problem. What is basically does is take all the desired data (array, variable, object, string etc.) and writes it in a human readable and for other frameworks readable fashion. I use JSON to store data in files when no database is available or when passing data from one framework to another (like JS <-> PHP).
Your example code
What happens here:
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked."); // not yet
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php --> this I don't know
type: "GET", // communication type
dataType: 'json', // Choosing a JSON datatype
success: function (msg) { // here, the whole content of the url is read, idealy it is in JSON format ofc
alert("ajax worked."); // hoorray
JsonpCallback(msg);
},
})
There is the serverside.php file that receives a GET command and returns HTML. All the HTML content is in JSON type (so no <stuff>, i.e. no actual HTML) and your success function returns that content in the msg variable. Typically you use something like
var obj = JSON.parse(text);
to convert the JSON data to Javascript variables. Read this here JSON in Javascript
JSONP
Now what if you want to do some domain crossing (as you suggested), then I strongly recommend to read this here What is JSONP all about? . It explains what JSONP is all about

Jquery .ajax get request for a json response

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url:"http://bustime.mta.info/api/siri/vehicle-monitoring.json",
data: {key: '',
OperatorRef:'MTA%20NYCT',
LineRef:'B54',
VehicleRef:'9531' },
dataType: 'json',
async: false,
success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1">Let jQuery AJAX Change This Text</div>
<button>Get External Content</button>
</body>
</html>
Hi, I am new to Javascript & Jquery so please forgive me for any newbie mistake. What I am trying to do here is send a get request to the mta api(http://bustime.mta.info/wiki/Developers/SIRIVehicleMonitoring ) and simply just print the json response once the user clicks a button.
The code is not printing out anything when the button clicks. Can anyone detect the problem with the code above? I would appreciate it a lot.
You need to change the dataType to jsonp to avoid the CORS restriction.
JSONP is a technique used in JavaScript programs running in web browsers to request data from a server in a different domain. Typically this is prohibited by web browsers because of the same-origin policy. Wikipedia provides a far better description than I possibly could. See here.
When it comes to making GET requests to APIs, this is something you will encounter regularly, so it's worth knowing.
The jquery code allows you to view the JSON object in the console, which you can then manipulate as you please. The way I have currently included will change the div to the timestamp as returned by the JSON object. This jsfiddle should demo what you are looking for http://jsfiddle.net/zmxv2j7q/
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url:"http://bustime.mta.info/api/siri/vehicle-monitoring.json",
data: {key: '##################',
OperatorRef:'MTA%20NYCT',
LineRef:'B54',
VehicleRef:'9531' },
dataType: 'jsonp',
async: false,
success: function(result){
console.log(result.Siri)
$("#div1").html(result);
$("#div1").html(result.Siri.ServiceDelivery.ResponseTimestamp)
}});
});
});

Executing dynamic javascript from an ajax call

I have a web application that is powered by ASP.NET on the server side and Javascript/jQuery on the client side. I'd like to know if it's possible to make an Ajax call to an ASP.NET WebMethod and have the returned javascript code executed. For example (very simplified example):
My HTML:
<html>
<head>
<title></title>
</head>
<body>
<div id="divMessage"></div>
</body>
</html>
In my C#:
[WebMethod]
public static string GetScriptCode()
{
return "$('#divMessage').html('This is a test');";
}
In my javascript:
$(function() {
var handler = function(msg) {
var myScriptCode = msg.d;
// I'd like $('#divMessage') to contain my message
};
$.ajax({
type: "POST",
url: "Test.aspx/GetScriptCode",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: handler
});
});
I'd like the javascript that is returned from my GetScriptCode() to execute. Any ideas how to do this?
using eval() is one option, but as everyone say eval is evil, don't use it.
I normally do it using a dynamic function like so:
var theCode = "$('#divMessage').html('This is a test');";
var F=new function (theCode);
return(F());
Sort of looks like reinventing the eval, but that's how I do it as of now.

Categories

Resources