I'm developing some javascript code to use the summon api server. I developed a simple js function to send a ajax request to the server using JQuery .ajax as below.
requestApi = function(currentDate, digest) {
return $.ajax({
type: "GET",
url: "http://api.summon.serialssolutions.com/2.0.0/search",
data: "s.q=cancer",
headers: {
'Accept': 'application/xml',
'x-summon-date': currentDate,
'Authorization': 'Summon myuser;' + digest
},
error: function(xhr, status, err) {
return console.log(status, err.message);
}
}).done(function(data) {
return console.log(data);
}).fail(function() {
return console.log("Summon Ajax Failed!");
});
};
but I faced an error like:
Failed to execute 'setRequestHeader' on 'XMLHttpRequest':
'Summon myuser;CkKhLokX5jdOx8oCYhgn848MZfw='
is not a valid HTTP header field value.
I don't really know where the problem is. Guide me please. Thanks
Related
<script>
function editComment(id) {
var content = $('#Content').val();
var modelData = { 'Id': id, 'Content': content };
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("EditC", "Comment")',
data: JSON.stringify({ model: modelData }),
contentType: 'application/json',
success: function () {
alert("YES");
},
error: function () {
alert("Error");
}
});
}
</script>
Here the server is returning 200 OK, but for some reason the error function is getting called. Both type and contentType seem to be correct. Any idea how to fix this?
Edit:
After adding
error: function (xhr, textStatus, error) {
console.log(xhr.responseText);
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
this is what is being logged:
parsererror
parsererror
SyntaxError: Unexpected end of JSON input
at parse (<anonymous>)
at ajaxConvert (jquery-3.4.1.js:9013:19)
at done (jquery-3.4.1.js:9483:15)
at XMLHttpRequest.<anonymous> (jquery-3.4.1.js:9785:9)
Moving to an answer for future readers...
The server is indeed returning a successful response, but an empty successful response:
return new HttpStatusCodeResult(200);
However, the client-side code is expecting valid JSON:
dataType: 'json',
As a result, after the successful response is received, internally the jQuery code attempts to parse that response as JSON and that fails, resulting in triggering the error callback.
Since there's no response body (and in most cases even when there is, as long as the server returns the correct MIME type), you don't need or want to specify a dataType in the jQuery AJAX operation. Simply remove this part:
dataType: 'json',
function addthisuser(){
var data = {
__metadata: { 'type': 'SP.User' },
'LoginName': "martin.newman#sharepoint.com"
};
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/SiteGroups/GetByName('HRGroupSharePoint')/users",
method: "POST",
data: JSON.stringify(data),
headers: { 'Accept': 'application/json;odata=nometadata',
'Content-type': 'application/json;odata=verbose',
'odata-version': ''
},
success: function (data) {
debugger;
alert('Item added successfully');
},
error: function (error) {
debugger;
alert("Error: "+ JSON.stringify(error));
}
});
}
Using above POST request to add user (hard coded email against LoginName) ends in error saying "The user does not exist or is not unique". If the user, specified above, is given Read permission on entire site as Unique permissions the error still persists... Is the LoginName format wrong? Is anything wrong in headers?
LoginName must be Key property of person column e.g. i:0#.w|rib.johnson#domain.com
I have the code to post data to the django server and get data from it using ajax. When I use post method the server responds with Bad Request: /quizzes/
[29/Apr/2019 18:13:42] "POST /quizzes/ HTTP/1.1" 400 83
And in the ajax code is not returning any information, not in error nor complete.
When I tried to get data from the server, the server says it's okay
[29/Apr/2019 18:19:57] "GET /quizzes/ HTTP/1.1" 200 249
but the code entered the error and complete blocks with error msg ONLY "Error with status: error"
Another problem is when the request end, my firefox reloads the page and I don't know why
So anyone can suggest a solution to these problems?!
This is my Ajax code for post method, which not giving me any response
And the server is expecting to recieve json object in this format
{
'title': "superheroes java",
'pass_score': 1,
'num_of_questions': 3,
'expected_duration': 10,
'skill_type': {"name": "java"},
}
Here's how I format and send it
$("#add-quiz").click(function () {
quizData = {
title: $("#quizTitle").val(),
pass_score: Number($("#quizPassScore").val()),
num_of_questions: Number($("#quizNumQuestions").val()),
expected_duration: Number($("#quizDuration").val()),
skill_type: {name: $("#quizSkillType").val()}
};
response = ""
$.ajax({
url: "http://127.0.0.1:8001/quizzes/",
dataType: "json",
method: "POST",
data: quizData,
success: function () {
response = "success";
}, error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}, complete: function (request, status) {
alert("Error with status: " + status);
}
});
alert(response);
});
And this is get method which says Error with status: error
response = "";
$.ajax({
url: "http://127.0.0.1:8001/quizzes/",
method: "GET",
success: function (data) {
response = data;
}, error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Status: " + textStatus + "Error: " + errorThrown);
}, complete: function (request, status) {
console.log("Error with status: " + status);
}
});
alert(response);
I'm just using respone for further testing
The problem was that cross-origin resource sharing was disabled. We were able to solve it adding the needed configurations to the server to allow them.
The server used DJANGO so the steps we followed were the ones on the answer of this question
I'm new to the GMail API and am trying to make an AJAX call to retrieve mails.
My code is:
$.ajax({
beforeSend: function (request)
{
request.setRequestHeader("authorization", "Bearer xxxxxxxxxxxxxxxxx.apps.googleusercontent.com");
},
url: 'https://www.googleapis.com/gmail/v1/users/me/messages?key=xxxxxxxxxxxxxxxxxx',
dataType: 'json',
cache: false,
success: function(data) {
// this.setState({Emails: data});
console.log("Mail thread"+data);
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
The response is a 401 error. On examining the request, I find the following query parameter appended to the request URL getting sent:
&_=1470236511985
So the request URL appears like this.
https://www.googleapis.com/gmail/v1/users/me/messages?key=xxxxxxxxxxxxxxxxxx&_=1470236511985
Is the appended query parameter causing the 401 error or am I using the authorization header incorrectly? How can I resolve this.
Thanks in advance.
For testing purposes, you can go to the OAuth 2.0 Playground and get an access token with the Gmail API scopes. Just use this access token in a query parameter named access_token:
var accessToken = 'ya29...';
$.ajax({
url: 'https://www.googleapis.com/gmail/v1/users/me/messages?access_token=' + accessToken,
dataType: 'json',
success: function(data) {
console.log(data.messages);
}
}
I am trying to detect the user's city via this website: http://www.ipaddresslocation.org/my-ip-address.php. Almost all of the free geolocation APIs I've seen so far were not very accurate. When the following code executes, I see all the information I need in the Response tab (in the Network tab in Firefox), but the success event fails and I am not able to access any of that data.
$(document).ready(function(){
getCity();
});
var parameters = {
"Content-Type": "text/html",
'Accept-Encoding': 'gzip, deflate',
};
function getCity() {
$.ajax({
type: "GET",
url: 'http://www.ipaddresslocation.org/ip-address-locator.php',
dataType: 'jsonp',
success: function(data) {
console.log("success");
},
error: function(xhr, status, error) {
console.log("ERROR");
console.log(error.message);
}
});
}
The problem with my code was that I was trying to get the server to respond when I just needed to read the HTML page in my browser. Because of the Same Origin policy, I ended up using the CORS Anywhere node.js proxy to add headers to the proxied request and then doing RegEx to get the city. This link is great at explaining how to make cross-domain requests: Loading cross domain endpoint with jQuery AJAX .
$(document).ready(function() {
$.ajaxPrefilter(function(options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
}
});
$.get(
'http://www.ipaddresslocation.org/ip-address-locator.php',
function(response) {
//regex to get the desired info
});
});
This happens when third party APIs haven't set things up developer-friendly. You can use the complete callback instead of the success callback and then access the responseText property of the XHR response:
$(document).ready(function(){
getCity();
});
var parameters = {
"Content-Type": "text/html",
'Accept-Encoding': 'gzip, deflate',
};
function getCity() {
$.ajax({
type: "GET",
url: 'http://www.ipaddresslocation.org/ip-address-locator.php',
dataType: 'jsonp',
complete: function(jqXHR, txtStatus) {
var myData = jqXHR.responseText;
},
error: function(xhr, status, error) {
console.log("ERROR");
console.log(error.message);
}
});
}
http://api.jquery.com/jquery.ajax/