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.
Related
I'm new to the .Net development and i want to make a call to the client server. When i'm running the lines of code with POSTMAN, it runs pretty well. But when i'm using the same code/headers in java script i'm able to get the desired result.
Below is the line of code i'm using
var xhr = new XMLHttpRequest();
var params = "grant_type=password";
xhr.open("POST", "ClientURL");
xhr.setRequestHeader("Authorization", "Basic ZDJWQ1NmE4NjA4MDc0MjQ2NzSfdsdakj=");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Data-Type", "json");
xhr.setRequestHeader("Host", "URL");
xhr.send(params);
console.log(xhr.status);
console.log(xhr.statusText)
Or
$.ajax({
type: "POST",
url: 'CLIENT URL',
dataType: "json",
headers: { 'Authorization': 'Basic ZDJWQ1NmE4NjA4MDc0MjQ2NzSfdsdakj=' },
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic "ZDJWQ1NmE4NjA4MDc0MjQ2NzSfdsdakj="');
},
success: function (data) {
if (data) {
alert(data);
}
else {
alert("Something went wrong");
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
Is there anything missing in the call? Any help is appreciated
Below it the error in IE
XMLHttpRequest: Network Error 0x80070005, Access is denied.
and in Chrome
Default.aspx:68 Uncaught SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'Basic ZDJWQ1NmE4NjA4MDc0MjQ2NzSfdsdakj=' is not a valid HTTP header field value.
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', "Basic ZDJWQ1NmE4NjA4MDc0MjQ2NzSfdsdakj=");
},
change the function as above.
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);
i have the following code in jquery-ajax that is working fine
ajaxHandler = {
defaultAttributes: {
type: 'GET',
url: 'index.php/request',
datatype: 'json',
data: {},
success: null,
error: function(data) {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
},
timeout: function() {
errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
}
},
sendRequest: function(attributes) {
$.ajax(attributes);
}
Now i want to convert this to native JavaScript Code and i am doing this and 403 error is occur and i am unable to get response.
let me know what changes i have to make to make it working like above code(using jquery-ajax)
ajaxHandler = {
defaultAttributes: {
type: 'GET',
url: 'index.php/request',
datatype: 'json',
data: {},
success: null,
error: function(data) {
errorHandler.showError('An Error occurred while trying to retreive your requested data, Please try again...');
},
timeout: function() {
errorHandler.showError('The request has been timed out, Please check your Internet connection and try again...');
}
},
sendRequest: function(attributes) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.responseType = 'json';
xmlhttp.overrideMimeType("application/json");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
var jsonResponse = JSON.parse(xmlhttp.responseText);
console.log(jsonResponse);
attributes.success(attributes.data);
} else {
console.log(xmlhttp.responseType);
console.log(JSON.parse(xmlhttp.responseXML));
console.log(xmlhttp);
}
}
xmlhttp.open(attributes.type, attributes.url);
xmlhttp.send(attributes.data);
}
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 want to send JSON data in XDR using the POST method. I'm able to send JSON data, however the problem is . (DOT) symbols are converted into _ (underscores). Here is the code:
if ($.browser.msie && window.XDomainRequest) {
var xdr = new XDomainRequest();
xdr.open("POST",Path);
xdr.send(JSON.stringify(data) + '&ie=1');
xdr.onerror = function() {
alert('in error');
};
xdr.onload = function() {
alert(xdr.responseText);
}
} else {
jQuery.ajax({
type: "POST",
url: Path,
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
success: function(msg) {
alert(msg);
}
});
}
May be your server side scripting is wrong..
this code seems to be correct....