Do a jQuery/ajax POST on form submit - javascript

I have an html form like this:
<form action="myServer.com/test.php" method="post">
...
</form>
When the form is submitted, the user should be redirected to myServer.com/test.php and ofc send the post data to the script. BUT at the same time (or before), I want to post the same POST data to another script "myServer.com/test2.php".
$.post("myServer.com/test2.php", variableWithTheFormPOSTData);
I tried to attach an EventListener to the form submit, but that doesn't seem to work, maybe the jquery post cant be submitted fast enough before the redirection?
I hope you can help me. :(

Whenever you use a method with onsubmit, make sure it returns true, otherwise it won't submit.

use a button as your submit button sothat the form doesnt get posted at the same time you click on it. And trigger the ajax function to post the data indirectly to the second page.
<form name="myform" action="myServer.com/test.php" method="post">
...
<button onclick="doIndirectPost();"></button>
</form>
and in the success callback of ajax posting function trigger your form post
function doIndirectPost() {
//initialize variableWithTheFormPOSTData here
$.post("myServer.com/test2.php", variableWithTheFormPOSTData,function(success,error) {
//ajax post is completed now we trigger the form post to test.php
document.myform.submit();
});
}

You can do it using ajax itself, which will avoid reloading the page
<form id="form1">
.....
<input type="text" name="email"/> <!--Example input text box-->
<input type="button" id="submit"/>
</form>
and the jquery code
$("#submit").click(function()
{
$.post("myServer.com/test2.php", $("#form1").serialize());//$("#form1).serialize() will get the data in the form automatically
$.post("myServer.com/test.php", $("#form1").serialize());
});
.serialize() will automatically serialize the data from the form that is to be posted
in your server side page use this
<?php
parse_str($_POST['serialize'], $data);
$name = $data["email"]
// do your code
?>
Hope this helps,Thank you

Related

Form firing javascript onsubmit but not passing values from form POST

I am using the form action POST to submit a form and javascript onsubmit to redirect a user to the thank you page. The POST was working prior to adding the javascript code, and once that was implemented the form is redirecting correctly but not calling up the POST page to process the values anymore.
<form action="https://www.website.com/leads.php" method="post" id="bm-form" class="form-style" novalidate="novalidate">
<!--form fields here-->
<div>
<input class="btn theme-btn" value="Process" type="submit">
</div>
</form>
Javascript
<script type="text/javascript">
window.onload=function() {
document.getElementById("bm-form").onsubmit=function() {
window.location.replace("https://www.website.com/thank-you.html");
return false;
}
}
</script>
The JavaScript is cancelling the normal behaviour of the form submission and telling the browser to load a different page instead.
To redirect to a thank-you page, have https://www.website.com/leads.php return a 302 status and a Location HTTP response header. Don't involve JavaScript.
You should do the redirect from inside the php code (leads.php) server side not from javascript. The javascript logic you have added it overwrites the form submit and post is never done, just the redirect is.

POST value in PHP when submitting onChange Javascript

I'm trying to submit an image file using javascript onChange, the thing is I don't know the value of the submitted POST form, and how can I set a custom POST value. Here is a simple example:
HTML:
<form id="form" action="upload.php" method="post">
<input type="file" id="file" name="image">
</form>
Javascript:
document.getElementById("file").onchange = function() {
document.getElementById("form").submit();
}
So after I submit the form I can only get the value $_POST['image']. Usually when receiving POST I check for the value of the submit button which I create uniquely for each form such as, updateform, updateclient. Now I want to do the same by creating custom messages, one page will send 'uploadclientimage' the other will say 'uploadshopimage' and so on. This way the upload.php file can process the status to decide what to do next.
In upload.php I want to do like this:
if(isset($_POST['uploadclientimage']))
{//Save in client uploads folder and update client info}
else if(isset($_POST['uploadshopimage']))
{//Save in shops uploads folder and update shop info}
else header("Location: login.php");
using submit button does that easily <input type="submit" name="uploadclientimage">
How can I do something like that with onChange form submit???
Just add a hidden field in the form. For example:
<input type="hidden" name="uploadclientimage" value="">

Stopping a refresh/redirect on form submission

I have an app that wants to redirect after submitting and I would like to freeze it after clicking submit. The app is a multiform that has an end slide that I would like the animation to trigger and then freeze it from redirect/refresh.
<form id="form" class="msform hs-form stacked hs-custom-form" accept-charset="UTF-8"
action="confidential-url" enctype="multipart/form-data" method="POST" novalidate="">
<!-- form stuff -->
</form>
$(".submit").click(function () {
return true;
e.preventDefault();
});
I have tried adding onSubmit="return false" to my <form> tag as well as various e.preventDefault(); methods. All of them will either:
• Cause it to prevent the redirect/refresh but not update the fields in the DB
• Update fields but page will still redirect
EDIT:
After trying to do this in AJAX I found out that I was being blocked out from the external URL, thanks to to r4phG for helping me figure it out!
Is your submission causing your redirection/ refresh ?
If you have to submit your form to update fields in your database, you'll have to submit your form. But if you don't want to refresh all your page, you should think of using Ajax, as your submission will not refresh your page
Example from jquery ajax doc :
$("#form").submit(function() {
$.ajax({
url:'confidential-url',
method:'POST' ,
data:$(this).serialize() //submits your form information
});
return false; // prevent the server form submission
});
jQuery ajax documentation

PHP doesn't process the form

I'm having a little problem here.
I have a form with a jQuery that disables the submit input when the form is submited.The problem is: I use PHP to process the data when the input submit is clicked. But apparently the button is being disabled first, then PHP can not perform the processing. I need to find a way to prevent this, take a look in the code snippets:
<form class='send' action='{$_SERVER['PHP_SELF']}' method='post'>
<!--Form data-->
<input type='submit' name='finish' value='Send'/>
</form>
jQuery function to disable:
$('.send').on('submit', function()
{
$(this).find('input[type="submit"]').prop("disabled", true);
});
And then the PHP code to process:
if(isset($_POST['finish']))
{
//Do things
}
As I said, the PHP don't process the form because JS disabled the button to prevent multiple submitions. How to process PHP before disable the button? Thanks!
Since you are disabling the submit button it will not get send over to to server in the $_POST variable so your code doesn't work, as you have said.
Another way to do what you are looking for is to create a hidden HTML input
<input type="hidden" name="form">
Then when you check if the form is send, you will use
if(isset($_POST['form']))
{
//Do things
}
You can solve it easily changing your submit button by a simple button:
<form class='send' action='{$_SERVER['PHP_SELF']}' method='post'>
<!--Form data-->
<input type='button' name='finish' value='Send'/>
</form>
$('input[name="finish"]', '.send').on('click', function(){
$(this).prop('disabled', true);
$('.send').submit();
});

Why is POST method sending form data twice to the server?

Why is this form sending data twice? Also, the second time, the data is "undefined".
The form:
<form action="/loginPage" method="POST" >
Username: <input type="text" id="username"> <br><br>
Password: <input type="text" id="password"> <br><br>
<input type="submit" id="Login" value="Login" >
</form>
The client-side script:
$(document).ready(function(){
$('form').submit(function(event){
//event.preventDefault(); This prevents from sending data twice, but then the page doesn't redirect to "Hi, <username>"
$.post("/loginPage",{username: $("#username").val(),password: $("#password").val()}, function(data){
;
});
});
});
The server-side script:
app.post('/loginPage', function(req, res) {
var username = req.body.username;
console.log("Now, "+username);
res.send("Hi, "+username);
//res.sendFile(__dirname + '/lobby.html');
});
This is the output I get when I run this code:
Hi, Sho
Hi, undefined
I'm stuck at this one for the past whole day. Please help me.
When you submit the first time, jQuery fires and sends the POST through AJAX. The second submit is the HTML form firing. You want to stop the HTML form from submitting and use your custom handler instead.
The reason you're getting undefined is because you don't have name attributes on the inputs in your form.
You should return false; in your jQuery handler to prevent the form from firing, and do something with the response data as well.
Your code is posting via ajax, but it's not preventing the ordinary browser action of posting the form. You don't get any parameters from the normal form post because your <input> elements don't have "name" attributes.
You can return false; from the "submit" handler to prevent the normal form submission.
Try this instead: return false in your form onsubmit to prevent it from submitting twice
<form action="/loginPage" method="POST" onSubmit="return false" >

Categories