jquery $ajax not working as expected - javascript

I Have to do a cross-domain request and fetch content from a url using $.ajax function.
But the below code only displays the first alert i.e alert(myUrl),
After that the execution stops.The second alert is not displayed. I don't know what is wrong with the code i have written.
Can somebody tell me what i am doing wrong here?Thanks in advance.
function getContentFromUrl(){
var myUrl="http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" +
encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
success: function () {
alert("***********"+data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function() {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
});
}

Same Origin Policy:
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.

You can't use regular JSON for cross-domain requests because of the same-origin policy. Instead, you'll need to use JSONP. In jQuery, you can do so like this:
$.ajax({
dataType: 'jsonp',
crossDomain: true
// other info
});
Note that there are security issues involved with JSONP. Only use JSONP if you trust the host domain.

I assume this is jQuery?
Try the following:
url = "http://query.yahooapis.com/v1/public/yql?" +"q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?";
getContentFromURL(url);
function getContentFromURL(url)
{
$.get(url, function (data) {
console.log(data);
});
}
If it dumps out to the console a response, you can build from there.

The data here is not defined
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
and you forget to add a param for the callback function
success: function (data) {
....
}
The finally code should like this
function getContentFromUrl() {
var myUrl = "http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: {},
success: function (data) {
alert("***********" + data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function () { document.getElementById("displayerrors").innerHTML = "Could not load the page."; }
});
}

Related

How to copy file using Rest API and javascript in Sharepoint 2013 between site and subsite

I need to copy file between document libraries. Library A is located in one site and Library B is located in subsite. I know how to copy file between libraries on the same level but the problem is with copying between different level.
The code I use to copy file between libraries on the same level.
$.ajax({
url : "http://xxx/PWA/_api/web/folders/GetByUrl('/PWA/CopyFromLibrary')/Files/getbyurl('Import.csv')/copyTo(strNewUrl = '/PWA/TargetLibrary/Import.csv',bOverWrite = true)",
method: 'POST',
headers: {
"Accept": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function () {
alert("Success! Your file was copied properly");
},
error: function () {
alert("Problem with copying");
}
});
For different level I use just another target URL:
url : "http://xxx/PWA/_api/web/folders/GetByUrl('/PWA/CopyFromLibrary')/Files/getbyurl('Import.csv')/copyTo(strNewUrl = '/PWA/Subsite/TargetLibrary/Import.csv',bOverWrite = true)",
And it doesn't work.
How to work around this problem?
Just figured this one out today for the cross site solution. The trick is-- don't use $.ajax for the download of the document. Use good old XMLHttpRequest. The reason is that JQuery simply doesn't let you get a raw binary data array from SharePoint. But, the XMLHttpRequest does because it allows you to get an arraybuffer as part of its implementation, which SharePoint accepts!
The following is the code with the parts identified for building the full source and target REST urls. Note that you can use $.ajax to upload the file.
sourceSite is a sharepoint site suitable for appending the '_api' rest endpoint
sourceFolderPath is the relative folder path your document is located within
sourceFileName is the filename of the document
targetSite, targetFolderPath and targetFileName are the mirror images or source, only for the destination.
requestDigest is that special value you need for SharePoint to accept updates.
function copyDocument(sourceSite, sourceFolderPath, sourceFileName, targetSite, targetFolderPath, targetFileName, requestDigest) {
var sourceSiteUrl = sourceSite + "_api/web/GetFolderByServerRelativeUrl('" + sourceFolderPath + "')/Files('" + sourceFileName + "')/$value";
var targetSiteUrl = targetSite + "_api/web/GetFolderByServerRelativeUrl('" + targetFolderPath + "')/Files/Add(url='" + targetFileName + "',overwrite=true)";
var xhr = new XMLHttpRequest();
xhr.open('GET', sourceSiteUrl, true);
xhr.setRequestHeader('binaryStringResponseBody', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
if (this.status == 200) {
var arrayBuffer = this.response;
$.ajax({
url: targetSiteUrl,
method: 'POST',
data: arrayBuffer,
processData: false,
headers: { 'binaryStringRequestBody': 'true', 'Accept': 'application/json;odata=verbose;charset=utf-8', 'X-RequestDigest': requestDigest }
})
.done(function (postData) {
console.log('we did it!');
})
.fail(function (jqXHR, errorText) {
console.log('dadgummit');
});
}
}
xhr.send();
}
What kind of error are you getting?
One probable cause of your problem is that your RequestDigest does not match the location where you want to POST your file since it is fetched from the page where your code is running. Fetch a matching RequestDigest by calling '_api/contextinfo' on your target location.
See:
http://blogs.breeze.net/mickb/2012/11/20/SP2013GettingAFormDigestForUpdateRESTCalls.aspx
and
http://msdn.microsoft.com/en-us/magazine/dn198245.aspx (writing to Sharepoint section)
Note
File Move operations only work within the scope of a given document library. You cannot copy between document libraries.
http://msdn.microsoft.com/en-us/library/office/dn605900(v=office.15).aspx#Folder6
For POST - operation we need request digest value, which is used by SharePoint to authenticate mainly for Post, Delete, Update not needed for GET operation,
Sample jquery ajax code for post operation-
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
success(data); // Returns the newly created list item information
},
error: function (data) {
failure(data);
}
});
You can try the following code for copying file from one location to another within SharePoint.
The following example will be helpful in copying files within SharePoint sandbox.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="myapp" ng-controller="mycont">
<input type="button" ng-click = "myclick()" value="Angular File Copy" />
</div>
<input type=button onclick="x()" value="jQueryFile copy" />
<script>
var dt =new Date();
var val_ue = dt.getDate()+""+dt.getHours()+""+dt.getMinutes()+""+dt.getSeconds() +"1" ;
var url1 = "/_api/web/getfilebyserverrelativeurl('/Lists/Document_Mapping/Attachments/1/9.jpg')";
var url2 = "/Lists/AddressVersioning/Attachments/84/" ;
var combined = "";
var app = angular.module('myapp',[]);
var _headers = {
'X-RequestDigest': document.getElementById("__REQUESTDIGEST").value,
'accept':'application/json;odata=verbose'
};
app.controller('mycont',function($scope,$http){
$scope.myclick = function(){
combined = url1 + "/copyTo('" + url2 + val_ue + ".jpg')";
$http({method:'POST',url:combined,headers:_headers}).then(
function(response){
console.log("hi");
val_ue += 1;
},
function(error){
console.log("Error:");
console.log(error);
},
function(process){
console.log("process:");
console.log(process);
}
);
}
});
var x = function(){
combined = url1 + "/copyTo('" + url2 + val_ue + ".jpg')";
$.ajax({
url : combined,
method: 'POST',
headers: {
"Accept": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function () {
alert("Success! Your file was copied properly");
val_ue +=1;
},
error: function () {
alert("Problem with copying");
}
});
}
</script>
Note: the above function will not work if the list item is newly created. But for all other situations it will work (even form one doc library to another doc library or cross site / site collection)

jquery ajax function with json

Hi i am using this code to get contents from a json file but i am not able to show results
my code is
$(document).ready(function(){
$.ajax({
url: 'http://50.116.19.49/rest/user.json',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 50000,
success: function(data, status){
alert(data);
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
In google chrome i can see that the request status is 200 and data is loaded. here is the link from which i am copying code The Link.... Any help!!!!
Thanks
Your code doesn't work because the http://50.116.19.49/rest/user.json resource return a JSON response instead of JSONP (difference).
So you can't make cross-domain calls via ajax BUT you can create a some proxy script ON YOUR SERVER which will make it for you. Example:
cross-domain-call.php
<?php echo file_get_contents('http://50.116.19.49/rest/user.json');?>
And change your script to
$(document).ready(function(){
$.ajax({
url: 'http://127.0.0.1/cross-domain-call.php',
dataType: 'json',
timeout: 50000,
success: function(data, status){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
});
Since you don't seem to have access to remote webservice to convert it to JSONP, here is a solution using Yahoo's YQL as a proxy. YQL will retrieve file contents from any remote site and return as xml or jsonp.
Working DEmo http://jsfiddle.net/Uh8cz/2/
You will notice the response object has additional properties created by YQL
var yqlBaseUrl = 'http://query.yahooapis.com/v1/public/yql?q=';
var restUrl = 'http://50.116.19.49/rest/user.json';
var yqlQuery = 'select * from json where url="' + restUrl + '" ';
var yqlFormat = 'format=json'
var jQueryCallback = '?'
var fullQueryUrl = yqlBaseUrl + yqlQuery + '&' + yqlFormat + '&' + jQueryCallback;
$.getJSON(fullQueryUrl, function(json) {
var jsonString = JSON.stringify(json.query.results.json.json, null, ' ')
$('body').append('<h1>Response</h1><pre>' + jsonString)
}) ​
If you can control the content of "user.json", wrap it around a function:
user.json content:
execute_jsonp({you_json)
your javascript:
$(document).ready(function(){
$.ajax({
url: 'http://50.116.19.49/rest/user.json',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 50000,
success: function(data, status){
data(); //execute the function that is sent
},
error: function(){
output.text('There was an error loading the data.');
}
});
function execute_jsonp(json){ //recreate the function so you may access the json as a parameter
alert(json);
}
});
Hope this helps ;)

Client Side Ajax with jQuery reading a JSON

I'm trying to make a JavaScript that is fetching a JSON (IP DATA) and retrieves data from it (GEO IP) with AJAX and this is what I have so far:
$(document).ready(function(){
var path_to_the_webservice = "http://www.pathtothescript.com/check.php";
$.ajax({
url: path_to_the_webservice,
success: function(html)
{
if(html)
{
alert('3');
$('#content').append(html);
}
else
{
alert('4');
}
}
});
});
and I get alert(4), WHY?
Basically when you access http://www.pathtothescript.com/check.php from browser, retrieves a JSON that I have to parse with:
$.getJSON(path_to_the_json,
function(data)
{
$.each(data, function(i,item)
{
});
}
but I'm not sure how to make it.
The JSON looks like this http://j.maxmind.com/app/geoip.js
Any help?
It can be caused by Same origin policy.
Try to use JSONP request:
$.getJSON('http://example.com?callback=?', function(data) {
console.log(data);
});
Handling the response from http://j.maxmind.com/app/geoip.js
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.get('http://j.maxmind.com/app/geoip.js', function(data) {
console.log('Retrieved data:',
data,
'is type of', typeof data);
// Now we have some functions to use:
console.info('Some info:', geoip_country_name(),
geoip_latitude(),
geoip_longitude());
});​
Fiddle
UPDATE:
In chat we found that my previous example works good in Google Chrome but doesn't work in Mozilla Firefox.
Though I played a little bit with it and found the solution:
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.ajax({
url: 'http://j.maxmind.com/app/geoip.js',
type: 'GET',
success: function(data) {
// Now we have some functions to use:
alert(geoip_country_name() + ': ('
+ geoip_latitude() + '; '
+ geoip_longitude() + ')');
},
error: function(e) {
console.log('Error:', e);
},
contentType: 'application/javascript; charset=ISO-8859-1',
dataType: 'script'
});
​
Fiddle
Also I've set a charset accordingly to service documentation.

Cross site HTTP authentication in JQuery

I want to see if it is possible to log into a third site that uses HTTP authentication. Ideally, the browser will store the credentials. Unfortunately this fails every time. Any help would be much appreciated, I'm using the base64 Jquery plugin, which I've tested to work.
So, two questions:
How can I view the HTTP status code?
Will this ultimately work, in principle?
<script>
$("#login_button").click(function() {
var username = 'myFunUsername';
var password = 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + $.base64.encode(username + ":" + password));
},
success: function(data) { $("#label").text("Logged in, yay!"); }
}).fail(function(){ $("#label").text("It didn't work"); });
});
Thanks!!
var user= 'myFunUsername';
var pwd= 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
crossDomain:true,
username :user,// Keep the variable name different from parameter name to avoid confusion
password:pwd,
xhrFields: { /* YOUR XHR PARAMETERS HERE */}
beforeSend: function(xhr) {
// Set your headers
},
success: function(data, textStatus, xhr) {
alert(xhr.status);// The status code
//Code for success
}
}).fail(function(){
//Fail code here
});
For more details on parameters refer to http://api.jquery.com/jQuery.ajax/

Access control origin error calling Google custom search API via jQuery

I'm trying to call the google custom search API with JQuery and getting an access-control-origin error. This works:
<script>
function hndlr(response) {
console.log(response);
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
$('#content').append(item.htmlTitle + "<br/>");
}
}
</script>
<script src="https://www.googleapis.com/customsearch/v1?key=AIzaSyABvGyx3nwDJJtbaRe2_UZhakVSpcxfebU&cx=017576662512468239146:omuauf_lfve&q=perlin+noise&callback=hndlr"></script>
but if I try to introduce jquery, it doesn't work:
var url = "https://www.googleapis.com/customsearch/v1?key=[MY_KEY]&q=perlin+noise&callback=hndlr";
$.ajax({
url: url,
dataType: 'json',
success: function(data){
console.log('data:' + data);
}
OR
$.get(url, function(data) {
console.log(data)
});
You are doing a cross domain request, so you have to use JSONP.
http://davidwalsh.name/jsonp
I recommend using $.getJSON
You would want to set the clear callback, so that that JSONP doesnt call a function
This seemed to work:
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp'
});

Categories