Connect HTTP POST request to an onclick using JavaScript - javascript

I am trying to make an HTTP POST request using javascript and connecting it to an onclick event.
For example, if someone clicks on a button then make a HTTP POST request to http://www.example.com/?test=test1&test2=test2. It just needs to hit the url and can close the connection.
I've messed around in python and got this to work.
import urllib2
def hitURL():
urllib2.urlopen("http://www.example.com/?test=test1&test2=test2").close
hitURL()
I have read about some ways to make HTTP requests using JavaScript in this thread JavaScript post request like a form submit, but think it's overkill for what I need to do.
Is it possible to just say something like this:
<button onclick=POST(http://www.example.com/?test=test1&test2=test2)>hello</button>
Or build it in to an event listener.
I know that is not anything real but I am just looking for a simple solution that non-technical people can use, follow directions, and implement.
I honestly doubt there is something that simple out there but still any recommendations would be appreciated.

You need to use XMLHttpRequest (see MDN).
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.onload = // something
document.getElementById("your_button's_ID").addEventListener("click",
function() {xhr.send(data)},
false
);

If you can include the JQuery library, then I'd suggest you look in to the jQuery .ajax() method (http://api.jquery.com/jQuery.ajax/):
$.ajax("http://www.example.com/", {
type: 'POST',
data: {
test: 'test1',
test2: 'test2'
}
})

Related

Are there different styles of ajax?

I'm kind of new to using ajax but I've been largely successful. Most of my ajax calls look very similar to this:
function saveQueryProf(){
var currentDate = new Date();
var date=currentDate.getDate()+'/'+(currentDate.getMonth()+1)+'/'+currentDate.getFullYear();
$.ajax({
type: "POST",
url: "API.php",
data: { method: "createQueryProfile",
prof_name: $('#nameTxt').val(),
prof_SQL: $('#sqlTxt').val(),
date: date
},
datatype: "json"
}).done(function(returnresult) {
})
}
Using the $.ajax({ method. However, any time I see someone using "ajax" on youtube or other sites, their code looks more like this:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
I realize that these are doing different things, but what is the difference in these 2? And when I'm looking for answers online how could I find an answer that is more along the lines of the first style?
The first example, using $.ajax(), is specific to jQuery. It's a lot simpler than the built-in Javascript API, XMLHttpRequest. XMLHttpRequest doesn't require any external libraries to use, though it's more difficult. $.ajax() relies on XMLHttpRequest.
Your code requires the jQuery library to work (that's where $ and $.ajax come from). Their code is using XMLHttpRequest directly, which is built in to JavaScript, so it doesn't need any libraries. If you want your AJAX code to depend on jQuery, then just include it as a search term.
I saw that the question was already answered, but I think that more information can be added.
In your first example you are using jQuery ($.ajax call). You will need to add this library to your website in order to make it work. The easiest way is to add a tag with jQuery CND to your website.
The second example is using vanilla JavaScript, the XMLHttpRequest. It has more complex syntax (a strange mixture of upper and lowercase characters), but you don't need to add anything to the site. It will do the work, and once you are used to the syntax it might be all you need.
Third option that I have used for AJAX request is the fetch() method. Like XMLHttpRequest it is build in in the JavaScript language. fetch() has very simple syntax and allows easy use of promises. You might need promises if you will be making requests that will not return data immediately. Here's more information on fetch:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Fourth option that I've used for AJAX is Axios library. If you are including jQuery only for AJAX requests Axios is probably better choice. More read on Axios: https://github.com/axios/axios
If you want to dig a bit more on the differences and pros/cons between fetch() and XMLHttpRequest take a look on this thread:
Fetch API vs XMLHttpRequest
Shortly Ajax is an extension method which defined in JQuery for factory class XmlHttpRequest.

iron-request doesn't make more than one request

I am working with the Polymer 2 library. Whenever I try to make multiple requests using iron-request, the code only ever seems to make a POST request on the first initiation. Any subsequent requests seem to be ignored, even when data that is set to be sent to the server is different from the initial request.
I've written a small example in this Plunker: https://plnkr.co/edit/cozVKUdQ2q2SV46rcCTL?p=preview
I created a iron-request and a button element to initiate the request like so:
<paper-button on-click="save" class="green">Send</paper-button>
...
<iron-request id="xhr"></iron-request>
The save function is setup to take text from a textarea and send that off to a server.
save() {
var response = this.$.xhr.send({
url: "https://httpbin.org/post",
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
body: {
content: this.inputdata
},
method: "POST"
});
var poly = this;
this.$.xhr.completes.then(function(data) {
console.log("finished");
poly.$.responsetext.innerHTML = data.response;
})
The code in question is in the "element1.html" file. If you try sending different text payloads, only the first request will be send. (You can see in the response box that the form "content" field stays the same.)
Any idea what is going on? I'm thinking that I would have to create new iron-request elements everytime I need to make a new request... but that doesn't sound like a very elegant solution.
As you suspected, iron-request has been built to send a single HTTP request. I had a quick look at the its implementation. The send method will actually just return null and not do anything, if the request has a status that is larger 0 than, which will be the case if you have used it before.
While you could create a new iron-request element for each request, it is not elegant (as you said yourself). Instead, you could work with iron-ajax. You can find some instructions on its documentation page.
Your <iron-request> can be rewritten as this.
<iron-ajax id="xhr" url="https://httpbin.org/post" content-type="application/x-www-form-urlencoded" method="POST" body="[[inputdata]]" on-response="onXhrSuccess"></iron-ajax>
Your save function,
save() {
this.$.xhr.generateRequest();
}
onXhrSuccess(event, request) {
console.log("finished");
poly.$.responsetext.innerHTML = event.detail.response;
}

Javascript: How did I get here? (Viewing data sent by server, non-AJAX.)

I've got a React-based app that works like this: The user makes a request for "foo", the server returns basic page info (applicable to all pages on the site), and when the client receives this (DOMContentLoaded), it does an AJAX call for the internal details "foo" and renders that.
But is it possible, if I send the data on the first request, to skip the AJAX call? (I tried this previously but was very new to React, which is how I came up with the current scheme. It's come up again because now I'm handling previously saved items.) So, I'm in my DOMContentLoaded listener, and I can see (in the Browser|Network|Response area of Chrome) all the data that has been sent by the server. It's everything I need, and it's right there, but I can't find a way to access it in Javascript.
The searches I've done have almost all turned up AJAX requests. (I am using JQuery, if that helps.) Obviously I can handle loading saved data using the same gag I'm currently using, and maybe that's a an all-around better approach.
So, once again, the question is: Is it possible to look at the response from a non-AJAX place? If it is possible, is it advisable?
Update: Let me walk through an example scenario.
The user goes to "/foo".
The server response is {:some "json"}.
In the Javascript onReady, I can do this:
console.log(window.location);
and I'll see "/foo". But can I see {:some "json"}? And how? Contrast with the AJAX call version:
The user goes to "/foo".
The server response is nothing (i.e., a 200 but no body).
The Javascript onReady has:
$.ajax({
url: "/foo/data"
type: "GET",
success: function (req) {...} //req has {:some data} in it!
So, when I make an AJAX call, I get the request. Is there any way to get that {:some data} on a non-AJAX call? This doesn't work, but I could see something like:
x = window.response();
or
x = Response.last();
Neither of those things exist, of course. I hope that clarifies what I'm looking for.
You could drop a script tag on your server-rendered page that includes a global var accessible by your script bundle. e.g.,
<script>
var myGlobalVar = { ... server data ... } <!-- // note: this is rendered raw by your server
</script>
<script src="myScriptBundle.min.js"></script>
Or, alternatively you could look into server-side rendering, which is possible with React. Check out the implementation in Redux: http://redux.js.org/docs/recipes/ServerRendering.html

Run (JS) function if server responded something specific

On one of my pages I have "tracking.php" that makes a request to another server, and if tracking is sucessful in Firebug Net panel I see the response trackingFinished();
Is there an easy way (built-in function) to accomplish something like this:
If ("tracking.php" responded "trackingFinished();") { *redirect*... }
Javascript? PHP? Anything?
The thing is, this "tracking.php" also creates browser and flash cookies (and then responds with trackingfinished(); when they're created). I had a JS that did something like this:
If ("MyCookie" is created) { *redirect*... }
It worked, but if you had MyCookie in your browser from before, it just redirected before "track.php" had the time to create new cookies, so old cookies didn't get overwritten (which I'm trying to accomplish) before the redirection...
The solution I have in mind is to redirect after trackingFinished(); was responded...
I think the better form in javascript to make request from one page to another, without leaving the first is with the ajax method, and this one jQuery make it so easy, you only have to use the ajax function, and pass a little parameters:
$.post(url, {parameter1: parameter1value, param2: param2value})
And you can concatenate some actions:
$.post().done(function(){}).fail(function(){})
And isntead of the ajax, you can use the $.post that is more easy, and use the done and fail method to evaluate the succes of the information recived
As mentioned above, AJAX is the best way to communicate between pages like this. Here's an example of an AJAX request to your track.php page. It uses the success function to see if track.php returned 'trackingFinished();'. If it did then it redirects the page 'redirect.php':
$.ajax({
url: "track.php",
dataType: "text",
success: function(data){
if(data === 'trackingFinished();'){
document.location = 'redirect.php';
}
}
});
The example uses JQuery.

Reuse XMLHttpRequest object or create a new one?

I searched stackoverflow but got contradictory answers:
Why should I reuse XmlHttpRequest objects?
Ajax-intensive page: reuse the same XMLHttpRequest object or create new one every time?
Also, there's a recommendation on w3schools.com :
If you have more than one AJAX task on your website, you should create
ONE standard function for creating the XMLHttpRequest object, and call
this for each AJAX task.
Why this recommendation? I'm instead using a global XMLHttpRequest object on my page for handling all Ajax tasks.
You misunderstood W3School's recommendation. I'll highlight the relevant part:
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.
It says that you use one AJAX function to fetch requests. This function will deal with the inconsistencies between IE and other browsers. XMLHttpRequest in standard-compliant browsers, and ActiveXObject in IE.
I recommend to use multiple XHR objects. With one global xhr object, your application can only deal with one request at a given time. It's also error-prone (eg. XMLHttpRequest launches multiple times without initiating the onreadystatechange function).
W3schools meant something like:
function createXHR() {
try {
return new XMLHttpRequest();
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return new ActiveXObject("Msxml2.XMLHTTP");
}
}
}
var xhr = createXHR();
xhr.open('get', '/test', true);
xhr.send();
Although it's better to create a function which handles requests, such as jQuery.ajax.
It is best to use different objects for each XHR you are making. Even if there's a way of doing it, avoid it! There's no problem with creating new object for each request. If you are worried about memory leak or something of that sort, do not worry, they are all properly GC`ed.
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.
It actually means that you have one function that creates a new object and returns it every time you call it. It something like:
function newXHR(){
return a new instance of XHR();
}
The recommendation you highlight is saying you should have one FUNCTION which handles AJAX, rather than specifically one XMLHTTPRequest object.
I would use a different one for each question.
The common argument against this concerns the overheads involved in setting up XHRs. However this is going to be pretty much negligible in any site that uses AJAX as it was intended (i.e. not as a labouring substitute for web sockets) and, in any case, much of the same overheads would apply with re-using an XHR. You'd still have to open the connection, fire it, attach listeners etc.
Browsers vary in terms of how many connection gateways are allowed at a given time, so it's up to the browser to control what XHRs can do what. In other words, you don't have to worry about managing this aspect.
Finally, there's nothing stopping you manually deleting the XHRs after you've used them, provided they are deletable (properties of an object rather than variables).
From MDN Web Docs:
If the httpRequest variable is used globally, competing functions
calling makeRequest() can overwrite each other, causing a race
condition. Declaring the httpRequest variable local to a closure
containing the AJAX functions avoids this.
Source: https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
I am using a pattern like this
var xhrSendBuffer = new Object();
function sendData(url, model) {
if (!xhrSendBuffer[url]) {
let xhr = new XMLHttpRequest();
xhr.onloadend = xhrDone;
xhr.error=xhrError;
xhr.onabort = xhrAbborted;
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhrSendBuffer[url] = xhr;
}
xhrSendBuffer[url].send(JSON.stringify(model));
}
function xhrDone(e) {
console.log(e);
}
function xhrError(e) {
console.error(e);
}
function xhrAbborted(e) {
console.warn(e);
}
if I end up producing a DOS on my own site because I send to the same url multiple requests I could use the xhr.readyState to see how busy it is before sending the next request, however I have yet to encounter this as an issue.

Categories

Resources