dont refresh the page when you submit the form - php

hii guys im new to web programing and im creating a website
in this website i want to add a contact us form in the footer of the page like this
<form action="footer_contactus1.php" method="post">
<div class="row">
<div class="form-grope col-lg-4">
<label><span class="glyphicon glyphicon-user"></span>Name</label><br>
<input name="cuname" type="text" class="form-cotrol">
</div>
<div class="form-grope col-lg-4">
<label><samp class="glyphicon glyphicon-envelope"></samp>Email</label><br>
<input name="cuemail" type="email" class="form-cotrol">
</div>
<div class="form-grope col-lg-4">
<label><i class="glyphicon glyphicon-earphone"></i>Phone Number</label><br>
<input name="cutele" type="tel" class="form-cotrol">
</div>
<div class="form-grope col-lg-12">
<br>
<label><span class="glyphicon glyphicon-paste"></span>Message</label><br>
<textarea name="cumessage" class="form-cotrol" rows="6" style="width: 100%;" ></textarea>
</div>
<div class="form-grope col-lg-12">
<br>
<input type="hidden" name="save" value="contact">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</div>
</form>
and when i click the submit button i want the php file to get executed so the inputs got inserted into the database
the php file
<?php
$pdo = new PDO('mysql:host=localhost;dbname=mywsite_db', 'root', '');
$req = $pdo->prepare('INSERT INTO message (id_message,nom,email,tele,message)
VALUES(null,?,?,?,?)');
$req->execute(array($_POST['cuname'],$_POST['cuemail'],$_POST['cutele'],$_POST['cumessage']));
header('Location: HomePage.php');
?>
i wanted this form to get submited without refreshing the page by ajax
i tried different tutorials and nothing worked can you plzz gives me the correct ajax script for my form so i can submit it to the php file and insert the data on the database then a message (alert) pop up telling me that the data has been inderted without refreshing the page plzz

<form action="footer_contactus1.php" method="post" id="myForm1">
...
</form>
<script type="text/javascript">
var frm = $('#myForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('The data has been inserted');
}
});
ev.preventDefault();
});
</script>

Related

Why is the Ajax code not posting to pho file?

I have a form which I am using to AJAX to submit. I have several forms using the same script all with different names posting to response.php however this particular form will not send.
When I remove my form name it tries to post in the normal way but when it has the correct name as the AJAX file I receive no reponse whatsoever leading me to think it is an error within the AJAX file.
HTML
<tr><Td>
<div class="row box" id="login-box">
<div class="col-md-9 col-md-offset-1">
<div class="panel panel-login">
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<div id="msg"></div>
<div class="alert alert-danger" role="alert" id="error" style="display: none;">...</div>
<form id="editMarshalTitleDetails-form" name="editMarshalTitleDetails_form" role="form" style="display: block;" method="post">
<div class="form-group">
<br><Br>
<input type="text" name="content" id="content" tabindex="2" class="form-control" value="<?php echo $content2 ?>">
<input type="hidden" name="marshalColumn" value="marshalPackFrontPageTitle">
<input type="hidden" name="userID" value="<?php echo "$userID"?>">
</div>
<div class="col-xs-12 form-group pull-right">
<button type="submit" name="editMarshalTitleDetails-submit" id="editMarshalTitleDetails-submit" tabindex="4" class="form-control btn btn-primary">
<span class="spinner"><i class="icon-spin icon-refresh" id="spinner"></i></span> Edit Title
</button>
</div>
</form>
</div>
</div>
</tr></td>
AJAX
$("#editMarshalTitleDetails-form").validate({
submitHandler: submitForm6
});
function submitForm6() {
var data = $("#editMarshalTitleDetails-form").serialize();
$.ajax({
type : 'POST',
url : 'response.php?action=editMarshalTitleDetails',
data : data,
beforeSend: function(){
$("#error").fadeOut();
$("#editMarshalTitleDetails_button").html('<span class="glyphicon glyphicon-transfer"></span> updating ...');
},
success : function(data){
$("#editMarshalTitleDetails_button").html('<span class="glyphicon glyphicon-transfer"></span> Template Updated');
var a = data.split('|***|');
if(a[1]=="update"){
$('#msg').html(a[0]);
}
}
});
return false;
}

jQuery Ajax passing input values from one modal to another

