jQuery/js submit form on click - php

I can't submit the form after disable the submit button.
I make a jquery code to prevent multiple submit it's work but the form doesn't send the POST request.
jQuery:
$(document).ready(function() {
var enblereg = function(e) {
$(e).removeAttr("disabled");
}
$("#goRegister").click(function() {
$(this.form).submit();
var reg = this;
$('#reg').submit();
$(this).attr("disabled", true);
setTimeout(function() { enblereg(reg) }, 2000);
});
});
php:
<?php if (isset($_POST['goRegister'])) { echo "send";} ?>
<form action="?" method="POST" id="reg">
<h6>Full Name: <?php echo $fnamerr; ?></h6>
<input type="text" name="fname" value="<?php echo $fullname;?>">
<h6>Email: <?php echo $emailerr; ?></h6>
<input type="text" name="email" value="<?php echo $email;?>">
<h6>Re-enter Email: <?php echo $aemailerr; ?></h6>
<input type="text" name="aemail" value="<?php echo $aemail;?>">
<h6>password: <?php echo $passworderr; ?></h6>
<input type="password" name="password">
<h6>Re-enter password: <?php echo $apassworderr; ?></h6>
<input type="password" name="apassword">
<h6>Birthday: <?php echo $bdayerr;?></h6>
<?php include ("/incs/birthdayinc.php");?>
<h6>Gender: <?php echo $gendererr; ?></h6>
<input type="radio" name="gender" value="female"><font size="1"><b>Female</b></font>
<input type="radio" name="gender" value="male"><font size="1"><b>Male</b></font><br>
<input type="submit" name="goRegister" id="goRegister" value="Register">
</form>
without the jQuery the post work, I tried to solve it with "ONCLICK":
this.form.submit() - doesn't work
what should I need to add in jQuery to submit the form before disable the submit button ?

I think the jQuery code for the process would be like this
$(this.form).submit();
This would submit the form for you. If it doesn't actually trigger the event. Then you can capture the form and submit it directly using the id of it.
id="reg"
So, it would be
$('#reg').submit();

Do this... The form has id of #reg. So simply use $('#reg').submit();
$("#goRegister").click(function() {
var reg = this;
$('#reg').submit();
$(this).attr("disabled", true);
setTimeout(function() { enblereg(reg) }, 2000);
});
EDIT
Updated for ajax submit
$("#goRegister").click(function() {
var reg = $(this);
var form = $('#reg').serialize();
var url = "Whereveryouareposting.php";
//Submit ajax form
$.post(url,form,function(data){
//This is where you could send back error messages or success from the server
// To dictate wether to hide the button, or display errors.
// Ie On success....do this...
$(this).attr("disabled", true);
setTimeout(function() { enblereg(reg) }, 2000);
// On error, send a message packet with the errors, and loop through it to attach error
//messages to fields
});
});

Related

Using multiple forms to insert data to DB using Jquery & PHP without refreshing the page

