I am trying to send my selection to a server using post and server need REST, Tested my data with Advanced Rest Client and all works well, But when I try from my chrome extension I am getting undefinded error. Here is what I am trying
chrome.runtime.sendMessage({
method: 'POST',
action: 'REST',
headers: {'Remote-User':'myuser'},
url: 'http://myserver/data/add/',
data: {'content': 'the paste content'}
}, function(responseText) {
alert(responseText);
});
Any help much appreciated, thanks
Update
Based sdc, I changed my code like this and still responseText is undefined :(
function genericOnClick(info, tab)
{
var url = 'http://mysite/data/add/';
var data = $.toJSON({'content': 'the paste content'});
$.ajax({
headers: {
'Remote-User':'username',
'Content-Type':'application/json;charset=utf-8'
},
url: url,
data: data,
method: 'POST',
dataType: 'json',
error: function(xhr, status, error){
alert(xhr.responseText);
},
success: function(data){
console.log('succes: '+data);
}
});
}
I think you misunderstand the purpose of chrome.runtime.sendMessage. See the first two paragraphs of the Message Passing documentation. sendMessage is used for "communication between extensions and their content scripts" it is not designed for sending an HTTP request.
A content script must also "set up a runtime.onMessage event listener to handle the message" only then will you receive a valid response from the sendMessage request
The result from their example is undefined
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
console.log(response.farewell);
});
<- undefined
If you are attempting to perform a HTTP request from within your chrome extension, you should use XHR
var data = $.toJSON({'content': 'the paste content'});
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myserver/data/add/", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
xhr.setRequestHeader('Remote-User', 'myuser');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log('xhr response: '+ xhr.responseText);
}
}
xhr.send(data);
Related
Please Help me with how to send json object and receive it it views.py in django.
my script:
var obj={ 'search_name':search_name,'search_email':search_email };
jsonobj=JSON.stringify(obj);
//alert(jsonobj);
var xhr=new XMLHttpRequest();
xhr.open('POST',"viewprofile",true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(jsonobj);
Using XMLHttpRequest() in plain JavaScript.
XMLHttpRequest is an API that provides client functionality for transferring data between a client and a server.
xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.name)
}
}
var data = JSON.stringify({"email":"tomb#raider.com","name":"LaraCroft"});
xhr.send(data);
Using AJAX Calls (preferred way)
$.ajax({
url: "https://youknowit.com/api/",
type: "POST",
data: { apiKey: "23462", method: "POST", ip: "208.74.35.5" },
dataType: "json",
success: function (result) {
switch (result) {
case true:
processResponse(result);
break;
default:
resultDiv.html(result);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
Note: Keeping an eye on developer tools or firebug XHR debug process is good way to learn more about the api calls be it in any technology.
I've seen similar incidents such as this. However, none of them seem to encounter the same problem I am having: Making a POST request and getting a 500 Internal Server Error in response.
I'm attempting to convert either of the following AJAX or XHR that I generated from a postman command to the AngularJS method of using the $http service:
The xhr:
var data = "json=<lots of encoded text>";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "https://myJenkins.com/job/Ansible_Deploy/build?token=<build_token>");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Basic <auth data>");
xhr.send(data);
The ajax:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://myJenkins.com/job/Ansible_Deploy/build?token=<build_token>",
"method": "POST",
"headers": {
"content-type": "application/x-www-form-urlencoded",
"authorization": "Basic <auth data>"
},
"data": {
"json": "<raw json text>"
}
};
$.ajax(settings).done(function (response) {
console.log(response);
});
The broken AngularJS implementation:
var heads = new Headers();
heads.append('Content-Type', 'application/x-www-form-urlencoded');
heads.append('Authorization', 'Basic <auth data>');
$http({
url: "https://myJenkins.com/job/Ansible_Deploy/build?token=<build token>",
method: "POST",
data: <json object>,
headers: heads
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.statusText);
});
Both of the above Ajax and xhr implementations work fine. As mentioned above, the angular approach is giving me a 500 Internal Server Error.
Any ideas why this may be happening? I can provide specifics if they may help, such as information from the network tab on the chrome inspector. Just let me know what I should take a screenshot of and I'll post it here.
EDIT: As promised in the comments, my solution is below.
$http({
url: "https://myJenkins.com/job/Ansible_Deploy/build?token=<build token>",
method: "POST",
data: 'json=' + JSON.stringify(data),
headers: {
'Accept': "*/*",
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic <auth data>'
}
}).then(function successCallback(response) {
console.log(response.data);
}, function errorCallback(response) {
console.log(response.statusText);
});
EDIT 2: If you stumble upon this question because you're also getting a 500 Internal Server Error and still don't understand how this was resolved, then it was resolved via a combination of ensuring that CORS was setup on the server containing the endpoint (indicated by Crome's inspector throwing Access-Control-* errors) as well as correctly formatting the x-www-form-urlencoded to be accepted by Jenkins, which requires the data being sent to be of the form json={"parameter":[{"name":<key>, "value":<value>}, ...]}. Furthermore, if the value of an entry is a nested then escaping is required. see this answer for more details.
I am trying to call Neo4j API from jquery.
when i am invoking GET requests it works perfectly
GET request endpoint
http://localhost:7474/db/data/node/10
but when i am invoking POST requests with json body it returns following error.
POST request endpoint
http://localhost:7474/db/data/cypher
Error Message
"NetworkError: 500 Server Error - http://localhost:7474/db/data/cypher"
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:7474/db/data/cypher. This can be fixed by moving the resource to the same domain or enabling CORS.
When i try from Advance REST Client, it returns correct response. Please refer following code
$(document).ready(function(){
$("#btnQuery").click(function(){
var Request = "{'query' : 'MATCH (Movie { name:{searchName} })-[SHOWS]-(Cinema) RETURN Cinema','params' : {'searchName' : 'Rio 2'}}";
//url = mainURL +"cypher";
url = "http://localhost:7474/db/data/cypher";
$.ajax({
url: url,
headers : {
'Authorization' : 'Bearer 5f0e0d8c2a5477d4a8e79fa2d34f84a'
},
crossDomain: true,
type: 'POST',
dataType: 'application/json',
complete: function(xhr) {
if (xhr.readyState == 4) {
if (xhr.status == 201) {
alert("Data is loaded");
clearUsers();
isUserAdd = false;
}
} else {
alert("Data is not loaded");
}
},
beforeSend: function (xhr) {
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
data: ('(' + Request + ')')
});
});
});
I have a working example here: http://jexp.github.io/cy2neo
Check out the code: https://github.com/jexp/cy2neo/blob/master/scripts/neo.js#L8
I think the problem was dataType: JSON which caused jquery to send a pre-flight header w/o CORS. I changed it to specifying content-type: JSON
The fail function gives me a correct output, whereas the done function gives me blank. I am stuck with this for hours. Any idea on how to debug this?
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (contentType == null) {
contentType = "application/json";
}
var reqst = $.ajax({
beforeSend : function(req) {
req.setRequestHeader("Content-Type", "application/json");
},
url : url,
type : "post",
contentType : contentType,
data : paramsTable,
});
reqst.done(function(xhr){
alert(xhr.responseText);
});
reqst.fail(function(xhr){
alert(xhr.responseText);
});
I would like to recommend you to use Ajax jQuery API instead of the old Ajax requests. No body uses it today (almost nobody; since you use it)
$.ajax({
beforeSend: function(req) {
req.setRequestHeader("Content-Type", "application/json");
},
url: url,
type: "post",
contentType: contentType,
data: paramsTable,
success: function () {
// here the code to execute if success
},
error: function () {
// here the code to execute if error..
}
});
Why your code isn't working
Because you are never using the xhr to send the Ajax request so it has nothing to show as the response text. Funny isn't it? hehehe.
use this:
success: function(resp) {
alert(resp); // where resp is the name of the responseText here..
}
I have shown you how to use it. Good luck!
For more: http://api.jquery.com/jquery.ajax/
Try to use standard jquery ajax structure:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
})
.fail(function() {
alert( "error" );
});
I'm currently having issues making an external GET request for an API that I need to call and retrieve data from dynamically in JSON. Does anyone know what below may be incorrect? The main issue seems to be that the header information for the Authentication field is not being set correctly and that javaScript can't call out of local domains. I desperately need a work around to this : (error: XMLHttpRequest cannot load http://www.website.com/api.php. Origin http://localhost is not allowed by Access-Control-Allow-Origin.)
function requestDealer(url)
{
alert("looking up dealer");
var request = new XMLHttpRequest();
$.ajax({
url:url,
type: 'GET',
data: null,
Accept : "application/json",
contentType: "application/json",
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
}
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'NLAuth nlauth_account=23984390, nlauth_email = email#email.com, nlauth_signature= myPwrd');
xhr.setRequestHeader('Content-Type', 'application/json');
}