//My jquery
$(document).ready(function() {
var form = $('#form1'); // contact form
var submit = $('#submit1'); // submit button
var alert = $('.alert1'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
// sending ajax request through jQuery
$.ajax({
url: 'giftcard_check.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Checking....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Apply'); // reset submit button text
var $container = $("#result1");
var refreshId = setInterval(function()
{
$container.load("result.php?code=<?php echo $variable; ?>");
}, 500);
},
error: function(e) {
console.log(e)
}
});
});
});
The above code is not working while using php code inside jquery. If iam not using php code its working fine. But i want to send session variables to another page (result.php). How can i solve this. Is there any method.
use below code . assing php session to javascript variable. make sure this code is in side PHP file . php will not work inside .js file
var sessionID = "<?php echo $_SESSION['id']; ?>";
$(document).ready(function() {
var form = $('#form1'); // contact form
var submit = $('#submit1'); // submit button
var alert = $('.alert1'); // alert div for show alert message
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
// sending ajax request through jQuery
$.ajax({
url: 'giftcard_check.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Checking....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Apply'); // reset submit button text
var $container = $("#result1");
var refreshId = setInterval(function()
{
$container.load("result.php?code="+sessionID);
}, 500);
},
error: function(e) {
console.log(e)
}
});
});
});
lets look on a different angle
you can do on your html something like this:
<form>
<input type="submit" id="f_the_world" data-session-id="<?php echo $variable; ?>"/>
</form>
then on your JS
$(document).ready(function() {
var form = $('#form1'); // contact form
var submit = $('#submit1'); // submit button
var alert = $('.alert1'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
// sending ajax request through jQuery
$.ajax({
url: 'giftcard_check.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Checking....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Apply'); // reset submit button text
var $container = $("#result1");
var refreshId = setInterval(function()
{
var code = $('#f_the_world').attr('data-session-id');
$container.load("result.php?code=".code);
}, 500);
},
error: function(e) {
console.log(e)
}
});
});
});
its just dont feel right seeing server scripts on client scripts
why are you sending the session id to the next page...session values are stored
in server. You can access session values from any page.
we can easily get the session variable in result.php by adding session_start(); at the begining of result.php. So that we can have access to the session variable created.
First Step:
In your jQuery code written page just start the session variable $_SESSION['id'].
Second Step:
In your result.php page, write session_start(); at the beginning. Then just call the $_SESSION['id'].
Hope this will help :-)
Related
I have a form that I'm submitting by AJAX and trying to replace the form once it's been submitted with a success message.
Using this:
jQuery(function($){
var $form = $('#ajax_form'),
$message = $('#thanks');
$form.submit(function(e){
$.ajax({
type: "POST",
data: $form.serialize(),
url: $form.attr('action')
})
.done(function(data) {
console.log(data);
if (data.success) {
$form.hide();
$message.fadeIn('slow');
}
});
e.preventDefault();
});
});
when I click the submit button, nothing happens, and I don't get anything written to the console. But the form is hooked up to a database and I can see in the back end that submissions are being saved.
So why is that nothing within the done function is returning?
I have following code and I want to submit my Form on click button, Click function is working fine but tell me how I can Assign values of "ID" at the end of my URL as mentioned on the below code.
<script type="text/javascript">
$(document).ready(function() {
$(".btn-success").click(function(){
var ID = $(this).prev('.sendEmail').attr('id');
alert(ID);
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
var form = $('#form2'); // contact form
var submit = $('#submit2'); // submit button
var alert = $('.alert'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: '//mydomain.com/'+ID,
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Sending....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('✔ Alert Successfully Sent!'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
</script>
You need to make the ID var global:
var ID;
$(document).ready(function() {
$(".btn-success").click(function(){
ID = $(this).prev('.sendEmail').attr('id');
alert(ID);
});
});
...rest of your code
Or if you combine your document ready calls:
$(document).ready(function() {
var ID;
$(".btn-success").click(function(){
ID = $(this).prev('.sendEmail').attr('id');
alert(ID);
});
var form = $('#form2'); // contact form
var submit = $('#submit2'); // submit button
var alert = $('.alert'); // alert div for show alert message
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: '//mydomain.com/'+ID,
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Sending....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('✔ Alert Successfully Sent!'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
This may help you understand more about variable scope
This question already has answers here:
Ajax - How refresh <DIV> after submit
(5 answers)
Closed 7 years ago.
// My jquery for form submission
$(document).ready(function() {
var form = $('#form1'); // contact form
var submit = $('#submit1'); // submit button
var alert = $('.alert1'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
// sending ajax request through jQuery
$.ajax({
url: 'giftcard_check.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Checking....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Apply'); // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
// My form
<p>
<form action="" method="post" id="form1">
<input type="text" name="valuebox" placeholder="type your code" required />
<button name="submit" class="button1" type="submit" id="submit1">Apply</button>
</form>
</p>
<div class="alert1">Hello</div>
// giftcard_check.php
include("include/dbconnection.php");
dbconnect();
session_start();
$_SESSION['fromttl'] = 0;
$valuebox = $_POST['valuebox'];
$query = "SELECT * FROM db_coupon WHERE code='$valuebox' AND publish='1'";
$result = mysql_query($query);
$length = mysql_num_rows($result);
$rows = mysql_fetch_array($result);
$discount = $rows['discount'];
if($length == 1)
{
$_SESSION['fromttl'] = $discount;
echo $_SESSION['fromttl'];
}
else
{
$_SESSION['fromttl'] = 0;
echo "Invalid Gift Card!";
}
My question is how to refresh a particular div (ie,
<div id="show"><?php echo $_SESSION['fromttl']; ?></div>
) immediate after the form submission.
My current result not refreshing the particular div after form submission. I don't want to refresh whole page, only a particular div. If i refresh whole page the div will be refreshed.
Is there any solution? I am stuck here.
You should try this, put a return false;at the end of your form.on('submit',... it will not submit your form request and you will stay on the same page :
// My jquery for form submission
$(document).ready(function() {
var form = $('#form1'); // contact form
var submit = $('#submit1'); // submit button
var alert = $('.alert1'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
// sending ajax request through jQuery
$.ajax({
url: 'giftcard_check.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Checking....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.html('Apply'); // reset submit button text
if(data != 'Invalid Gift Card!') {
$('div.show').html(data);
}
},
error: function(e) {
console.log(e)
}
});
return false; //Will not active the form submission
});
});
// My form
<p>
<form action="" method="post" id="form1">
<input type="text" name="valuebox" placeholder="type your code" required />
<button name="submit" class="button1" type="submit" id="submit1">Apply</button>
</form>
</p>
<div class="show"></div>
<div class="alert1">Hello</div>
After your form submission, you can clear the content of div as:
$("#show").html("");
Then, update the div content as you required.
empty the content of the division you want using jQuery empty()
for example if you want to clear that div after form reset then simply add
...
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
$('#show').empty(); // clear div from previous content
submit.html('Apply'); // reset submit button text
},
...
in case that "show" div needs not to be empty use html()
I'm attempting to use ajax/jquery to submit a form comprised of dropdown menus, with the intention of displaying information from a MySQL database based on the form input. Without ajax/jquery, the page functions properly. However, I don't want the page to refresh once the form is submitted, so that the selected dropdown options remain showing. My ajax/jquery is not very good, and I know this is where I'm having trouble. my code is as follows:
<script>
$(document).ready(funtion(){
var $form = $('form');
$form.submit(funtion(){
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
success: displayResults
});
});
});
</script>
the function displayResults is the function that I want to call when the form is submitted, but as of right now, when i click submit, the form refreshes and no results are displayed. Any help would be greatly appreciated. Thanks in advance.
<script>
$(document).ready(funtion(){
var $form = $('form');
$form.submit(funtion(e){
e.preventDefault();
$.ajax({
type: "POST",
data: $(this).serialize(),
cache: false,
success: displayResults
});
});
});
</script>
This prevents the form from submitting by preventing the event from firing. In vanilla javascript you could return false on submit and it would be the same.
Try this way to submit your form and prevent default behavior of form submit using e.preventdefualt() which will prevent event from firing,To serialize form data use serializeArray() ,use success and error to debug ajax call.
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
console.log(data); //display data Results
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(errorThrown); // dispaly error
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
The .submit() it will be the same as use the submit button. You have to use a button with the click event.
<script>
$(document).ready(funtion(){
var data1 = $('#field1').val();
// the same with all the values
$('#button').click(function(){
$.ajax({
type: "POST",
data: ({dat1: data1} ),
cache: false,
success: function(data) {
displayResults();
}
});
});
});
</script>
My Form HTML looks like this.
<form novalidate action="register.php" method="post" >
<label for="username">Username</label>
<input type="text" name="username" required placeholder="Your username" autofocus/>
<input type="submit" name="register" value="Register" cid="submit" />
</form>
And My jQuery looks like this
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
e.preventDefault();
});
The sad thing is that it logs hello to the console but it never submits the form with one click on the submit button. I need to press two times to submit button.
Can anyone tell me the problem and how can I fix it so that 1 click is sufficient for form submission.
NOTE: The data of form is send for validation not actually for submission . If data like email , username etc are valid i want the form to be submitted with one click.
Try separating the validation from the form submit.
Simply changing this line:
$("form").submit(function(e) {
to
$("input[name='register']").click(function(e) {
First of all I think it would be cleaner to use a success function instead of a .done() function. For example:
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
// Merge the check.php and register.php into one file so you don't have to 'send' the data twice.
url: "register.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON",
success: function() {
console.log("This form has been submitted via AJAX");
}
});
});
Notice that I removed the .unbind() function, as I suspect it might be the reason your code is acting up. It removes the event handlers from the form, regardless of their type (see: http://api.jquery.com/unbind/). Also, I put the e.preventDefault() at the start. I suggest you try this edited piece of code, and let us know if it does or does not work.
EDIT: Oh, and yeah, you don't need to submit it when you're sending the data via AJAX.
Try this one.
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
});
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datatype: "JSON",
success: function(data) {
return data;
}
});
});
So, to break it down.
Stop the form submission with the preventDefault().
Get the form data and submit it to your validator script.
The return value, I assume, is a boolean value. If it validated, it'll be true, or false.
Return the value which will continue the form submission or end it.
NB.: This is a horrible way to validate your forms. I'd be validating my forms on the server with the form submission, because javascript can be terribly easily monkeyed with. Everything from forcing a true response from the server to turning the submission event listener off.
Once I have the same issue
What I found is I have some bug in my url xxx.php
it may return error message like "Notice: Undefined variable: j in xxx.php on line ....."
It may let ajax run unexpected way.
Just for your info.
Instead of doing prevent default when clicking a submit button, you can create a normal button and fire a function when you click it, at the end of that function, submit the form using $('#form').submit();. No more confusing prevent default anymore.
You don't need to call submit() since you are posting your data via ajax.
EDIT You may need to adjust the contentType and/or other ajax params based on your needs. PHP example is very basic. Your form is most likely much more complex. Also, you will want to sanitize any php data - don't rely on just the $_POST
jQuery:
$("form").submit(function(e) {
$.ajax({
'type': 'post',
'contentType': 'application/json',
'url': 'post.php',
'dataType': 'json',
'data': { formData: $(this).serialize},
'timeout': 50000
).done(function(data) {
// Response from your validation script
if (data === true)
{
// SUCCESS!
}
else
{
// Something happened.
}
).fail(function(error) {
console.log(error);
});
e.preventDefault();
});
PHP
$is_valid = FALSE;
$name = $_POST['name'];
if ($name !== '')
{
$is_valid = TRUE;
}
else
{
return FALSE;
}
if ($is_valid)
{
// insert into db or email or whatver
return TRUE;
}