Making a GET request that uses POST method - Javascript to C# API - javascript

I have a situation where I'm required to encrypt data in flight from a JavaScript based application (Chrome Extension popup.html) to an API hosted in a .NET MVC website(C#).
I can run the request as a GET but project requirements make it necessary to encrypt the parameters I'm sending. For example if I was searching for all people named 'John' I need to encrypt 'John' in flight.
My JavaScript application is using jsencrypt and a RSA (public) key provided by the website in other APIs that work quite well to return counts.
If my GET version of the link looks like this:
<span class="person" id="personList">Person: '+ query +'</span>
On the .NET website end, this request is processed into a view that generates a table using a database call. As you can see in my link the results are populated onto a new tab in the browser.
How would you recommend changing it to calling a POST method and getting the same result as a GET?
EDIT
I tried to employ an AJAX function to make the POST but it doesn't like the data element:
event.preventDefault();
$.ajax({
url: repurl + 'Persons/Search',
timeout:30000,
type: "POST",
data: {body: encryptedmsg},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
alert('ok');
}
else
{
alert('some thing went wrong, plz try again');
}
}
});
});```

Related

How to make a request using jQuery to a django server to refresh infos on page

I made a website in python using Django. My site allows you to control lights while indicating if the light is on or not.
I'm looking for a solution that could make a simple request with data to the server and send data back to the client without updating the entire page but only a part of it.
My ideal would be for the client to make a request to the server with identification data. Then, the server returns the updated data that the user is allowed to have.
Is that possible to make a JavaScript to do that ? And the server, how it can return data to the client ?
You can Use jquery AJAX for send request and get a response and Update an element or part of the page you can read more about it in :
W3schools
or :
jquery.com
AJAX function I use for PHP project:(Just for example)
$.ajax({
type: "POST",
url: Url,
data: InfoData, // data if you want to send for example InfoData={dataName: variable} or you can set this = '' if you don't want to send data
datatype: "html",
success: function(result) {
console.log(result);
}
});

Is there a way to use javascript variable as part of PHP SQL page?

I have a variable within a laravel PHP page, held within Javascript. I currently print / output this as:
${data.id}
I now want to connect to PHPMyAdmin to check to see if the ID is within a table. However, I realise I can't use the ID number in PHP - as this is done on the server side and JS on the client side. A little stuck.
Unfortunately, I'm on a shared hosting package so node.js isn't a solution I can use.
Any help would be great! I think I can use AJAX, but unsure on how this would look.
here the AJAX sample.
$.ajax({
method: "POST",
url: "some.php",
data: { id: data.id}
})
.done(function( response) {
console.log(response);
//TODO:process your response here if receive response from php file.
});

Why is python requests getting different results than Ajax

I am trying to write a Python script that logs into website for me and downloads my messages. I'm using the the "requests" library and succesfully able to log in with a session
The website uses js/Ajax to download the actual messages client side after the messages page has been loaded, and uses pagination to achive an infinite list of messages effect.
The messages page url is in the form of https://website.com/messages. and that page contains an Ajax call that retrives the messsages like this:
$.ajax({
url: '/messages?mailbox=' + mailbox + optional params
}).done(function(data) {
urlLazyLoading = data.next_page_url;
$.each(data, function(i, v) {
//from this point on, data for each message can be
//accessed using the v object as such:
//v.sender, v.date, v.last_message, etc
//and the <ul> element is populated with '<li>'s
But when I try to access the same url in python (after I've loggedin) as such:
session.get('https://website.com/messages?mailbox=inbox')
instead of getting a json response with the messages data, I get the same/original messages page.
the only parameter passed to ajax in the code above is url, so by defult it should be just making a simple GET request, which is what I'm doing.
Is it possible that maybe somewhere else in the code ajax is being set up to default to POST or have some other non-default settings?
or is the server somehow detecting that one request is coming from ajax and the other from sessions? maybe using user-agent?
Got it!
Ajax sends a header value by default:
{'X-Requested-With': 'XMLHttpRequest'}
I added that in and viola
headers = {'X-Requested-With': 'XMLHttpRequest'}
r = s.get("https://website.com/messages?mailbox=inbox",headers=headers)

How to get all the repositories for a particular user?

I am trying the extract the various repository names for a particular user and populate a combobox on a html page. I am able to extract only one repository name. How can I get all the names? The code I have so far:
$.ajax({
url:"https://api.bitbucket.org/2.0/repositories/abc",
username: "palld#bdbd.in",
password: "abcdef123456",
success: function(data){
console.log(data);
},
error: function(){
console.log("Connection did not go through");
},
type: 'GET'
});
Writing similar code in Java and python worked and I was able to see all the repository names. Any help would be appreciated.
The result is as below:
Edit:
It appears that Bitbucket will send you some data even when you are not authenticated to their API. I suspect that there is no authentication request sent to you by the API and jQuery simply does not send the username and password when not asked for.
This code explicitly send the authentication data to the API:
var reposUsername = "OWNER_OF_REPOS";
var authUsername = "YOUR_USERNAME";
var authPassword = "YOUR_PASSWORD";
$.ajax({
url:"https://api.bitbucket.org/2.0/repositories/" + reposUsername,
success: function(data){
console.log(data);
},
error: function(){
console.log("Connection did not go through");
},
type: 'GET',
headers: {
'Authorization': "Basic " + btoa(authUsername + ":" + authPassword)
}
});
(I'm 100% sure that this code works as I've tested it a few minutes ago with my own Bitbucket account).
Note: please be aware that storing your credentials in the code is something you should not do, so think twice before you release your code/application the the public.
Obsolete answer:
Just look at the documentation Bitbucket provides to you (although, the example response looks kind of weird).
Assuming your data object is already a JSON parsed object, you should be able to access your respositiories like this (Edit: code adjusted the the provided screenshot):
data.values
Parse the JSON response. If it works from Python or Java then it must be something to do with the way you are handling the response in JavaScript. Perhaps you are not parsing it, which you need to do to convert it into a proper JSON object containing all the elements you want.
success: function(data){
console.log(JSON.parse(data));
},

Error when calling webservice with jquery

I have read a lot about jquery and i have a webservice where i convert a companyID to the real companyName. Now i want to call that webservice with jquery or javascript. The webservice is on host http://webservice/service.asmx en i'm working on http://tlmos. I don't work and i always get an error
Here is my code:
<script type="text/javascript" src="http://kmosvi24/_layouts/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var test = "KBEACDNV";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://webservice/service.asmx/getCompanyByCompanyID",
data: "{'sCompanyID:' + 'test'}",
dataType: "json",
succes:function(response){ alert("good"); },
error: function(response) { alert("Uh oh"); },
complete: function(response) { alert("" + response); }
});
</script>
Can someone help me?
thx
Umm.. you spelled success wrong on line 11
.. and you probably want to format your data as
data: "sCompanyID=test"
Take a quick pass through the jQuery API page on this one to verify you are passing the parameters that your service expects. It looks like you are expecting a SOAP packet with an ASMX service, and jQuery is more suited to hitting a restful service generated from an ASHX file or WCF service.
You can make a request to a different server, but only if the call uses GET. Since all you do is lookup anyway, a GET request should be fine.
As some othe people have pointed out you cannot call a webservice on another domain, however as you are using ASP.NET, you can write a raw HTTP handler (normally with an .ashx extension to proxy your request from client to server.) Which you'd place on your "timos" server
so in your ashx file you can write something along the lines of...
public void ProcessRequest (HttpContext context)
{
XmlDocument wsResponse = new XmlDocument();
string url = "http://webservice/service.asmx/getCompanyByCompanyID?CompanyID="
context.Request.Form["CompanyID"].ToString()
wsResponse.Load(url);
string XMLDocument = wsResponse.InnerXml;
context.Response.ContentType = "text/xml";
context.Response.Write(XMLDocument);
}
Hope this helps.
You can't do AJAX calls to hosts other than your own. If you really have to do this make a call to your own server and use a simple proxy to redirect to the domain you need.
You could do this for example by using a ProxyPass-directive in your webserver:
ProxyPass /service/ http://webservice/service.asmx
ProxyPassReverse /service/ http://webservice/service.asmx
Then you can issue an AJAX-request to /service/getCompanyByCompanyID and it will be proxied to the correct URL.
I don't think you are using the data parameter right, usually it's a key-value pair like:
data: {sCompanyID: 'test'}
I believe that they way you are using it will result in jQuery attempting to post to http://webservice/service.asmx/getCompanyByCompanyID?sCompanyID:blah
Also aren't .NET web services SOAP? I don't think jQuery can parse that...
edit: Nevermind, didn't realize you were passing these as json data. Thanks commenters!
In order to run your web-services from Jquery, you should use either WCF or just usual web services, but you should add [ScriptMethod] to your service's method and [ScriptService] to your webservice description.
Wow wow
just noticed that you're trying to call the service from one host to another... that one won't work. service should be hosted on the same domain as the page where it's being called from.
as a reply to Jeff's answer, correct way to format data is data: {key: "value"}
With jQuery Ajax Requests you need to use the following format when defining the variables to be sent in the request:
data: "variableName=variableContent",
You wrote:
data: "{'sCompanyID:' + 'test'}"
This won't work for two reasons:
- You have included curly brackets which don't need to be there.
- You have used a semi-colon,":", instead of an equals sign,"=".
So long as you change these it should work.
P.S I only just realized that Jeff Fritz has already given you the right answer. His answer is spot on!

Categories