Crossdomain request - html

I try to load static html pages from another server.I make crossdomain request.
$(document).ready(function (){
$("div[src]").each(function(){
var staticFileURL = $(this).attr('src');
$.ajax({
url: staticFileURL,
dataType: 'jsonp',
data: {},
error: function(xhr, status, error) {
alert(error);
},
success: function() {
alert("success");
},
jsonp: false,
jsonpCallback: 'jsonpCallback'
});
});
});
But I got in chrome error "SyntaxError:Unexpected token <".
In FF "SyntaxError:Invalid xml attribute value".
What's wrong.Could somebody help me?

JSONP is to get json data from the server, it looks like you are trying to received HTML data.
Try to put your HTML data inside JSON object on the server and then read that HTML on the success callback:
for example, your json data from the server:
{ html: "<html><head>...</head></html>" }
also, your success callback should look like:
success: function(**data**){
}

Related

How to Post JSON Data to server in phonegap

hi i write in this code but i get Error like UNdefined how we can resolve this issue if any one know this answer plz let me know
$.ajax({ type: "POST", contentType:"application/json; charset=utf-8", dataType: "application/json", url:"some url",
data :{familyVoterId:'0',boothId:'0',voterId:'59136604',previousEnrollmentNumber:'29422415',casteId:'62',street:'hamlet',voterRelationId:'8',cadrePrevYear:'',relativeName:'DESSAPPA',previousRollesList:[{fromDateStr:'2012-10-24',cadreRoleId:'1',cadreCommitteeId:'1',cadreCommitteeLevelId:'1',toDateStr:"2013-10-24"}],partyMemberSinceStr:"2001-10-24",uniqueKey:"10d11073-a8b1-4764-bf2f-e2c0a269e9cd",nameType:"Voter",panchayatId:"0",age:28,surveyTimeStr:"2014-10-24 15:05:15",gender:"M",relationTypeId:8,bloodGroupId:3,dobStr:"1968-02-02",nomineeGender:"1",photoType:"VOTER",voterCardNumber:"UXN0862806",longititude:"78.413",aadheerNo:"987654321",candidateAadherNo:"12345678910",educationId:"2",nomineeAge:"21",previousParicaptedElectionsList:[{"electionTypeId":17,candidateId:"30126",constituencyId:"461"}],voterName:"RAMAKRISHNA",occupationId:"1",houseNo:"3-60",cadreFamilyDetails:[],createdUserId:"152",refNo:"TR-T-9999-12985",constituencyId:"282",latitude:"17.4278",nomineeName:"nominee",mobileNumber:"9999999999"},
success: function(data)
{
alert("success");
},
error: function(msg)
{
alert(msg.message);
}
});
Also, in addition, the reason it is failing in the first place is because you need to do a cross-domain post. In order to do this correctly through jQuery, you need to use the following options:
dataType: 'jsonp',
cache: false,
I reproduced your error. In Chrome if you click inspect element and then select the Console tab you can see the error message :
XMLHttpRequest cannot load file:///D:/DeleteME/pyMail/some%20url.
Cross origin requests are only supported for protocol schemes: http,
data, chrome-extension, https, chrome-extension-resource.
As mentioned before you need to specify the data type as jsonp if your are posting to another domain.
Example:
$.ajax({ type: "POST", contentType:"application/jsonp; charset=utf-8", dataType: "application/json", url:"http://www.google.com",
data :{familyVoterId:'0',boothId:'0',voterId:'59136604',previousEnrollmentNumber:'29422415',casteId:'62',street:'hamlet',voterRelationId:'8',cadrePrevYear:'',relativeName:'DESSAPPA',previousRollesList:[{fromDateStr:'2012-10-24',cadreRoleId:'1',cadreCommitteeId:'1',cadreCommitteeLevelId:'1',toDateStr:"2013-10-24"}],partyMemberSinceStr:"2001-10-24",uniqueKey:"10d11073-a8b1-4764-bf2f-e2c0a269e9cd",nameType:"Voter",panchayatId:"0",age:28,surveyTimeStr:"2014-10-24 15:05:15",gender:"M",relationTypeId:8,bloodGroupId:3,dobStr:"1968-02-02",nomineeGender:"1",photoType:"VOTER",voterCardNumber:"UXN0862806",longititude:"78.413",aadheerNo:"987654321",candidateAadherNo:"12345678910",educationId:"2",nomineeAge:"21",previousParicaptedElectionsList:[{"electionTypeId":17,candidateId:"30126",constituencyId:"461"}],voterName:"RAMAKRISHNA",occupationId:"1",houseNo:"3-60",cadreFamilyDetails:[],createdUserId:"152",refNo:"TR-T-9999-12985",constituencyId:"282",latitude:"17.4278",nomineeName:"nominee",mobileNumber:"9999999999"},
dataType: 'jsonp',
success: function(data)
{
alert("success");
},
error: function(msg)
{
alert(msg.message);
}
});
Message is not a property of the XHR object msg in your error callback function. That is why it shows undefined in your alert box. You can try to alert msg.statusText and see the status text.
Please check the documentation http://api.jquery.com/jquery.ajax/
(The jqXHR Object section)

Using HTTP GET with JQuery

