In my site, I have different pages with different types of form. I want to submit all the forms to 'process.php' using Ajax and process data at 'process.php'. But, I am unable to catch the form name or form submit name at 'process.php' while posting data through Ajax.
Could anyone please tell me how could I know which form has been submitted from 'process.php'?
I tried the following steps that failed:
CHANGE PASSWORD.PHP
<form id="change_password_form" action="process.php" method="POST">
<input type="password" id="current_password" name="current_password" />
<input type="password" id="new_password" name="new_password" />
<input type="password" id="confirm_password" name="confirm_password" />
<input type="submit" value="change password" id="submit" name="change_password" />
</form>
AJAX.JS
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url:"process.php",
type:"POST",
data:$("#change_password_form").serialize(),
success: function(data){
$("#msg").html(data);
},
});
});
PROCESS.PHP
if(isset($_POST['change_password'])){
echo("<p>".$_POST['current_password']."</p>");
echo("<p>".$_POST['new_password']."</p>");
echo("<p>".$_POST['confirm_password']."</p>");
}
The above code does not echo anything because Ajax did not post INPUT >TYPE >SUBMIT .
Here is what it posted:
Array
(
[current_password] => 12345
[new_password] => 123
[confirm_password] => 12
)
How would I make Ajax post the input>type>submit ? or else, if I am posting multiple form data to same PHP file for processing, how would I make PHP understand which form has been submitted?
Your reply would be highly appreciated.
Did I detail too much? My apology is before you.
You can assign a name to each form.
For example, in the above form,
<form name="change_password_form" id="change_password_form" action="process.php" method="POST">
<input type="password" id="current_password" name="current_password" />
<input type="password" id="new_password" name="new_password" />
<input type="password" id="confirm_password" name="confirm_password" />
<input type="submit" value="change password" id="submit" name="change_password" />
</form>
Then in your javascript,
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url:"process.php",
type:"POST",
data:$("#change_password_form").serialize()+'&form_name='+$("#change_password_form").attr("name"),
success: function(data){
$("#msg").html(data);
},
});
});
And in your PHP file,
if(isset($_POST['form_name'])){
if($_POST['form_name']=="change_password_form")
{
echo("<p>".$_POST['current_password']."</p>");
echo("<p>".$_POST['new_password']."</p>");
echo("<p>".$_POST['confirm_password']."</p>");
}
//Similarly, add your other form processing code.
}
Note : You should never trust user input. $_POST elements can be easily manipulated. Always escape the input before inserting it into a database, or use PDO.
A good and more reliable way do pass extra info in a form is by using the hidden input type. If you add to your form something like
<input type="hidden" name="form_type" value="change_password" />
And change your PHP into
if(isset($_POST['form_type']) && $_POST['form_type'] == 'change_password')
Then you can get your data and any other information you might want to pass along with other hidden fields.
I would use a hidden field with desired name and that will be definitely posted and capture the same on PHP page and process my conditions.
It is easiest/quickest approach, I think.
I would use something like this:
url:"process.php?form=change_password",
Then in process you know which form was submitted with $_GET['form'];
Related
I have run into a bit of a problem recently.
I am still in the process of learning JS so i couldn't figure this one out alone :( .
I have been getting a lot of spam recently through this form I have on a website and I cant seem to fix it...I tried a few solutions with Jquery and JS but I cant get it to work so I just deleted them.
100% of the spam I receive has a link in the message so I would like to make it so the submit button stay disabled unless 2 conditions are met :
The message must contain more than 12 characters
The textarea must NOT contain any link
here is the html i got :
<form action="php/contact.php" method="POST">
<h1>Contact-us</h1>
<input type="text" id="name" name="name" placeholder="Name" required>
<input type="email" id="email" name="email" placeholder="Email" required>
<input type="tel" id="tel" name="tel" placeholder="Phone" required>
<input type="text" class="subject" id="subject" name="subject" placeholder="Subject" required>
<textarea name="message" id="messag" class="textarea" placeholder="Message" required></textarea>
<button type="submit" class="submit" name="submit" id="disabled">Send</button>
</form>
also I am preventing a page refresh using ajax, and any JS i tried would conflict or be ignored by the ajax request, here is the code :
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/php/contact.php',
data: $('form').serialize(),
success: function () {
alert('Your message was sent successfully');
}
});
});
});
a fairly simple form i think...any help is greatly appreciated !
Thanks
You can probably check to make sure that the body of the message sent by the user doesn't have a link using a regex to match links.
The regex I used was taken directly from the answer of this question: Detect URLs in text with JavaScript
$("#my-form").on("submit", ev => {
ev.preventDefault();
const urlRegex = /(https?:\/\/[^\s]+)/gm;
const message = $("#message-field").val();
if(! message.match(urlRegex)){
// you can send the message with ajax
// ...ajax code
alert("message sent");
} else {
// there was a link in the message, give a warning or something
alert("link detected");
}
});
<!-- Import JQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="my-form">
<p>Message: </p>
<textarea name="message" id="message-field" placeholder="Try adding text like https://google.com" style="width:200px;height:100px;"></textarea/>
<br/>
<button>submit</button>
</form>
This is only a front-end solution. Make sure you also have a check on the backend because javascript based validation can be easily bypassed.
Message length and filtering links still leave a number of options for spammers to breach your form.
You can quite easily implement a Google Recaptcha or implement your own in whatever backend language you're using.
The conditions you're looking for in your OP are,
if ($('#messag').html().length > 12)
if ($('#messag').html.indexOf('href') >= 0)
Cheers
I made a form in html that makes login request to this website: https://kintai.jinjer.biz/sign_in
Here is my html code:
<form method="post" class= "login-form" action="https://kintai.jinjer.biz/v1/sign_in">
<input class="login-input--text jcompanycode" id="company_code" name="company_code" type="hidden" value="1234" />
<input class="jemail login-input--text" name="email" type="hidden" value="1234" />
<input class="jpassword login-input--text" name="password" placeholder="パスワード" type="hidden" value="1234" />
<input type="submit" value= "submit" id= "submit" />
</form>
I wrote a javascript code to prevent redirect on submission of form.
<script>
$(document).ready(function(){
$('.login-form').submit(function(e){
e.preventDefault();
});
});
I want to prevent redirect on form submission.
However, when i add the javascript, the post request doesn't work.
Any ideas to send form data to server while remaining on current html page?
Note: please don't tell me to use ajax or jquery to make the login request.
I tried making post request using ajx/jquery a lot of times but it doesn't work. Perhaps due to same origin policy I presume.
HTML form redirect page is its feature.
If you want to avoid, please try to using formdata with ajax.
MDN FromData
MDN Fetch with FormData
I have seen hundreds of these questions on stackoverflow and none really explain in detail how its done step by step. I am still learning JS but I cannot find anything that shows step by step tutorial style how this is done. There are dozens, upwards of 70 questions asking how to implement this and most have no best answer chosen. So this is a generic form - using PHP $_POST that I would love to get some help with. I want to have this form refresh two divs. Here is my code;
<!-- This <form> for ENTERING measurements and SELECTING picture -->
<form name="log_data" method="post" action="" enctype="multipart/form-data" />
<input type="hidden" name="user_id" value="<?php echo $current_user->ID; ?>"/>
<input type="number" step="any" class="form-control" placeholder="Enter Length" name="length" value="" required="required"/>
<br />
<input type="number" step="any" class="form-control" placeholder="Enter Ground" name="ground" value="" required="required"/>
<br />
<label for="date">Week Of:</label>
<input type="date" name="date" class="form-control" value="" required="required"/>
<br />
<input type="file" name="file" class="form-control" value="" />
<br />
<input type="submit" name="submit" value="submit" class="btn btn-primary"/>
</form>
<?php
$post_id = NULL;
if(!empty($_FILES['file']['name'])) { //new code to fix string error
foreach ($_FILES as $file => $array)
{
$newupload = insert_attachment($file,$post_id);
}
} else { $newupload = '';} //new code to fix string error
if (isset($_POST['submit']))
{
$wpdb->insert(wp_jo_plugin_options, array (
'user_id' => $_POST['user_id'],
'length' => $_POST['length'],
'ground' => $_POST['ground'],
'date' => $_POST['date'],
'file' => $newupload
) );
}
?>
the form needs to update two divs. One named results_chart, and one named data_table. The idea is to do this without a page refresh. I currently use wordpress, and this is for a plugin. Additionally, I use ISSET to post, without a separate file. That may need to change based on what I read about implementing this feature.
The $newupload controls inserting a pictures post-id into a separate table. I am aware of the lack of validation in place, I am not to sure how to implement that so instead I took the JS validation approach.
NetTuts+ has a good tutorial as well:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
$.ajax({
async: false,
type: 'post',
dataType: 'json',
url: '/locationOfYourPHPFunction',
data: $('#form').serializeArray(),
success: function(__data) {
$('#firstDiv').html(__data.firstThing);
$('#secondDiv').html(__data.secondThing);
};
});
You must have your function that that is giving the post data to the AJAX call return json_encode($data); so that the format will be output properly. This assumes you have an associative array with the keys firstThing and secondThing. (e.g. array('first' => '', 'second' => '');).
async tell the AJAX function to not run these in unison, depending on what you're running this can make things not work properly.
.serializeArray() looks for your form that contains the id form and sends that data. Data can be appended to that array by pushing in JSON format: ({country: 'DE', time: '12:00'});
All this can be placed in a js function to be called onclick="" or through a jQuery().click();.
If you are using a framework like CakePHP make sure to place $this->autoRender = false; at the beginning of the function, otherwise you will run into problems.
EDIT: I missed the using wordpress part, all is still relevant but I would highly recommend to stop using wordpress. It's terribly unsecure, poorly structured, bloated and unfriendly for SEO & ones' sanity.
I want to 'postpone' (stop the default behavior of the form) sending the user to 'http://www.othersite.com' until server side validation is finished on check.php
Once complete, send the user on their way to 'http://www.othersite.com'. I can send to the validation page no problem, but I need to validate then send to another website. Say I have a form like this
$(document).ready(function(){
$('#sendbutton').click(function(){
$('#error').empty();
$('#send').ajaxForm(function (data, textStatus) {
$('#error').append(data);
});
});
});
<form id="send" name="send" method="post" action="http://www.othersite.com/index.htm">
<input type="text" id="fname" name="fname" />
<input type="text" id="lname" name="lname" />
<input type="text" id="address" name="address" />
<input type="text" id="city" name="city" />
<input type="text" id="state" name="state" />
<button id="sendbutton">Submit</button>
</form>
<div id="error"></div>
And server side validation occurs on check.php
check field inputs here on check.php
if not correct
echo error message
if successful echo "validation_ok"
If the returned data is 'validation_ok' then send the user to complete form submission on 'http://www.othersite.com'
Sounds like an excellent opportunity for AJAX (as implied by #nachito). Otherwise, you can also:
Have check.php render the form initially and do the client-side validation.
Have the form's action to check.php (effectively posting back to itself).
On successful validation, set the form's action to www.othersite.com and echo a javascript literal value (or a hidden input, if you're so inclined) flagging an "auto-submit".
You could also use jQuery to change the form's action, rather than flip it in check.php.
Once the flag is detected, submit the form on the document.ready event.
Failing that, you could also have check.php post to www.othersite.com if server-side validation has passed using cURL (and without, just google "HTTP POST from PHP, without cURL").
$(document).ready(function() {
$('#send').submit(function() {
$('#error').empty();
// Post the form to your validation page
$.post('/check.php', $(this).serialize(), function (data) {
// If validation failed, stop submission
if (data != 'validation_ok') {
$('#error').append(data);
// Prevent submission.
return false;
}
});
});
});
When defining a <form>, it is possible to set the action tag.
How can I set it to null (#), so that it will not actually change the page?
A bit hard to understand but I think what you want is this:
<form action="#">
<!-- code here -->
</form>
A <form> tag without an action attribute will send the data to the page it was submitted from.
You only need to use the action attribute if you're sending the form data to a different page.
<form method="GET">
<input type="text" size="10" name="input" value="default">
<input type="submit" value="Submit">
</form>
(NOTE: This does not work on the file:/// protocol handler.)
For anyone else reading this, it is usually better to have your input or button object return false; when it's clicked. This will make sure the form doesn't follow an action, and instead stays on the page. It would be similar conceptually to what is being asked, as in it will stay on the current page.
This let's you handle submit options in javascript.
Here's an example of how you would submit an email address to your API route, alerting the user what is returned by the API call:
HTML:
<form>
<input type="text" name="email">
<button onclick="do_something(); return false;"
</form>
JAVASCRIPT:
var do_something = function(){
$.ajax({
url: "http://myapi.com/route",
type: 'POST',
data: $('form').serialize(),
context: document.body
}).done(function(data) {
alert(data);
});
};
You can set form action to null in the following way. This worked for me.
< form action ='' >
Try This
<form method="dialog">
<input type="text" size="10" name="input" value="default">
<input type="submit" value="Submit">
</form>