I have successfully used ajax to refresh in-line, via ajax, a contact form. I'm having a bit more difficulty getting it to work with data being sent to mysql. I appreciate that what I have so far is not intended to be refreshed via ajax so it might need some work. Here's what I've got... and any help is appreciated.
Form
<form name="email_list" action="">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" name="submit" value="Submit Form" class="email_submit"></p>
</form>
JQuery
$(function() {
$('.email_submit').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = $(this).serialize();
//alert (dataString);return false;
/*$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});*/
});
PHP
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["action"] == "sub")) {
if ($_POST["email"] == "") {
header("Location: mailing_list_add.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo '';
} else {
echo 'Invalid Email Address';
exit;
}
// check that the email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// cleans all input variables at once
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// add record
$add_sql = "INSERT INTO subscribers (email) VALUES('$email')";
$add_res = mysqli_query($mysqli, $add_sql)
or die(mysqli_error($mysqli));
$display_block = "<p>Thanks for signing up!</p>";
// close connection to mysql
mysqli_close($mysqli);
} else {
// print failure message
$display_block = "You're email address - ".$_POST["email"]." - is already subscribed.";
}
}
}
?>
<html>
<?php echo "$display_block";?>
</html>
**Updated above after making changes :)
There are a few problems, like:
You need to attach the javascript to an event (the form submit), so the first part would be something like:
$('form').submit(function() {
You need to send in all (correct...) form values, not just the email address for your php to work:
$('form').submit(function() {
var dataString = $(this).serialize();
you miss the data from the server (remove the HTML tags in your server skript):
$.ajax({
type: "POST",
url: "mailing_list_add.php",
data: dataString,
success: function(data) {
$('#email_add').html("<div id='response'></div>");
$('#response').html("<h2>Successfully added to the database.")
.hide()
.fadeIn(2500, function() {
$('#response').html(data);
});
}
});
Related
I have a php file that has jquery ajax on it to submit a form and save its contents into a mysql without doing a page refresh.
My issue is if I load the file that the ajax call does the contents are saved into the database however if I try to use the form nothing gets saved to the database even though I get a success message.
Here is my code
The HTML file
<div id='backinstock-form'>
<form>
<input id='instockemailadr'>
<input id='instockpid' value='5' type='hidden'>
<input name='submit' class='submitbackinstock' type='button' value='Submit'>
</form>
<span class='error' style='display:none'> Please Enter A Valid Email</span>
<span class='success' style='display:none'> Email Submitted Success</span>
</div>
require(['jquery'], function($)
{
$(".submitbackinstock").click(function()
{
var instockemailadr = $("#instockemailadr").val();
var instockpid = $("#instockpid").val();
var dataString = 'usereaddr='+ instockemailadr + '&sku=' + instockpid;
if(instockemailadr =='' || instockpid =='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
//console.log(dataString);
var dataString = new formData();
dataString.append('usereaddr', instockemailadr);
dataString.append('sku',instockpid);
$.ajax({
type: "POST",
url: "<?php echo $block->getBaseUrl(); ?>/pub/media/theme_customization/backin-stock-email-code/backinstock_process_email.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
The PHP File
<?php
// MySQL portion
$conn = mysqli_connect("localhost", "root", "root");
mysqli_select_db($conn,"multisitedb");
$usereaddr = mysqli_real_escape_string($conn, $_POST['usereaddr']);
$stockproductid = mysqli_real_escape_string($conn, $_POST['sku']);
$created_on = date('Y-m-d h:i:s');
$result = mysqli_query($conn, "INSERT INTO multisitedb.backinstock_email_addresses(email_addr, product_sku, created_on)
VALUES ('$usereaddr','$stockproductid','$created_on')");
if($result) {
echo $result; // or whatever you want
} else {
echo "Something went wrong.";
}
?>
First, you didn't specify a Database in your php script. The format is mysqli_connect(host, username, password, database);
Secondly, your ajax code seems wrong. You're making a post request. The data should be an instance of formData(). You can modify this way:
var dataString = new formData();
dataString.append('usereaddr', instockemailadr);
dataString.append('sku',instockpid);
//...
data: dataString,
success: function(){
Also, your PHP script is not doing security checks. You need to validate user inputs as well as use prepared statements to prevent against SQL injection attack.
I have problem with a log in form. When I try to log in the javascript always returns the false value even when I am typing correct username and password.
Here is my code in the jQuery file:
$(document).ready(function(){
var teamname = $("#teamname");
var teampassword = $("#teampassword");
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
var result = false;
$.post('../php/validations/validatePassword.php', {tname: name, tpassword: password}, function(data){
if(data == 1){
result = true;
}else{
result = false;
}
});
return result;
}
$("#join").click(function(){
if(isPasswordCorrect()){
alert("You have joined");
}else{
alert("You have not joined");
}
});
});
Here is my code in the PHPfile:
<?php
$teamname = $_POST['tname'];
$teampassword = $_POST['tpassword'];
if($teamname != "" || $teampassword !=""){
include('../connection.php'); // Here is the log in to the phpmyadmin
$queryCheckPassword = mysqli_query($con, "SELECT password FROM
teams WHERE name = '$teamname'");
$row = mysqli_fetch_row($queryCheckPassword);
$teamPassword = $row[0];
if($teamPassword == $teampassword)
{
echo 1;
}else{
echo 0;
}
}
?>
And here is my code in HTML file:
<form id="joinform"> <!-- action="teams.php" method="post"> -->
<ul>
<div>
<label>Team name <font color='red'>*</font></label>
<input type='team' name='teamname' id='teamname' placeholder='Team name' readonly='readonly'/>
<span id='teamnameinfo'>Select an existing team</span>
</div>
<div>
<label for="teampassword">Team password <font color='red'>*</font></label>
<input type='password' name='teampassword' id="teampassword" placeholder='Team password'/>
<span id='teampasswordinfo'>Write team password</span>
</div>
<div>
<button name='join' id='join'>Join</button>
</div>
</ul>
</form>
The problem lies in your use of Javascript. Look at your isPasswordCorrect function (which I have reformatted slightly to make the issue a little clearer):
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
var result = false;
$.post(
'../php/validations/validatePassword.php',
{tname: name, tpassword: password},
function (data) {
if(data == 1){
result = true;
}else{
result = false;
}
}
);
return result;
}
See that function (data) {} in there? That's a callback. The way the $.post method works is this:
your JS code sends a request to the server using $.post
your JS code continues, moving on to whatever comes next
Some time later (could be 10 milliseconds later, could be 30 seconds later), the server responds to the request. At that point your callback is called.
What does this mean? When your code hits the return result; line, your code has just submitted the request to the server and the server has probably not responded yet. Thus, result is still false.
A quick solution to this problem is to move the alert statements into the callback, like this:
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
$.post(
'../php/validations/validatePassword.php',
{tname: name, tpassword: password},
function (data) {
if(data == 1){
alert("You have joined");
}else{
alert("You have not joined");
}
}
);
}
$("#join").click(function(){ isPasswordCorrect(); });
However, I imagine you're going to want to do more than just alert something. You're going to need to research the asynchronous nature of Javascript and understand it before you can extend this fragment to do much.
PeterKA is correct about the async. The default value (false) is probably be returning before your async call comes back. Try adding a callback instead (untested):
function isPasswordCorrect(callback)
{
var password = teampassword.val();
var name = teamname.val();
$.post('../php/validations/validatePassword.php', {tname: name, tpassword: password},
function(data) { callback(data == 1); });
}
$("#join").click(function(){
isPasswordCorrect(function(result) {
if (result)
alert("You have joined");
else
alert("You have not joined");
});
});
Because AJAX does not return the result immediately - ASYNCHRONOUS - you want to do the check only and only when you have the result - in the AJAX callback like so:
function isPasswordCorrect()
{
var password = teampassword.val();
var name = teamname.val();
$.post(
'../php/validations/validatePassword.php',
{ tname: name, tpassword: password },
function(data) {
if(data == 1) {
alert("You have joined");
} else {
alert("You have not joined");
}
}
);
}
$("#join").click(isPasswordCorrect);
I have a form submission page, call a function at the time of form submission.Include an ajax.Form submission occur or not according to the condition in ajax.Ajax msg have two values 1 and 0,one value at a time.My requirement is when msg==1 form not submit and msg==0 submit form.But now in both cases form is not submitting.
My code is given below.Anybody give any solution?
main page
<form action="addCustomer_basic.php" method="post"
name="adFrm" id="myform" >
<input name="name" type="text"
class="txtfld" id="name"
value=">" style="width:250px;"/>
<input name="email" type="text"
class="txtfld" id="email" value="" style="width:250px;"/>
<input name="submit" type="submit" value="Submit" />
</form>
<script language="JavaScript">
$(function() {
$("#myform").submit(function(e) {
var $form = $(this);
var cust_name = $form.find('[name="name"]').val();
e.preventDefault();// prevent submission
var email = $form.find('[name="email"]').val();
$.ajax({
type: "POST",
url: 'ajx_customer_mailid.php',
data:'cust_name='+cust_name + '&email=' + email,
success: function(msg)
{
alert(msg);
if(msg==1)
{
alert("Email Id already excist in database");
return false;
}
else
{
self.submit();
}
}
});
});
});
</script>
ajx_customer_mailid.php
<?php
require_once("codelibrary/inc/variables.php");
require_once("codelibrary/inc/functions.php");
$cust_id=$_POST['cust_name'];
$email=$_POST['email'];
$se="select * from customer where name='$cust_id' and email='$email'";
$se2=mysql_query($se);
if($num>0)
{
echo $status=1;
}
else
{
echo $status=0;
}
?>
I've checeked your code, without ajax, and just set directly the msg to 1 or to 2.
See my code, now you can simulate it:
$("#myform").submit(function(e) {
var $form = $(this);
e.preventDefault();// prevent submission
var msg = 2;
if (msg === 1) {
alert("Email Id already excist in database");
return false;
} else {
$form.submit(); //This causes Too much recursion
}
});
There are some errors in it.
So, self.submit(); is bad:
TypeError: self.submit is not a function
self.submit();
You need to rewrite it to $form.submit();
But in that case, if the form needs to submit, you will get an error in your console:
too much recursion
This is because, if it success, then it fires the submit again. But, because in the previous case it was succes, it will be success again, what is fires the submit again, and so on.
UPDATE:
Let's make it more clear what happens here. When you submit the form, after you call e.preventDefault() what prevents the form to submit. When ajax need to submit the form, it triggers the submit(), but you prevent it to submit, but ajax condition will true again, so you submit again, and prevent, and this is an inifinte loop, what causes the too much recursion.
NOTE:
if($num>0) Where the $num is come from? There are no $num anywhere in your php file. You also do not fetch your row of your sql query.
Use mysqli_* or PDO functions instead mysql_* since they are deprecated.
Avoid sql injection by escaping your variables.
So you need to use like this:
$se = "select * from customer where name='$cust_id' and email='$email'";
$se2 = mysql_query($se);
$num = mysql_num_rows($se2); //NEED THIS!
if ($num > 0) {
echo $status = 1;
} else {
echo $status = 0;
}
But i am suggest to use this:
$se = "SELECT COUNT(*) AS cnt FROM customer WHERE name='".mysql_real_escape_string($cust_id)."' and email='".mysql_real_escape($email)."'";
$se2 = mysql_query($se);
$row = mysql_fetch_assoc($se2); //NEED THIS!
if ($row["cnt"] > 0) {
echo $status = 1;
} else {
echo $status = 0;
}
By the time your ajax call finishes, submit handler already finished so the submit continues, it's async you know, so the function makes the ajax call and continues executing. You can do something like this http://jsfiddle.net/x7r5jtmx/1/ What the code does is it makes the ajax call, then waits until the ajax success updates the value of a variable, when the value is updated, if the value is 1, no need to do anything, as we already stopped the form from submittin. If the value is 0, then trigger a click on the button to re-submit the form. You can't call submit inside the submit handler, but you can trigger click on the button. You obviously need to change the ajax call, just set msg inside your success.
var data = {
json: JSON.stringify({
msg: 0 //change to 1 to not submit the form
}),
delay: 1
}
var msg = null;
var echo = function() {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: data,
cache: false,
success: function(json){
msg = json.msg;
}
});
};
$( "#myform" ).submit(function( event ) {
echo();
var inter = setInterval(function(){
console.log("waiting: " + msg);
if (msg != null){
clearInterval(inter);
}
if (msg == 0){
$( "#myform" ).off(); //unbind submit handler to avoid recursion
$( "#btnn" ).trigger("click"); //submit form
}
}, 200);
return false; //always return false, we'll submit inside the interval
});
I have wrote this code in php:
public function getinfo($username){
$this->autoRender = false;
if($this->request->is('ajax')){
if(!ereg('^[A-Za-z0-9_.]+$',$username)){
echo 'username';
}
else{
$user = $this->User->find('all',array('conditions'=>array('User.username'=>$username)));
if(empty($user)){
echo 'Fail';
}
else{
$this->loadModel('Question');
$question = $this->Question->find('all',array('conditions'=>array('Question.id'=>$user[0]['User']['questionid'])));
echo 'Sec Question : ' . $question[0]['Question']['title'] . '<br />';
echo 'Answer: <input type="text" id="userAnswer" class="loginField" name="data[answer]" /> ';
echo '<input type="submit" id="sendAnswer" class="button" value="send" /> <br />';
echo '<span id="recoverErr"></span>';
$this->Session->write('recoverPass',$user[0]);
}
}
}
else{
$this->redirect(array('controller'=>'message','action'=>'forbidden'));
}
}
And I have wrote this in my jquery file:
$('#send').click(function(){
var recover = $('#recoverUsername').val();
$('#recErr').css('color', 'red');
if(recover == ''){
$('#recoverUsername').focus();
$('#recErr').html('Enter username');
return false;
}
$.ajax({
url: $('#base').html() + '/users/getinfo/'+recover,
type: 'POST',
success: function(data){
if(data.match('username')){
$('#recErr').html('Enter correct username.');
}
else if(data.match('Fail')){
$('#recErr').html("This username doesn't exist");
}
else{
$('#recErr').html('');
$('#recoverWindow').html(data);
$('#recoverWindow').dialog('open');
}
}
});
});
$('#sendAnswer').click(function(){
var answer = $('#userAnswer').val();
$.ajax({
url: $('#base').html() + '/users/getanswer/'+answer,
type: 'POST',
success: function(data){
if(data.match('answer')){
$('#recoverErr').html('Enter answer');
}
else if(data.match('Fail')){
$('#recoverErr').html('answer is false.');
}
else if(data.match('Bad')){
$('#recoverErr').html('fail too send mail.');
}
else{
$('#recoverWindow').html('');
$('#recoverWindow').html('Email was sent, check your spam if it is not in your inbox.');
}
}
});});
but when I click and the server found the User's info and put it in recoverWindow the click function doesn't work and doesn't send the answer to the action.
please Help me, i don't have time
You have used Ajax for creating recover form in your php function. so you can't put $('#sendAnswer').click() in ready function. Because sendAnswer element doesn't exist in your HTML and you want create in your php file.
So you should write click function for this element after ajax execution. With this explanation your JQuery Code should change to this:
$('#send').click(function(){
var recover = $('#recoverUsername').val();
$('#recErr').css('color', 'red');
if(recover == ''){
$('#recoverUsername').focus();
$('#recErr').html('Enter username');
return false;
}
$.ajax({
url: $('#base').html() + '/users/getinfo/'+recover,
type: 'POST',
success: function(data){
if(data.match('username')){
$('#recErr').html('Enter correct username.');
}
else if(data.match('Fail')){
$('#recErr').html("This username doesn't exist");
}
else{
$('#recErr').html('');
$('#recoverWindow').html(data);
$('#recoverWindow').dialog('open');
$('#sendAnswer').click(function(){
var answer = $('#userAnswer').val();
$.ajax({
url: $('#base').html() + '/users/getanswer/'+answer,
type: 'POST',
success: function(data){
if(data.match('answer')){
$('#recoverErr').html('Enter answer');
}
else if(data.match('Fail')){
$('#recoverErr').html('answer is false.');
}
else if(data.match('Bad')){
$('#recoverErr').html('fail too send mail.');
}
else{
$('#recoverWindow').html('');
$('#recoverWindow').html('Email was sent, check your spam if it is not in your inbox.');
}
}
});});
}
}
});});
Help me, i don't have time
thats the reason you didn't search for other related answer..
anyways like many other answers in stackoverflow including mine , here i go again..
you need to delegate click event for dynamically added element using on
$('#recoverWindow').on('click','#sendAnswer',function(){
....
instead of
$('#sendAnswer').click(function(){
If your element with id="sendAnswer" is loading via ajax and you wrote click event for that in your main page then you have to use .on() or .live() method to get it executed.
But they both methods are used for different jQuery versions.
Please write it as following
$(document).ready(function() {
//if you are using jQuery version after 1.7 then use following
$(document).on('click', '#sendAnswer', function(){
//your logic
});
//if you are using jQuery version upto 1.7 then use following
$('#sendAnswer').live('click', function(){
//your logic
});
});
I am having an issue where I am trying to pass a submit buttons values along with the form to ajax but for some reason the only value that passes no matter which button I push is the first button. There is more to the form but I am just showing the buttons.
<form>
<input type="submit" name"finalize_invoice" id="finalize_invoice" value="Delete" />
<input type="submit" name"finalize_invoice" id="finalize_invoice" value="Save" />
<input type="submit" name"finalize_invoice" id="finalize_invoice" value="Finalize" />
</form>
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var invoice_temp_id = $('#invoice_temp_id').attr('value');
var man_part_number = $('#man_part_number').attr('value');
var customer = $('#customer').attr('value');
var date = $('#date').attr('value');
var shipdate = $('#shipdate').attr('value');
var shipvia = $('#shipvia').attr('value');
var ponumber = $('#ponumber').attr('value');
var rep = $('#rep').attr('value');
var invoicenotes = $('#invoicenotes').attr('value');
var serial_number = $('#serial_number').attr('value');
var skid = $('#skid').attr('value');
var finalize_invoice = $('#finalize_invoice').attr('value');
$.ajax({
type: "POST",
url: "includes/createfinalinvoice.php?",
data: "invoice_temp_id="+ invoice_temp_id+
"&man_part_number="+ man_part_number+
"&customer="+ customer+
"&date="+ date+
"&shipdate="+ shipdate+
"&shipvia="+ shipvia+
"&ponumber="+ ponumber+
"&rep="+ rep+
"&invoicenotes="+ invoicenotes+
"&serial_number="+ serial_number+
"&skid="+ skid+
"&finalize_invoice="+ finalize_invoice+
$( this ).serialize(),
success: function(data){
if (data == 1) {
var thiserror = 'You may not have any blank fields, please make sure there is a serial number in each field';
alert(thiserror);
}
if (data == 2) {
var thiserror = 'Your serial number(s) do not match with the Manufacture Part Numbers, please double check your list';
alert(thiserror);
}
if (data == 3) {
var thiserror = 'Some of your serial numbers are not located in the database, please make sure you entered the correct serial number';
alert(thiserror);
}
if (data == 4) {
var thiserror = 'This item has already been sold to another customer. Please report this to administration';
alert(thiserror);
}
if (data == 5) {
var thiserror = 'Everything went OK, you may continue and view the processed invoice';
alert(thiserror);
}
if (data == 6) {
var thiserror = 'There are no default prices setup for this customer matching the Manufacture Part Numbers. Please check and make sure they all exist before processing this list';
alert(thiserror);
}
if (data == 7) {
window.location = ('/admin/?mmcustomers=1&viewinvoice=1');
}
}
});
return false;
});
});
You have three submit buttons with identical ids of finalize_invoice. ids must be unique however. This is the reason, jquery selects the first button only, no matter which one was clicked. If you want to send the request with the clicked button, bind a function to the button's click event
$('form#submit input[type="submit"]').click(function() {
...
var finalize_invoice = $(this).attr('value');
$.ajax(...);
...
return false;
}
As #thaJeztah suggested, suppressing the submit event on form
$('form#submit').submit(function() {
return false;
});
<form>
<input type="button" name"del_button" id="del_btn" value="Delete" />
<input type="button" name"save_button" id="save_btn" value="Save" />
<input type="button" name"finalize_button" id="finalize_btn" value="Finalize" />
</form>
<script>
$(document).ready(function(){
var clicked_btn = '';
$('form').submit(function(){ return false; });
$('form input[type=button]').click(function(){
clicked_btn = $(this).attr('id');
yourSubmitFunction(clicked_btn);
return false;
});
}
</script>