Sending two post request with html form and AJAX at once - javascript

I´m trying to make two POST requests to different sites:
One from the action attribute form tag , and the otherone using AJAX (specifically XMLHttpRequest) on the onsubmit event.
Here is a snippet I made that IS WORKING on chrome browser (it sends first the ajax POST and then the form post) , but IT DOESN´T work in firefox (it only sends the POST action form).
Form action POST request
<form name="form_log" method="POST" action="Site1.php" onsubmit="return validate(this);">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="Submit" value="Enter">
</form>
AJAX POST request
function validate(){
if(document.form_log.username.value == ""){
alert('User name is empty');
return false;
}
if(document.form_log.password.value == ""){
alert('Password is empty');
return false;
}
else{
var user=document.getElementsByName('username')[0].value;
var pass=document.getElementsByName('password')[0].value;
var parameters=`username=${user}&password=${pass}&Submit=Enter`;
var url = "http://Site2.php";
var xhttp = new XMLHttpRequest();
xhttp.open('POST',url,true);
xhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhttp.onreadystatechange = ()=>{
if(xhttp.DONE && xhttp.status == 200){
console.log("SENT!");
}
}
xhttp.send(parameters);
}
}
Am I doing something wrong, and this behaviour is due to a Firefox restriction?
Thanks in advance !!
I tried this snippet on chrome and works OK! , but I can´t make to send both POST request on Firefox (it only sends the POST action request).

Related

Send PHP POST using Javascript AJAX

My data is not inserting into database, I get a blank response from the console log and network. I'm kinda lost my javascript source code is mix with other stack overflow answers as well as my PHP code.
<form id="requestForm">
<input type="text" name="fName" id="name">
<input type="text" name="fAddress" id="address">
<input type="text" name="fComment" id="comment">
<input type="submit" value="Submit" name="nameSubmit">
</form>
<script>
document.querySelector('#requestForm').addEventListener('submit', postRequest);
function postRequest(e){
e.preventDefault();
const params = {
fName: document.querySelector('#name').value,
fAddress: document.querySelector('#address').value,
fComment: document.querySelector('#comment').value,
};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'addRequest.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function(){
console.log(this.responseText);
}
xhr.send(params);
}
</script>
</body>
Here's the PHP code:
require_once 'Database.php';
var_dump($_POST); // returns `array(0) {}`
if (isset($_POST['nameSubmit'])) {
var_dump($_POST); // shows no response
$r = $_POST['fName'];
$o = $_POST['fAddress'];
$p = $_POST['fComment'];
$query = "INSERT INTO user_request(name, address, comment) VALUES(?,?,?)";
$stmt = $db->prepare($query);
$insert = $stmt->execute([$r, $o, $p]);
if($insert){
echo 'Success';
}else{
echo 'Error';
}
}
I believe the post parameter nameSubmit does not exsist.
Use the var_dump() function for dump all $_POST
From my prespective, the only parameter given was
fName
fAddress
fComment
Why not check for request method instead?
This is better than checking if a variable exsisted or not.
You can do the checks for required parameter later after you're sure this is a POST request.
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// Do whatever you want when POST request came in
}
UPDATE :
Here is the answer you wanted!
<form id="requestForm">
<input type="text" name="fName" id="name">
<input type="text" name="fAddress" id="address">
<input type="text" name="fComment" id="comment">
<button onclick="sendData();" type="button">Submit</button>
</form>
<div id="testdiv"></div>
<script>
function sendData(){
var data = new FormData();
data.append('fName', document.getElementById("name").value);
data.append('fAddress', document.getElementById("address").value);
data.append('fComment', document.getElementById("comment").value);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test.php', true);
xhr.onload = function () {
if(xhr.status !== 200){
// Server does not return HTTP 200 (OK) response.
// Whatever you wanted to do when server responded with another code than 200 (OK)
return; // return is important because the code below is NOT executed if the response is other than HTTP 200 (OK)
}
// Whatever you wanted to do when server responded with HTTP 200 (OK)
// I've added a DIV with id of testdiv to show the result there
document.getElementById("testdiv").innerHTML = this.responseText;
};
xhr.send(data);
}
</script>
</body>
The PHP code :
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
var_dump($_POST);
}else{
header('HTTP/1.0 403 Forbidden');
}
?>
To add another field, add another data.append function below data var.
The submit button MUST BE CLICKED. To allow the use of enter, add an event listener for it!.
What it looks like on my end : https://image.ibb.co/gfSHZK/image.png
Hope this is the answer you wanted.
Two issues:
1.) Params not sent properly/at all because lack of serialization. When you use form content-type your params object need to be in a particular format name=value&name2=value2. So to facilitate that you need to transform your ojbect using something like:
function getReadyToSend(object) {
var objList = [];
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
objList.push(encodeURI(prop + '=' + object[prop]));
}
}
return objList.join("&");
}
So your sending becomes: xhr.send(getReadyToSend(params));
2) Your php is expecting the submit button to be sent. if (isset($_POST['nameSubmit'])) {
You don't have a variable being sent called nameSubmit you can fix this by either including it or check that each variable is set instead. I would suggest the latter that way you can error handle should 1 or more are not passed.
Suggestion: Update your onload to check status:
if (xhr.status === 200)
{
console.log(xhr.responseText);
}
else if(xhr.status !== 200)
{
console.log('Request failed. Returned status of ', xhr.status);
}
Example fiddle: http://jsfiddle.net/qofrhemp/1/, open network tab and inspect the call you will now see the params in form data for the call that fires when submit clicked.

AJAX Request Body Empty (No jQuery)

I am trying to solve this problem without using jQuery so that I can have a better understanding of how things work.
I am sending an AJAX request to a node server with a JSON object. The server can receive the request and respond but the request body is always empty. I have tried setting the request header to 'application/json' but for some reason this changes the form submission to POST the parameters to the URL, rather than use the Javascript function. If anyone could tell me why that is happening as well it would be much appreciated.
Form
<form onsubmit="sendEmail(); return false;">
<input type="text" name="fromEmail">
<input type="text" name="subject">
<textarea name="message" rows="14"></textarea>
<input type="submit" value="SEND">
</form>
Email Function
function sendEmail() {
var emailContent = JSON.stringify(
{
email: $('input[name=fromEmail]').val(),
subject: $('input[name=subject]').val(),
message: $('textarea[name=message]').val()
}
);
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.open('POST','/message', true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
alert(httpRequest.responseText);
}
}
httpRequest.send(emailContent);
}
Node JS Routing
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
// set body parser
app.use(bodyParser.json());
// Process email form
app.post('/message', function(req,res) {
console.log('Request received by email path.');
console.log(req.body);
res.send('{"success": true}')
console.log('Response sent.')
});
I think I understood your problem, what you need is to call the function sendEmail() without doing a postback. Well, for this you will nead a regular html button instead of a form submit. Forms are used to execute server requests to an specific url and generate another postback.
You have two options:
1) Do a client side call using a button and an ajax request (XMLHttpRequest):
<input type="text" name="fromEmail">
<input type="text" name="subject">
<textarea name="message" rows="14"></textarea>
<input type="submit" value="SEND">
<button type="button" onclick="sendEmail()">Send</button>
2) Use a form submit and call the service directly form the form. The parameters will be taken from the form and will be sent in the request:
<form action="/message" method="post">
<input type="text" name="fromEmail">
<input type="text" name="subject">
<textarea name="message" rows="14"></textarea>
<input type="submit" value="SEND">
</form>
Then in the server side you can access the data using the names you gave to the fields:
fromEmail = req["fromEmail"]
If you are trying to send json response, you need to set the content type of response as json.
res.setHeader('Content-Type', 'application/json');
You can try this:
httpRequest.open('POST','/message', true);
httpRequest.setRequestHeader("Content-Type","application/json");
httpRequest.send(emailContent);
Reference:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

