I can't seem to get it working, I followed other code, and it didn't seem to get success, I then written it letter to letter, stil can't get success.
The url works great, I can put it in browser and it will show me the array which I need.
$(document).ready(function(){
$("#submitSearch").on("click", function() {
var searchInput = $("#txtName").val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + searchInput;
var wikiItemArray = [];
$.ajax({
url: url,
type: "GET",
async: false,
dataType: "json",
success: function (data) {
console.log(data);
},
error: function(error){
console.log("There was an error somewhere in &.ajax: " + url);
}
});
});
});
Change the dataType from "json" to "jsonp".
That api is not CORS enabled but does serve jsonp
Related
I'm trying to update a file using the Github v3 api. Most of the documentation I could find was based on the older API. I want to utilize: https://developer.github.com/v3/repos/contents/#update-a-file
I first grab the file using:
$.ajax({
url: "https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "user" + btoa(owner+":"+passwrd));
},
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var jsonFile = data.content;
sha = data.sha;
var decodedJson = atob(jsonFile);
var parsedDecodedJson = JSON.parse(decodedJson);
parseData(parsedDecodedJson);
},
error: function(error){
alert.addClass('alert-danger').removeClass('hidden').html('Something went wrong:'+error.responseText);
}
});
Which works perfectly.
After editing the file, I try to update the file.
On my submit I post the following using jQuery:
var postData = {
"message": "Update",
"content": btoa(obj),
"sha": sha,
"branch":"gh-pages"
};
$.ajax({
url: "https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "user" + btoa(owner+":"+passwrd));
},
type: 'PUT',
data: postData,
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log("Success!!!", data);
},
error: function(error){
console.log("Cannot get data", error);
}
});
All the variables contain the expected values. Regardless, I keep getting a 404.
I know the API more often than not returns a 404 instead of something like a 403 as stated here: https://developer.github.com/v3/#authentication But it makes debuggin nearly impossible in my opinion. I have no clue what I'm doing wrong here. Thanks!
The only way I was able to do it is to make the entire round trip.
I used a javascript Github API wrapper
Luckily I found this article in which the bulk of the work was already been done. Props to Illia Kolodiazhnyi.
In the end. I ended up with this:
Handler on top of github api plugin
Usage:
var api = new GithubAPI({ token: token});
api.setRepo(owner, repo);
api.setBranch(branch).then(function () {
return api.pushFiles(
'CMS Update',
[
{
content: JsonData,
path: path
}
]
);
}).then(function () {
console.log('Files committed!');
});
Good morning stackoverflow,
I try to get json response from an URL
Click, as expected i got Access-Control-Allow-Origin within GoogleChrome, I switched to FireFox, to avoid this problem and then i got status -1 and data null.
$(document).ready(function () {
var URL = "https://www.infojort.com/axs/search?q=marouani%20zied";
console.log('------------------------');
$.ajax({
url: URL,
dataType: 'application/json;charset=utf-8',
success:function (data) {
console.dir(data);
console.log('yes');
},
complete:function () {
console.log('yes');
}
})
$.ajax({
dataType: "application/json;charset=utf-8",
url: URL,
success: function (data) {
console.dir(data);
}
});
$.getJSON(URL, function (data) {
var items = [];
$.each(data, function (key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
});
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).appendTo("body");
});
Notice :
I can get the response with postman without problems.
Content-Type →application/json;charset=utf-8
I need a solution with jquery, ajax or angularjs.
Thanks you all.
Your problem seems related to the API and not to your JavaScript call itself,
what I mean is that you are trying to Call to your API from a Cross Origin and it is not allowed by default for security reasons, so you have to enable cross origin in the server in order to make this kind of calls https://spring.io/understanding/CORS
Look at this, it is a Cross Origin call (Jquery within AngularJS):
$.ajax({
type: 'POST',
url: CTHelper.ApiUrl() + '/token',
data: {
grant_type: 'password',
username: $scope.UserName,
password: $scope.Password
},
success: function (result) {
alert('OK');
},
error: function (result) {
alert('Error');
}
});
but the API must allows CORS, this is a part of the file Startup.Auth.cs
[This example uses AspNet Web Api, C# as Backend]
public void ConfigureAuth(IAppBuilder app) {
...
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
...
}
Microsoft.Owin.Cors can be downloaded as a nuget package.
I'm trying to get the extract of a random Wikipedia page using Ajax. I've got as far as getting the data, but I'm having trouble outputting it.
Here's my code:
$.ajax({
type: "GET",
url: "https://simple.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=extracts&exsentences=10&format=json&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data) {
console.log(data);
var text = data.parse;
document.getElementById('div_text').innerHTML = text;
},
error: function (errorMessage) {
}
});
The console logs the data fine, but the output in the browser is simply undefined.
Clearly, the problem is this line:
var text = data.parse;
Where am I going wrong?
The data is not in data.parse but in data.query.pages and in there the first object.
So change you success method to
success: function (data) {
var pages = data.query.pages;
var text = pages[ Object.keys(pages)[0] ].extract;
document.getElementById('div_text').innerHTML = text;
}
For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "¶m2=" + param2 + "¶m3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);
I have a JSON response coming from REST web service and want to bind that data to html using jQuery. Looks like its not even hitting web service url which I have provided in my jquery.
Url is working fine which gives me JSON data in browser but jQuery I am using unable to get any content from this. I am pasting my code here, plz let me know if some one can help.
While debugging script its directly going on error section in ajax call.
<script type="text/javascript">
$(document).ready(function () {
GetData();
});
function GetData() {
// alert(textblock.value);
$.ajax({
type: "GET",
url: "http://localhost:8092/api/Employees",
data: "{'employeeId'= '" + 1234 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var results = $.parseJSON(msg.d);
alert(msg);
alert(results);
},
error: function (result) {
alert('here');
var tt = result.text;
alert(tt);
}
});
}
</script>
finally i am able to get data now.
I added below properties in $.ajax:
processData: false,
async: false,