I'm trying to use a GET HTTP cal, I got the request to work with the Advanced REST client (Chrome plugin) but cannot get it to work in JQuery.
Following the advice from this thread, I've set up the following:
$(document).ready(function() {
$('.ap1').click(function(){
$.ajax({
url: 'https://api2.panopta.com/v2/monitoring_node/41',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
//extra stuff from REST CLIENT
xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
} });
This is the output I'm trying to get (successfully with REST client)
{
url: "https://api2.panopta.com/v2/monitoring_node/41"
hostname: "phoenix01.monitorengine.com"
ip_address: "65.23.158.149"
name: "Phoenix"
textkey: "na.west.phoenix01"
}
I just want to be able to access the name variable from that JSON and pass it through my function. I wanted to at least get the above code to work before I try to figure out how to create an object so I can successfully call the name, something like .append(object.name)
I just started learning JQuery and this is my first post so sorry if I didn't include enough details.
You can't apply ajax calls to other domains. You can make workaround using server-to-server calls via curl() or file_get_content(url), and then make a js call to your script.
First make php file, which will call the server note that if you want to use file_get_contents you should allow_url_fopen in your php.ini:
myProxy.php
<?
$content = file_get_contents($yourUrl);
// do whatever you want with the content then
// echo the content or echo params via json
?>
your js should make call to your PHP, so you have workaround Same Domain Policy:
$.ajax({
url: 'myProxy.php',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
I am not sure if your api info is correct, but I think the main thing you need to do is change to jsonp instead of json due to the same origin policy that musa mentions.
The following JS fiddle "works" but the request is not authorized at the server: http://jsfiddle.net/cf8S9/.
$(document).ready(function() {
$('#button').click(function(){
$.ajax({
url: 'https://api2.panopta.com/v2/monitoring_node/41',
type: 'GET',
dataType: 'jsonp',
success: function() { alert('hello!'); },
error: function() { console.log(arguments);alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
//extra stuff from REST CLIENT
xhr.setRequestHeader('Authorization', 'ApiKey nGhhAjGshbOu4dhLYvGY');
} });

JSON parsing from cross domain using jquery ajax

Im trying to parse json from cross domain but im getting error like 405 (Method Not Allowed) in jquery plugin (im using latest plugin only from google) Any solution or suggestions will be great help for me.
Thanks
Basha
Here is my code
$(document).ready(function() {
$.ajax({
type: "GET",
url: "http://myurl.com/webservice&callback=?",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "jsonp",
data: "{}",
Accept: "",
beforeSend: setHeader,
success: OnGetAllMembersSuccess,
error: OnGetAllMembersError,
});
});
function setHeader(req) {
req.setRequestHeader("Authentication", "Basic credentials");
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("Accept", "application/json");
}
function OnGetAllMembersSuccess(data, status) {
alert(status);
$.each(data.result, function(key, value) {
$("#result").append(key+" : "+value);
$("#result").append("<br />");
});
}
function OnGetAllMembersError(request, status, error) {
alert(status);
}
While using jsonp as dataType, you need to bind a call back function in the server side..
for example, if you need a json response like {"id":"myId"}, at the server side it should be return like "mycallback({"id":"myId"})";
Also you need to write that function in client side too.
function mycallback(json)
{alert(json);}

how to set jsonp callback in retrieving restful web service data via jquery

I have asked a question regarding invalid label on firebug which happens when I try to retrieve data from my restful web service. Most of the answers I received was about setting a callback function. but I can't seem to get the right juice from it. can you show me an exact code on how to do it? or atleast correct the code here:
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
processdata:true,
jsonp: false, jsonpCallback: "success",
url: 'http://localhost:8732/Service1/data/10',
success : function success(data) {
jsonResponse = eval("(" + data + ")");
alert(jsonResponse)
},
error : function(req,status, ex) {
alert(ex);
}
Thanks,
Wow, you've got a lot of unnecessary stuff there. Try this:
$.ajax({
url: 'http://localhost:8732/Service1/data/10',
dataType: 'jsonp',
error: function(req, status, ex) {
// your code here
},
success: function(data) {
//your code here
// Please note: you don't need to 'eval' the json response.
// The 'data' variable will be loaded with the object that the json string represents.
// By the way, don't use 'eval', ever.
}
});
jQuery will take care of the callback on the url. See here: http://api.jquery.com/jQuery.ajax/
UPDATE
Why jsonp? If you're getting this from localhost, why not just json? As discussed in the comments below, your server currently is not capable of a jsonp response, but it can do json.

Cross Domain JSON Request Failing

I am trying to run this code in my browser's console:
$.ajax({
dataType: 'json',
url: 'http://www.web2pdfconvert.com/engine?curl=http://www.nytimes.com&outputmode=json?callback=?',
success: function (data) {
if(data.resultcode == 1) {
console.log(true);
} else {
console.log(false);
}
},
});
However, I am getting a Cross Domain Request Error. when I try to make a simple JSON request then also same error occurs, because JSON request cannot be made on Cross Domains. however, when you go to this URL:
http://www.web2pdfconvert.com/engine?curl=http://www.nytimes.com&outputmode=json
You'll be able to see the JSON data. However, a key point written in the documentation of this websites API says that:
json - all conversion data are returned as JSON object. Also JSONP cross domain communication supported usign jQuery.
Thanks in advance.
Use jsonp instead:
$.ajax({
dataType: 'jsonp',
url: 'http://www.web2pdfconvert.com/engine?curl=http://www.nytimes.com&outputmode=json',
jsonp: "callback",
success: function (data) {
if(data.resultcode == 1) {
console.log(true);
} else {
console.log(false);
}
},
});