I have a modal for entering user information. A user should be linked to a building. After user information has been entered and submit button has been clicked, I am preventing the default action and am overlaying/showing a building modal over the user modal.
Code for doing so follows.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
}
});
$('#modalConnectBuilding').modal('show');
});
})(window.jQuery);
console.log() logs the input information correctly, however in 'modalConnectBuilding.php' the following does not work:
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];
?>
Producing the following errors:
Undefined index: name_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: address_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: city_user in
C:\laragon\www\modals\modalConnectBuilding.php
My intent is to do a classic 'form action="./php/processConnectBuilding.php" method="post"' but would need access to the three undefined variables as seen above. Adding users and buildings works in isolation but not when connected in this way. Any help would be greatly appreciated and if you need any more info, please ask. Thank you!
Code for the form (within the modal) I'm submitting follows (please note, default action is being suppressed by preventDefault() so action attribute is never "called", also the form for connecting a building is basically the same, but the action attribute is not suppressed):
<form role="form" id="formAddUser" action="./php/processAddUser.php" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<form role="form" id="formAddUser" action="" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" id="name" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>
</body>
</html>
<script>
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: 'tariffdetaildata.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function(data) {
alert(data)
}
});
});
</script>
tariffdetaildata.php
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];
Try this way I think you need to open the modal popup once you get the response back from the ajax.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
$('#modalConnectBuilding').modal('show');
$("#modalConnectBuilding .modal-body #name_user").val( name_user);
$("#modalConnectBuilding .modal-body #address_user").val( address_user);
$("#modalConnectBuilding .modal-body #city_user").val( city_user);
}
});
});
})(window.jQuery);

Using 2 recaptcha on same page and getting different values for both via AJAX