I have working code for posting data to DB using PHP and Jquery without refreshing the page.
But however, I could only use 1 form with the given code, if I'm to add another form with different variables both the forms getting submitted.
My code goes as:
index:
Query starts
$countlikes = 1;
$countdislikes = 1;
<form data-id='<?= $countlikes?>' action="likeinsert" method="post" id="myform<?= $countlikes?>">
<input type="hidden" id="fid<?= $countlikes?>" name="fid" value="<?php echo $f_id; ?>" />
<input type="hidden" id="uid<?= $countlikes?>" name="uid" value="<?php echo $u_id; ?>" />
<button style="border:none; background:transparent;" data-toggle="tooltip" data-placement="right" title="Like" class="up"><i class="fa fa-thumbs-o-up"></i><?= $f_likes; ?></button>
</form>
<form data-id='<?= $countdislikes?>' action="dislikeinsert" method="post" id="myform<?= $countdislikes?>">
<input type="hidden" id="fid<?= $countdislikes?>" name="fid" value="<?php echo $f_id; ?>" />
<input type="hidden" id="uid<?= $countdislikes?>" name="uid" value="<?php echo $u_id; ?>" />
<button style="border:none; background:transparent;" data-placement="right" data-html="true" title="DisLike" class="down"><i class="fa fa-thumbs-o-down"></i><?= $f_dislikes; ?></button>
</form>
$countlikes ++;
$countdislikes ++;
Query Ends
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script>
$(document).on('submit','form',function(e){
e.preventDefault();
let id = $(this).data('id');
$.post(
'likeinsert.php',
{
fid: $("#fid"+id).val(),
uid: $("#uid"+id).val()
},
function(result){
if(result == "success"){
$("#result").val("Values Inserted");
} else {
$("#result").val("Error");
}
}
);
});
</script>
<script>
$(document).on('submit','form',function(e){
e.preventDefault();
let id = $(this).data('id');
$.post(
'dislikeinsert.php',
{
fiid: $("#fid"+id).val(),
uiid: $("#uid"+id).val()
},
function(result){
if(result == "success"){
$("#result").val("Values Inserted");
} else {
$("#result").val("Error");
}
}
);
});
</script>
When I to click on any form button, both forms are getting submitted.
It is happening, because you are adding two submit event listeners on both forms, so when you submit one form, both jquery scripts are getting executed.
To prevent this, add form's unique ids to your event listeners (in your case they are myform1 and myform1, but you should make them unique), somewhat like this:
$(document).on('submit','form#dislikesForm',function(e){
request to dislikeinsert.php ...
$(document).on('submit','form#likesForm',function(e){
request to likeinsert.php...

Submit page but dont refresh

I'm working on a footer generator.
Which looks like this:
This "preview" button has 2 functions function 1 is posting the values that the user entered in the black box like this :
and the second function is to show me a button(which is hidden by default with css) called "button-form-control-generate" with jquery like this:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Now here comes my problem:
If i click on preview it refreshes the page.. so if i click on preview it shows the hidden button for like 1 second then it refreshes the page and the button goes back to hidden. So i tried removing the type="submit" but if i do that it wont post the entered data like it did in image 2 it will show the hidden button though, but because the submit type is gone it wont post the entered data on the black box.
Here is my code:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate"name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
The jquery:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Already tried prevent default but if i do this the users entered data doesnt show in the preview box. Looks like preventdefault stops this bit from working:
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
I heard this is possible with ajax, but i have no idea how in this case i already tried to look on the internet..
if you have a type="submit" inside a form, it will submit the form by default. Try to use <input type="button" instead. Then you can use ajax on the button action, that will run without refreshing the page.
Here's an example of how to use ajax:
function sendAjax() {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
$(".result").html(JSON.stringify(data))
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="button" onclick="sendAjax()" value="callAjax" />
<div class="result"></div>
</form>
Add
return false;
to your jQuery-function at the end. With this you can avoid the submit.
Then you need to add an ajax-function, which sends the data from your form to the php-script you already use.
This is just an example:
$.ajax({
url: "YOUR-PHP-SCRIPT"
}).done(function (content) {
// ADD HERE YOUR LOGIC FOR THE RESPONSE
}).fail(function (jqXHR, textStatus) {
alert('failed: ' + textStatus);
});
So you have to do $.ajax post request to the php. Something like this:
<script>
$('.form-control').click(function() {
$.post(url, {data}, function(result) {
footerPreview();
}, 'json');
});
</script>
So footerPreview will be called when your php returns result.
//add in javascript
function isPostBack()
{
return document.referrer.indexOf(document.location.href) > -1;
}
if (isPostBack()){
$("button.form-control-generate").show();
}
you can create an index.php:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" id="tm">
<option val=""></option>
<option val="©">©</option>
<option val="™">™</option>
<option val="®">®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" id="cn" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate" name= "submit" id="generate">
Generate
</button>
</form>
<div class="output" id="output">
</div>
<script type="text/javascript">
$('#generate').on('click', function(e){
e.preventDefault();
var companyname = $('#cn').val();
var trademark = $('#tm').val();
$.ajax({
url: 'process.php',
type: 'post'.
data: {'company':companyname,'trademark':trademark},
dataType: 'JSON',
success: function(data){
$('#output').append("<div id='footer_date'>"+data.trademark + " " + data.date + " " + data.company + " </div>");
},
error: function(){
alert('Error During AJAX');
}
});
})
</script>
and the process.php:
<?php
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["company"];
$date = date("Y");
$array = array(
'trademark' => $trademark,
'company' => $company,
'date' => $date
);
echo json_encode($array);
?>
Be sure that the index.php and the process.php will be under the same folder.. ex.public_html/index.php and public_html/process.php

Load php form on submit

I have an admin panel where I have an option to add a user into database. I made a script so when you click the Add User link it will load the form where you can introduce the user infos. The thing is, I want to load in the same page the code that is run when the form is submited.
Here's the js function that loads the file:
$( ".add" ).on( "click", function() {
$(".add-user-content").load("add-user-form.php")
});
and here's the php form
<form id="formID" action="add-user-form.php" method="post">
<p>Add Blog Administrator:</p>
<input type="text" name="admin-user" value="" placeholder="username" id="username"><br>
<input type="password" name="admin-pass" value="" placeholder="password" id="password"><br>
<input type="email" name="admin-email" value="" placeholder="email" id="email"><br>
<input type="submit" name="add-user" value="Add User">
</form>
<?php
include '../config.php';
$tbl_name="blog_members"; // Table name
if(isset($_POST['add-user'])){
$adminuser = $_POST['admin-user'];
$adminpass = $_POST['admin-pass'];
$adminemail = $_POST['admin-email'];
$sql="INSERT INTO $tbl_name (username,password,email) VALUES('$adminuser','$adminpass','$adminemail')";
$result=mysqli_query($link,$sql);
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
}
?>
Maybe I was not that clear, I want this code
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
to be outputted in the same page where I loaded the form because right now it takes me to the add-user-form.php when I click the submit button.
Thanks for your help!
if you do this the code will be redirected on post to your page:
<form name="formID" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
you should add a validation so it doest show the form if you receive $_POST['add-user']
You have to submit your for via ajax.
Alternatively you don't need to load form html, just hide the form and on add user button click show the form.
Check this code. Hope that helps you :-
// Add User Button
<div class="color-quantity not-selected-inputs">
<button class="add_user">Add User</button>
</div>
// Append form here
<div class="add_user_form"></div>
// for posting response here
<div class="result"></div>
Script for processing form and appending user form
<script>
$(function(){
$( ".add_user" ).on( "click", function() {
$(".add_user_form").load("form.php")
});
$(document).on("submit","#formID", function(ev){
var data = $(this).serialize();
console.log(data);
$.post('handler.php',data,function(resposne){
$('.result').html(resposne);
});
ev.preventDefault();
});
});
</script>
form.php
<form id="formID" action="" method="post">
<p>Add Blog Administrator:</p>
<input type="text" name="admin-user" value="" placeholder="username" id="username"><br>
<input type="password" name="admin-pass" value="" placeholder="password" id="password"><br>
<input type="email" name="admin-email" value="" placeholder="email" id="email"><br>
<input type="submit" name="add-user" value="Add User">
</form>
handler.php
<?php
include '../config.php';
$tbl_name="blog_members"; // Table name
if(isset($_POST['add-user'])){
$adminuser = $_POST['admin-user'];
$adminpass = $_POST['admin-pass'];
$adminemail = $_POST['admin-email'];
$sql="INSERT INTO $tbl_name (username,password,email) VALUES('$adminuser','$adminpass','$adminemail')";
$result=mysqli_query($link,$sql);
if($result){
echo '<p class="user-added">User has been added successfully!</p>';
echo '<a class="view-users" href="view-users.php">View Users</a>';
}else {
echo "Error: ".$sql."<br>".mysqli_error($link);
}
die;
}
?>
What you are looking for is to submit the form using AJAX rather than HTML.
Using the answer Submit a form using jQuery by tvanfosson
I would replace your
<input type="submit" name="add-user" value="Add User">
with
<button id="add-user-submit">Add User</button>
and then register an onClick-handler with
$( "#add-user-submit" ).on( "click", function() {
$.ajax({
url: 'add-user-form.php',
type: 'post',
data: $('form#formID').serialize(),
success: function(data) {
$(".add-user-content").append(data);
}
});
});
to add the actual submit functionality.

jquery $.post fails to send data on second request

I have a bunch of records from a database that I am displaying on a page. Each record has their own form with an update and delete button. I'm using JQuery ajax to send the data to a PHP page to process the form.
The script works fine the first time I push any one of the buttons on any of the forms, but when I push another button on any of the forms (or even the same button on the same form) the ajax request doesn't send any of the data to the PHP page.
Code I'm using to output data on page:
<?php
foreach($records as $data) {
?>
<form>
<input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<input type="submit" name="update" value="Update" />
<input type="submit" name="delete" value="Delete" />
</form>
<?php
}
Javascript:
$(document).ready(function() {
var buttonName;
$('input[type=submit]').click('click', function() {
buttonName = $(this).attr('name');
});
$('form').on('submit', function(e) {
e.preventDefault();
var values = $(this).serializeArray();
console.log(values);
if(buttonName == 'delete') {
var message = confirm('Are you sure you want to delete this record?\n\n You can\'t get it back once you do.');
} else {
message = true;
}
if(message) {
$.post('submit/raw_et.php', {et: values[0].value, token: values[1].value, id: values[2].value, button: buttonName}, function(r) {
console.log(r);
});
}
});
});
PHP Snippet:
echo $_POST['button'];
echo $_POST['et'];
echo $_POST['id'];
The "values" variable in the javascript always has the correct data, but the ajax fails to send any data after the first time a button is pushed and the results return blank.
I don't understand why it won't send the data. Am I missing something really easy, or is it something more complicated?
Edit:
I've taken out the tables in the html, but still get the same results.
you are developing in a completely wrong pattern, instead of defining form inside tr, use record id and register event for clicking buttons:
<?php
foreach($records as $data) {
?>
<tr>
<td><input type="number" name="et" step="0.01" value="<?php echo $data->et; ?>" /></td>
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="hidden" name="id" value="<?php echo $data->et_id; ?>"/>
<td><a class='edit' meta-id="<?php echo $record; ?>">edit</a></td>
<td><a class='delete' meta-id="<?php echo $record; ?>">delete</a></td>
</tr>
<?php
}
?>
And now, try to register all buttons onclick for delete and edit.
$(".edit").click(function() {
var record = $(this).attr("meta-id");
$.post("edit uri" , {record : record , otherparam: valueofit} , function(result) {
alert(result);
});
});
$(".delete").click(function() {
var record = $(this).attr("meta-id");
$.post("delte uri" , {record : record} , function(result) {
alert(result);
});
});
You can expand the concept as you want, for less adding class to buttons or so on.

Ajax Data Posting

Hello im trying to implement an ajax invitation script which will let the user to invite his/her friends to that event. I use the mostly same javascript in the other parts of the website and they work perfect, but in this case, it doesn't work, i'm sure that the problem persists because of the javascript part, because as i said, i use the nearly exact script and it works perfect, when i post the data, it doesn't send the email, my mail function works good ( in other pages i use the same without ajax and it works ) but i think the javascript part can't post the data in this case.
By the way there is not any problem with getting the values in the hidden parts.
Hope you can help.
the javascript part :
<script type=\"text/javascript\">
$(document).ready(function() {
$('.error').hide(); //Hide error messages
$('#MainResult').hide(); //we will hide this right now
$(\"#button\").click(function() { //User clicks on Submit button
var js_name = $(\"#name\").val();
var js_message = $(\"#message\").val();
var js_username = $(\"#username\").val();
var js_useremail = $(\"#useremail\").val();
var js_eventname = $(\"#eventname\").val();
if(js_name==\"\"){
$(\"#nameLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
if( js_message==\"\"){
$(\"#messageLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
var myData = 'postName='+ js_name + '&postMessage=' + js_message + '&username=' + js_username + '&useremail=' + js_useremail + '&eventname=' + js_eventname;
jQuery.ajax({
type: \"POST\",
url: \"invite.php\",
dataType:\"html\",
data:myData,
success:function(response){
$(\"#MainResult\").html('<fieldset class=\"response\">'+response+'</fieldset>');
$(\"#MainResult\").slideDown(\"slow\"); //show Result
$(\"#MainContent\").hide(); //hide form div slowly
},
error:function (xhr, ajaxOptions, thrownError){
$(\"#ErrResults\").html(thrownError);
}
});
return false;
});
$(\"#gobacknow\").live(\"click\", function() {
$(\"#MainResult\").hide(); //show Result
$(\"#MainContent\").slideDown(\"slow\"); //hide form div slowly
//clear all fields to empty state
$(\"#name\").val('');$(\"#message\").val('');
});
$(\"#OpenContact\").live(\"click\", function() {
$(\"#form-wapper\").toggle(\"slow\");
});
});
</script>
the html part:
<div id="form-wapper">
<div id="form-inner">
<div id="ErrResults"><!-- retrive Error Here --></div>
<div id="MainResult"><!-- retrive response Here --></div>
<div id="MainContent">
<fieldset>
<form id="MyContactForm" name="MyContactForm" method="post" action="">
<label for="name" id="nameLb">Email : <span class="error" style="font-size:10px; color:red;">Error.</span></label>
<input type="text" name="name" id="name" />
<label for="message" name="messageLb" id="messageLb">Message : <span class="error" style="font-size:10px; color:red;">Error.</span></label><textarea style="resize:vertical;" name="message" id="message" ></textarea>
<input type="hidden" name="username" id="username" value="<?php echo get_username($userid); ?>">
<input type="hidden" name="useremail" id="useremail" value="<?php echo get_email($userid); ?>">
<input type="hidden" name="eventname" id="eventname" value="<?php echo $eventname; ?>">
<br><button id="button">Send</button>
</form>
</fieldset>
</div>
<div style="clear:both;"></div>
</div>
invite php file :
$postName = filter_var($_POST["postName"], FILTER_SANITIZE_STRING);
$postMessage = filter_var($_POST["postMessage"], FILTER_SANITIZE_STRING);
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
$useremail = filter_var($_POST["useremail"], FILTER_SANITIZE_STRING);
$eventname= filter_var($_POST["eventname"], FILTER_SANITIZE_STRING);
invite($useremail, $postMessage , $username, $eventname, $postName); // this is a functipon that i use, it works in other cases, but not working in here
Rather than trying to debug that javascript, here is a much much easier / cleaner way to do this for the javascript AJAX post:
$.post('invite.php',$('#MyContactForm').serialize(),function(data){
if(data.success){
// all your on success stuff here
alert('success!');
}else{
// show error messages
alert(data.e);
}
},'json');
For your PHP part, echo a JSON response array, eg:
$data['success']=false;
$data['e']='Some error';
echo json_encode($data);

Categories