I have struggled for quite some time now with this but can figure out whats wrong.
I have an index file where I'm loading the contend with ajax (in this case a form stored in add_admin.php). I have a form which loads just perfectly in a div after clicking a menu item(calling the ajax function - this part works). But if I want to submit that form with jQuery afterwords using the
$(".loginform").submit(function(e) {});
it doesn't get called. I'm suspecting the reason is that the form was not present on the page at the time it was loaded. If I move the form directly to the index page, the function works perfectly.
$(document).ready(function () {
$(".loginform").submit(function(e) {
data = $("#loginform").serialize();
password = document.getElementById("user_pass").value;
passtosubmit=hex_sha512(password);
data += "&pass=" + encodeURIComponent(passtosubmit);
password="";
//$.post("modules/process/process_add_admin.php", data);
//alert(data);return false;
$.ajax({
type: "POST",
url: "/modules/process/process_add_admin.php",
data: data,
success: function() {
$('#main_panel_container').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png'/>");
});
}
});
return false;
});
});
The form to submit
add_admin.php
<div id="contact_form">
<form name="loginform" class="loginform" id="loginform" action="#" method="post">
<label><strong>Username</strong></label><input type="text" name="username" id="user_login" size="28" class="input" />
<br />
<label><strong>Password</strong></label><input type="password" name="p" id="user_pass" size="28" class="input"/>
<br />
<label><strong>E-mail</strong></label><input type="text" name="email" id="user_email" size="28" class="email" />
<br />
<label><strong>First Name</strong></label><input type="text" name="fname" id="user_fname" size="28" class="input" />
<br />
<label><strong>Last Name</strong></label><input type="text" name="lname" id="user_lname" size="28" class="input" />
<br />
<input id="save" class="addbutton" type="submit" value="Add" onclick=""/>
</form>
</div>
can anyone please advise?
Thanks
Here's what I normally do, add a onSubmit event in the form tag
<form name="loginform" class="loginform" id="loginform" action="#" method="post" onSubmit="return addContent('loginform');">
and then with javascript
function addContent(frm) {
//anything you wanna do before you post
$.post(
url,
$('#' + frm).serialize(),
function (data) {
result = data;
}
)
.success(function() {
//add your success proccesses
})
.complete(function() {
})
.error(function() {
alert('An error has occurred.');
});
return false;// this stops the form from actually posting
}
Use this code:
<div id="contact_form">
<form name="loginform" class="loginform" id="loginform" action="javascript:add_admin();" method="post">
<label><strong>Username</strong></label><input type="text" name="username" id="user_login" size="28" class="input" />
<br />
<label><strong>Password</strong></label><input type="password" name="p" id="user_pass" size="28" class="input"/>
<br />
<label><strong>E-mail</strong></label><input type="text" name="email" id="user_email" size="28" class="email" />
<br />
<label><strong>First Name</strong></label><input type="text" name="fname" id="user_fname" size="28" class="input" />
<br />
<label><strong>Last Name</strong></label><input type="text" name="lname" id="user_lname" size="28" class="input" />
<br />
<input id="save" class="addbutton" type="submit" value="Add"/>
</form>
</div>
You have to define a function on javascript use this javascript code
function add_admin(){
data = $("#loginform").serialize();
password = document.getElementById("user_pass").value;
passtosubmit=hex_sha512(password);
data += "&pass=" + encodeURIComponent(passtosubmit);
password="";
//$.post("modules/process/process_add_admin.php", data);
//alert(data);return false;
$.ajax({
type: "POST",
url: "/modules/process/process_add_admin.php",
data: data,
success: function() {
$('#main_panel_container').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
}
Thanks!
I was having the same issue when I ran across this thread. This solution did not quite work for what I needed to do, but what I wound up doing is just calling my page initiate function again after I loaded the AJAX form. This added the new AJAX form to the event calls and it worked perfectly.
Related
I am trying to submit a form to a my PHP script that uses phpmailer to send emails. I am using a. ajax call to run the PHP script without refreshing but when I click the submit button all it does is refresh the page. Thank you.
Below is my form script
<form method="POST" name="form" onsubmit="return chk()">
<fieldset>
<p><input type="text" name="name" placeholder="NAME" class="field"></p>
<p><input type="email" name="email" placeholder="EMAIL" class="field"></p>
<p><textarea cols="2" name="msg" rows="2" placeholder="MESSAGE"></textarea></p>
<p><input type="submit" class="button" onclick="return chk()"></p>
</fieldset>
</form>
Below is the ajax call. Its my first time using ajax so it may be wrong.
<script type="text/javascript">
function chk()
{
e.preventDefault();
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var msg=document.getElementById('msg').value;
var dataString='name='+name+'&email='+email+'&msg='+msg;
$.ajax({
type:"post",
url:"mail.php",
data: dataString,
cache:false,
success: function(html) {
'Email Sent'
}
});
return false
}
</script>
To use .preventDefault() from a function you need to pass event as an argument
function chk(e){ //<<<<<<< here chk(e) while you're using e.preventDefault() if its somethingelse.preventDefault() so it should be chk(somethingelse)
e.preventDefault();
console.log('Not refreshed');
//return false; no need for it here.. return false here will work for a function not for the submit/click event so it will not prevent the default action in this case you've to use `preventDefault()`
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="chk(event)"> <!-- ck(event) -->
<input type="submit" value="submit"> <!-- No need for onclick here -->
</form>
You can forget about the function and use the submit event directly .. no need to use onsubmit/onclick
$(document).ready(function(){
$("form[name='form']").on('submit' , function(e){
e.preventDefault();
console.log('Not refreshed');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" name="form">
<fieldset>
<p><input type="text" name="name" placeholder="NAME" class="field"></p>
<p><input type="email" name="email" placeholder="EMAIL" class="field"></p>
<p><textarea cols="2" name="msg" rows="2" placeholder="MESSAGE"></textarea></p>
<p><input type="submit" class="button"></p>
</fieldset>
</form>
I am using Xampp and just started learning web dev.
Basically i am trying to learn how to use jquery to submit a form without having to change page, bare in mind i do know it has no validation in and this is for my learning practice.
So myy issue is when i click submit it is causing my webpage to freeze and crash, have I done something wrong with the code i am trying to learn to use?
register.php
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/submit.js"></script>
</head>
<body>
<form id="myForm" method="post">
Username: <input name="username" id="username" type="text" /><br />
Email: <input name="email" id="email" type="text" /><br />
Password:<input name="password" id="password" type="password" /><br />
<input type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
</form>
==============================
<br />
<div id="results"></div>
</body>
</html>
js/submit.js
function SubmitFormData() {
var username = $("#username").val();
var email = $("#email").val();
var pass = $("#password").val();
$.post("submit.php", {
username: username,
email: email,
pass: pass
}, function(data) {
$('#results').html(data);
$('#myForm')[0].reset();
});
}
submit.php
<?php
echo $_POST['username'] ."<br />";
echo $_POST['email'] ."<br />";
echo $_POST['pass'] ."<br />";
echo "==============================<br />";
echo "All Data Submitted Successfully!";
?>
thanks
Use var formData = $("#myform").serialize() instead!
$(document).ready(function() {
// process the form
$("#myform").submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = $("#myform").serialize();
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'register.php', // the url where we want to POST
data : formData, // our data object
dataType : 'html', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
console.log(data);
});
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
The following code is working in jquery-2.2.0.min.js, But in 1.11.1 it is throwing RangeError.
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<form id="myForm" method="post">
Username: <input name="username" id="username" type="text" /><br />
Email: <input name="email" id="email" type="text" /><br />
Password:<input name="password" id="password" type="password" /><br />
<input type="submit" id="submitFormData" value="Submit" />
</form>
==============================
<br />
<div id="results">
</div>
<script>
$("#myForm").on('submit', function(e) {
e.preventDefault();
var name = $("#username").val();
var email = $("#email").val();
var pass = $("#password").val();
$.post("submit.php", {
name: name,
email: email,
pass: pass
}, function(data, status) {
$('#results').html(data);
$('#myForm').trigger("reset");
});
return false;
});
</script>
</body>
</html>
The way question asked
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<form id="myForm" method="post">
Username: <input name="username" id="username" type="text" /><br />
Email: <input name="email" id="email" type="text" /><br />
Password:<input name="password" id="password" type="password" /><br />
<input type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
</form>
==============================
<br />
<div id="results">
</div>
<script>
function SubmitFormData() {
var username = $("#username").val();
var email = $("#email").val();
var pass = $("#password").val();
$.post("submit.php", {
name: username,
email: email,
pass: pass
}, function(data) {
$('#results').html(data);
$('#myForm').trigger('reset');
});
}
</script>
</body>
</html>
Here only change, I have changed the jQuery version.
The above two methods are working. Might be jquery version issue.
I'm quite new to jquery but can't get the following to work properly. I can submit my form only once, after that i can't submit it a second time.
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#register').submit(function() {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
$('#regrespons').html(response);
$("#regrespons").css("visibility", "visible");
$("#regrespons").fadeOut(1000);
}
});
return false;
});
});
</script>
<form id="register" action="includes/register.php" method="post" autocomplete="off">
<input class="inp" name="gebr`enter code here`" type="text" />
<input class="inp" name="ww1" type="password" />
<input class="inp" name="ww2" type="password" />
<input class="inp" name="mail" type="text" />
<input class="but" type="submit" value="Registreren" />
</form>
Any help is apriciated!
Change $("#register").submit(function () { to $(document).on('submit', '#register', function () {
When I try to run my code on any other webbrowsers apart from the Internet explorer it works fine. But when I try to run the code on Internet explorer I do get an alert box saying HERE along with an Ok button. but the problem is when I click on that OK button I do not get anything. Ideally I should be getting another alert box.
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(event) {
alert("here");
$.post('process.php', {name:'test1',email:'test.com'}, function(data)
{
$('#results').html(data);
alert(data);
});
});
});
</script>
</head>
<body>
<form name="myform" id="myform" action="" method="POST">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<label for="email" id="email_label">Email</label>
<input type="text" name="email" id="email" size="30" value=""/>
<br>
<input type="button" name="submit" id="submit" value="Submit">
</form>
<div id="results"><div>
</body>
</html>
Any help on this is very much appreciated.
Edit: I found out that Internet Explorer which has HTTP works perfectly fine but not on Internet Explorer which uses HTTPS.
Change your code to
<form name="myform" id="myform" action="" method="POST" onsubmit="return validate(this);">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<label for="email" id="email_label">Email</label>
<input type="text" name="email" id="email" size="30" value=""/>
<br>
<input type="button" name="submit" id="submit" value="Submit">
</form>
<script>
function validate(elem){
$.post('process.php', {name:'test1',email:'test.com'}, function(data)
{
$('#results').html(data);
return true;
});
return false;
}
</script>
try using jquery $.ajax() for posting your form data using $(fomname).serialize() method
function submitYourForm()
{
$.ajax({
type: 'POST',
cache: false,
async:true,
url: 'your url',
data: $('#myform').serialize(),
success: function(data) {
alert(data);
}
});
}
change your button type from "submit" to "button" and call your function onclick the button
like
<input type="button" name="submit" onclick="submitYourForm();" value="Submit" />
remove function call onsubmit.
try this
just a question --
How do i actually submit a form and still stay on the same page whilst the script is being executed?
I have a simple form that goes like this:
<form action="process.php" method="post" id="form">
<label for="name">Name</label>
<input type="text" name="name" id="name" required="required" />
<label for="email">Email</label>
<input type="email" name="email" id="email" required="required" />
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" required="required" />
<label for="message">Message</label>
<input type="text" name="message" id="message" required="required" />
<input type="submit" id="button" value="Submit"/>
</form>
But everytime i submit the form it just goes to process.php. I don't want that, i want it to stay on the same page, maybe even have a jquery popup saying "thank you" or something.
How do i actually stay on the same page whilst the script is being run?
Put your form processing logic on the same page as the form
Use Ajax
Redirect back to that page when process.php is done processing the form
You have to use ajax in this case.
Basically, you need to post all data using ajax. In server side, you will need to get all parameters using $_POST['name'] like you normally do in server scripting.
FORM
<form action="process.php" method="post" id="form">
<label for="name">Name</label>
<input type="text" name="name" id="name" required="required" />
<label for="email">Email</label>
<input type="email" name="email" id="email" required="required" />
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject" required="required" />
<label for="message">Message</label>
<input type="text" name="message" id="message" required="required" />
<input type="button" id="button" value="Submit"/>
</form>
<div id="dialog-message" title="Thank You">
<p>Your message here</p>
</div>
JQUERY
$(document).ready(function(){
$('#dialog-message').dialog({
modal: true,
autoOpen: false,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
$('#button').on('click', function() {
var name = $('#name').val();
var email = $('#email').val();
var subject = $('#subject').val();
var message = $('#message').val();
var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function() {
alert('');
$('#dialog-message').dialog('open');
}
});
});
});
See the example here
Please note, dont forget to put jquery reference and also jquery ui reference
I think John Conde gave the best answer.
I would either make it so the php file that displays the form also handles the $_POST or if you can't do it that way then do it in Ajax with a code similar to this:
$("#form").bind("submit", function() {
var nameTxt = $("#name").val();
var emailTxt = $("#email").val();
$.post('process.php',
{
name: nameTxt,
email: emailTxt
},
function(data) {
if (data == 'ko')
alert('Could not submit...');
else {
alert('Thank you for your message.');
}
});
return false;
}
What this does is that it "blocks" the regular submit of the form when you click the submit button, retrieve input values and sends them to the process.php script.
It assumes that your "process.php" does an
echo "ko";
if there is an error. You can do some form cleanup after the form has been successfully sent by reseting the inputs:
$("#name").val('');
$("#email").val('');
Assuming you're using jquery:
$(document).ready(function(){
$('#form').submit(function(e){
// do some ajax request to process.php here...
// stop the form doing its default action of submitting directly to process.php
e.preventDefault();
});
});
try something like this
action="<?php print $_SERVER["PHP_SELF"]; ?>" (or) action=""
EDIT:
<?php
if(isset($_POST['Submit'])){
//do your validation or something here
header("location:Process.php");
}
I targeted an iframe to solve the problem, and it worked perfectly.
<form name="contact" role="form" method="post" action="contact.php" target="my_iframe">
Feild 1: <input name="feild1" id="feild1" type="text" placeholder="Lorem ipsum dolor"><br/><br/>
Feild 2: <input name="feild2" id="feild2" type="text" placeholder="Lorem ipsum dolor"><br/><br/>
Feild 3: <textarea name="feild3" id="feild3" rows="5" type="text" placeholder="Lorem ipsum dolor, sit amet."></textarea><br/><br/>
<input type="submit">
</form>
<!-- target iframe to prevent redirection to 'contact.php' -->
<iframe name="my_iframe" width="1" height="1" style="border:none"></iframe>
Literally:
<form action="process.php" method="post" id="form" target="_blank">
^^^^^^^^^^^^^^^^
This will make the browser stay on the same page, even if the form is submitted.
But you will be more likely looking for AJAX instead, some Introduction.
To do that you'll need jquery ajax, see here $.post
You can do something like this (with jQuery, untested)
$(function() {
$("#form").submit(e) {
// Prevent regular form submission
e.preventDefault();
// Submit the form via AJAX
var $form = $("#form");
$.post(
$form.attr("action"),
$form.serialize(),
function() { alert("Done!"); }
);
}
}