I have 2 Google Recaptcha's on same page in different forms (Login and Register Forms). I had to put both the forms on the same page due to the designing requirements which can't be changed. Now the problem is that the 1st form is the login form followed by the register form in the 2nd. Now, the recaptcha on the login form takes effect for register form as well. I mean that I can see recaptcha on both the forms but the one in register form doesn't work (which means it doesn't sends the correct value to the PHP page where the form will be processed). When I tried verifying the recaptcha on the login form and submitting the register form it worked. This means that the 1st loaded recaptcha (on the login form) is working for both which should not be. Both the recaptchas should work separately for each forms. Also, when I get the values of both the recaptchas via AJAX to send to the PHP page for the server side validation I am using captcha: grecaptcha.getResponse() for both. THIS CAN BE THE ACTUAL PROBLEM I GUESS. If I could get separate values for both maybe the things would have gone down well. Any help would be appreciated.
Here are my codes.
<div class="container">
<div class="row">
<div class="col-md-6">
<h3 class="com-reps cr-panel">Login Now</h3>
</div>
<div class="col-md-6">
<h3 class="com-reps cr-panel">Register Now</h3>
</div>
<div class="col-md-6">
<div class="post-holder">
<div class="login-message"></div>
<div class="post-content">
<form method="post" action="">
<div class="form-group">
<input type="text" id="uname" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input type="password" id="pass" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="<?php echo $mainf['set_recaptcha_sitekey']; ?>"></div>
</div>
<div class="form-group">
<input type="submit" id="login" value="Log In" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
<div class="col-md-6">
<div class="post-holder">
<div class="register-message"></div>
<div class="post-content">
<form method="post" action="">
<div class="form-group">
<input type="text" id="name" class="form-control" placeholder="Full Name">
</div>
<div class="form-group">
<input type="text" id="username" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input type="password" id="password" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="password" id="cpass" class="form-control" placeholder="Confirm Password">
</div>
<div class="form-group">
<input type="text" id="email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="text" id="dob" class="form-control" placeholder="Date of Birth">
</div>
<div class="form-group">
Sex
<input type="radio" id="sex" name="sex"> Male
<input type="radio" id="sex" name="sex"> Female
</div>
<div class="form-group">
<input type="checkbox" id="legal" name="legal"> I accept the Terms of Service and Privacy Policy.
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="<?php echo $mainf['set_recaptcha_sitekey']; ?>"></div>
</div>
<div class="form-group">
<input type="submit" id="submit" value="Register" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#login").click(function(){
var dataString = {
uname: $("#uname").val(),
pass: $("#pass").val(),
captcha: grecaptcha.getResponse()
};
$.ajax({
type: "POST",
//dataType : "json",
url: "processes/login.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#login").val("Please wait...");
$(".login-message").hide();
},
success: function(html){
$('.login-message').html(html).fadeIn();
if($('.login-message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
window.location.replace("index.php");
}, 500);
}else{
$("#login").val("Log In");
}
}
});
return false;
});
$("#submit").click(function(){
var dataString = {
name: $("#name").val(),
uname: $("#username").val(),
pass: $("#password").val(),
cpass: $("#cpass").val(),
email: $("#email").val(),
dob: $("#dob").val(),
sex: $("input[name='sex']:checked").val(),
captcha: grecaptcha.getResponse()
};
$.ajax({
type: "POST",
//dataType : "json",
url: "processes/register.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").val("Please wait...");
$(".register-message").hide();
},
success: function(html){
$('.register-message').html(html).fadeIn();
$("#submit").val("Register");
}
});
return false;
});
});
</script>
I got the solution. In case someone comes looking for this it will help them.
In both HTML Forms replace
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
to
<div id="recaptcha1"></div> and <div id="recaptcha2"></div> respectively.
Then replace your script calling from
<script src="https://www.google.com/recaptcha/api.js></script>
to
<script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
And insert these code in your <script></script>. Note that this should be outside of $(document).ready(function() { and above your next form submission AJAX codes.
var recaptcha1;
var recaptcha2;
var myCallBack = function() {
recaptcha1 = grecaptcha.render('recaptcha1', {
'sitekey' : 'YOUR_SITE_KEY'
});
recaptcha2 = grecaptcha.render('recaptcha2', {
'sitekey' : 'YOUR_SITE_KEY'
});
};
Next and last thing, change the captcha: grecaptcha.getResponse() in your form submission AJAX code to captcha: grecaptcha.getResponse(recaptcha1) and captcha: grecaptcha.getResponse(recaptcha2) respectively (for both AJAX codes of login and register forms in my case). For full form submission code please refer to the code in my question above. Just replace the captcha: part here as said.
Done! Now you can proceed to server side validation in your language (PHP or ASP whatever).

How to submit form on one page to a different page using ajax call in jquery

I have a page called page2.php. It has a form that allows you to search via jquery ajax call. The code is below. My question is, I have a different form on page1.php. How can I submit the form on page1.php to go to page2.php and have it execute the page2.php code below using the data from the form on page1.php? I know this is most likely simple, having a brain fart right now.
$(function() {
$.validate({
form: '#form_search',
validateOnBlur: false,
errorMessagePosition: 'top',
onSuccess: function(form) {
var formval = $(form).serialize();
var formurl = '/page2.php?a=search';
$('#form_results').html('<div class="form_wait_search">Searching, please wait...<br><img src="/images/search-loader.gif"></div>');
$.ajax({
type: 'POST',
url: formurl,
data: formval,
success: function(data){
var json = $.parseJSON(data);
$('#form_errors').html(json.message);
$('#form_results').html(json.results);
}
});
return false;
}
});
});
UPDATE
Here is the forms Im referring to.
On page1.php this is like a module on the right side bar. Just a form that I want to post to page2.php
<div class="scontent_box1">
<strong class="box_title"><i class="fa fa-search fa-flip-horizontal"></i> Find Locations</strong>
<form method="post" action="/page2.php">
<div class="form-group">
<label>Street Address</label>
<input type="text" class="form-control" name="ad" placeholder="Enter Street Address...">
</div>
<div class="form-group">
<label>City, State or Zip Code</label>
<input type="text" class="form-control" name="ct" placeholder="Enter City, State or Zip Code...">
</div>
<button type="submit" class="btn btn-default blue_btn">Search</button>
</form>
</div>
Now here is the form on page2.php that executes the ajax code above. I want page1.php to submit to page2.php and envoke the same jquery code above.
<div class="row no_gutters">
<div class="search_page">
<div id="form_errors"></div>
<form method="post" id="form_search">
<div class="form-group">
<label for="ad">Street Address<span class="reqfld">*</span></label>
<input type="text" class="form-control" data-validation="required" id="ad" name="ad" placeholder="Enter Street Address..." value="">
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="ct">City, State or Zip Code<span class="reqfld">*</span></label>
<input type="text" class="form-control input-sm" data-validation="required" id="ct" name="ct" placeholder="Enter City Name..." value="">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-xs-12">
<button type="submit" class="btn btn-default blue_btn btn-block">Search Locations</button>
</div>
<div class="col-md-8"></div>
</div>
</form>
</div>
<div id="form_results"></div>
</div>

jquery append() function not working

I am creating my own custom chat bar all the related coding i have done, database and all the php functions working fine but when after submit the chat input message i am trying to append the input box data with jquery append function its not working at all.
html:
<div class="chat-bar-wrapper">
<div class="chat-bar-head">
<div class="chat-bar-icons-top">
<i class="fa fa-minus"></i>
</div>
<div class="chat-bar-title">
<p>Chat Online</p>
</div>
</div>
<div class="chat-bar-form">
<div class="chat-bar-text-display" id="messages_output"></div>
<form class="message-box" id="chat-form">
<div class="chat-bar-text-inputs">
<div class="chat-bar-text-input">
<input type="text" class="form-control" name="messages_input" placeholder="Enter your text here">
</div>
<div class="chat-bar-text-enter">
<input type="submit" class="btn btn-warning form-control" value="#">
</div>
</div>
</form>
</div>
</div>
js:
$(function(){
$("#messages_output").load('ChatMsgLoad.php');
$("#chat-form").submit(function(){
$.post('chatMsgPost.php', $('#chat-form').serialize(), function(data){
$('#messages_output').append(data);
});
return false;
});
});
Try this appendTo() instead of append().
$( data ).appendTo( "#messages_output");
And check in the console whether data variable contains something.
Read more here appendTo() in jQuery

Categories