How can I make a post request (after validating some user input) to a webhook without redirecting the user to the webhook url?
Tis kind of request is generally done using AJAX.
If you are using jQuery, you should look at .post() method. See an exemple of it:
$.post( "/url.html", function( data ) {
# action on request response
});
If you are using raw javascript (without js libs), you should look at XMLHttpRequest() object. Example of use:
var post = function() {
var url = "http://www.example.com";
var request = new XMLHttpRequest();
request.open( "POST", url, true);
request.send(null);
}
Using this approach of request you will not be redirect, like the common case of HTML submitions.
Related
I'm currently refactoring some of my previous code to move away from jQuery's AJAX function towards XMLHttpRequest in vanilla JS. From my understanding, the following code blocks should be identical. However, while the jQuery version works, XMLHttpRequest doesn't. If successful, you should see an array returned by PHP in the network tab in dev tools.
jQuery
$("#submit").click(() => {
$.ajax({
type: "POST",
url: "http://arig.asuscomm.com/mn/PHP/submitNames.php",
data: {
first: "Hi!"
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="submit">
Submit
</button>
Vanilla JS
function send() {
var data = {
"first": "Hi!"
};
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://arig.asuscomm.com/mn/PHP/submitNames.php", true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.send(JSON.stringify(data))
}
<button id="submit" onclick="send()">
Submit
</button>
Note that my server is running locally, but I will try to keep it up until my question is answered. And, because my server doesn't have HTTPS quite yet, you might need to send the request from an HTTP source. Thanks!!!
Edit: I'm using code found here.
jQuery encodes data using the application/x-www-form-urlencoded data format, not JSON.
You can encode data in that format using the URLSearchParams object.
const data = {
"first": "Hi!"
};
const params = new URLSearchParams();
Object.entries(data).forEach(
([key, value]) => params.append(key, value)
);
const encoded_data = params.toString();
console.log(encoded_data);
Problem is with your server not the data itself as I'm getting the response (it's just an empty array)
You can either use the same method for sending data like with ajax and use form-data for which I'm getting the same response as with Ajax
function send() {
var formData = new FormData();
formData.append("first", "Hi!");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://arig.asuscomm.com/mn/PHP/submitNames.php", true);
xhr.send(formData)
}
Or you will need to handle json input on your server
I am looking for a way to send the following POST request using only plain Javascript:
Let's say the above HTTP request was a variable, would it maybe be possible to send that as a request and gather the result? Or is it a better way to send this POST request using Javascript?
Thanks in advance for all answers.
Something like this should work as long as it is your own api that you are calling to?
var post = function() {
var url = "http://www.example.com";
var request = new XMLHttpRequest();
request.open( "POST", url, true);
request.send(null);
}
Heres my email sending function:
function send() {
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe";
var message_name = "defender_send_message";
var data = {};
data.value1 = document.getElementById('textBox').value;
data.value2 = localStorage.getItem("AdminsEmail");
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
console.log("Message Sent");
}
}
}
xmlhttp.open('POST', url, true);
xmlhttp.responseType = 'json';
xmlhttp.send(new FormData(data));
}
I wanted to create an email sending function with only pure js, not jquery or anything. I get the following errors when i click send:
(ignore the first error i fixed that already)
I had a jquery function that worked (but i had to get rid of it):
var message = localStorage.getItem("Message");
console.log(message + localStorage.getItem("AdminsEmail"));
var key = "dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe"; // << YOUR KEY HERE
var message_name = "defender_send_message"; // << YOUR MESSAGE NAME HERE
var url = "https://maker.ifttt.com/trigger/" + message_name + "/with/key/" + key;
$.ajax({
url: url,
data: {value1: message,
value2: localStorage.getItem("AdminsEmail")},
dataType: "jsonp",
complete: function(jqXHR, textStatus) {
console.log("Message Sent");
}
});
why would this work and my other function not?
EDIT 2 : Since it seems the endpoint doesn't actually return JSON, I think your original jQuery code wasn't correct either. You need to do more research into this iftt.com platform and how to use it. From what I can tell, it's meant to be used in a mobile app, not in the browser- it would be a normal POST XHR then, and CORS doesn't apply to mobile apps. They have this page for testing the endpoint- notice that it gives you an example using curl, a command-line tool, where again CORS doesn't apply. So I think you need to rethink things, this service is not designed to be used from a browser, like you are trying to do.
EDIT: since it turns out you are actually trying to use JSONP and not a plain XHR, all you need to do is implement that without jQuery- create a script tag with the server's URL and add a URL parameter to define your callback function to handle the data. This answer should give you the solution.
In your case the code might look like this :
http://www.codeply.com/go/bp/VRCwId81Vr
function foo(data)
{
// do stuff with JSON
console.log(data)
}
var script = document.createElement('script');
script.src = "https://maker.ifttt.com/trigger/defender_send_message/with/key/"+
"dJdJekCVAFIqvUJ13DEczZjgIh_4MyeIGEHz2GBYKFe?callback=foo";
document.getElementsByTagName('head')[0].appendChild(script);
Note that this doesn't work for me(but with your code, you would get Message sent printed to the console, so maybe you thought it was working?)- the response isn't JSON. Most likely the endpoint isn't actually meant to be used for JSONP?
My answer below only applies if you are trying to do a regular XHR in a browser without JSONP.
This happens because of the Cross Origin Resource Sharing policy of your browser. Your code is hosted at localhost, and it is trying to access a resource hosted at maker.ifttt.com through an XmlHttpRequest. In order to allow this to happen, the server at maker.ifttt.com would need to be configured to allow access from the localhost origin. Presumably you can not make that change as you don't control that server.
In your case, the best solution would be to make the request to maker.ifttt.com through your own server- CORS doesn't apply for server-to-server requests. Send the XmlHttpRequest to your server, take the data regarding the email from the request URL parameters, and then make the request to maker.ifttt.com using that data.
We can create XMLHttpRequest object and then can use it later for another request like :-
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function(){ } // something
xhr.send(null);
There will be a search box and when we enter something in it, it sends an ajax request, but if the user entered more so we will cancel that previous ajax request and create new.
If we want to send another ajax request by same object, we can create an xhr object for that search box to be sure that there will be only one ajax request at a time so if we need to send another request, will will do like :-
xhr.abort()
xhr.open()
xhr.send(null);
I'm using jQuery for portability across browsers, and I want something similar to the above, meaning an XHR (or wrapped XHR) object, that can be used again and again and can also cancel previous request.
How we can do that in jQuery ?
Try using a function to return $.get() , .abort()
var current;
var request = function(url) {current = $.get(url); return current};
request(url); current.abort();
request(url).then(function(data) {
// do stuff
}, function err(jqxhr, textStatus, errorThrown) {
// do stuff with error
});
I am working on a web crawler that can integrate with our partner portals and submit post requests to make bid changes.
The trouble is that the crawler runs in an environment which cannot execute jQuery, only native Javascript.
I have determined that the following AJAX code successfully sends the post request:
$.ajax({
type: "POST",
url: "http://acp.example.com/campaigns/122828",
data: "data-string"
});
Is there a way to translate the above statement into native javascript so that the crawler can execute it?
UPDATE
When executing hex494D49's native Javascript below, I am receiving a "NetworkError: 404 Not Found - http://acp.fyber.com/campaigns/122828" message.
However, when I execute the original AJAX code in firebug, it successfully sends the POST request.
Any idea why the same url would return a 404 error using native Javascript as opposed to AJAX?
Thanks
Sending AJAX request using POST method
var xhr = new XMLHttpRequest();
var url = "url";
var data = "email=hey#mail.com&password=101010";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
};
xhr.send(data);
Sending AJAX request using GET method
xhr = new XMLHttpRequest();
var url = "url?email=hey#mail.com&password=101010";
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
}
xhr.send();
To avoid unexpected requests to the server, it's a good practice to use encodeURIComponent() method on any user-entered parameters that will be passed as part of a URI.