Collapsing a div element that contains a form using javascript

I have a user sign up form that i am trying to collapse once the user has successfully signed up (and replaced with something like 'please check your email to activate account') . I am having problems collapsing the form (and all the elements inside it) after receiving the correct response from an ajax request. I just cannot figure out where my code is incorrect. Please can someone advise?
Ajax request:
// Create XMLHttprequest
var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
//Need to get a response after processing the submitted data.
if(xmlhttp.responseText == 'Sign up success'){
window.scrollTo(0,0);
document.getElementById('signup_main').style.display='none';
}else{
document.getElementById("status").innerHTML = xmlhttp.responseText;
}
}
}
function adduser()
{
$("#inp").hide(0);
$("#main").html("User added successfully");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div id="inp">
<p> A Div with content or form</p>
<input type="button" value='add' onclick='adduser();'>
</div>
</div>

Submitting a form using AJAX

I've a JSP page which includes a checkbox, so when i try to submit the form using the conventional javascript way of document.forms[0].submit(); the form gets refreshed and the checkbox values are not getting retained.
Can anybody help me on how to send the form value using only AJAX. I don't need the way to send using JQuery.
This is the code I had used for sending using form submit:
function relatedAER(){
......
document.forms[0].literatureSelected.value = litNO + "&";
document.forms[0].opCode.value = "relatedAER";
document.forms[0].target='_self';
document.forms[0].action="<%=request.getContextPath()%>/litaer.do?selected="+selected;
document.forms[0].submit();
}
I hope next time, you'll put some effort, into creating even a simple code, and showing us instead of asking for a script.
Now, that bieng said: This will submit a username to a php file, called fetch.php
HTML
<input type='text' name='user' id='user' /><br/>
<input type='submit' name='submit' onclick='check()' />
<div id='output'></div>
Ajax:
function check(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('output').innerHTML = xmlhttp.responseText;
}
}
get_user = document.getElementById('user').value;
param = "name="+get_user;
xmlhttp.open('POST','fetch.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
</script>

Making sure request will be completed after changing page

The problem is: I have custom analtyics engine that sends log using JavaScript. I want to send log after user submits a form. The log is send using AJAX. Now the problem is, form submission is not AJAX, it is normal request that refreshes the page.
I already learned that you can force the script executions even if client aborted connection
Does php execution stop after a user leaves the page?
What I want to learn is how to be sure that server recives request and headers if form is submited almost instantly after AJAX call is send?
var url = "...";
var my_form = document.getElementsByTagName("form")[0];
var request_received = false;
my_form.addEventListener("submit", function(e) {
if (!request_received) {
e.preventDefault(); // prevent the form from submitting
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState >= 2 && !request_received) {
request_received = true;
my_form.submit(); // submit the form only if the request has been received
}
};
xhr.open("GET", url, true);
xhr.send();
return false;
}
}, false);
Lets say that this is your form with submit button:
<form id="myForm" action="/myAction.html" method="POST">
<!-- form inputs -->
<input type="submit" value="submit me!" />
</form>
With JavaScript you can bind to the submit event of your form, do your ajax call and then return true to continue submiting your form to the server:
<script type="text/javascript">
document.getElementById('myForm').addEventListener('submit', function(e){
// do your ajax call here and when you finish, return true from
// this function (in the ajax success callback)
return true;
});
</script>

Categories

Resources