I'm inserting data into a table using Ajax. I'm using ajax so my page wouldn't get refresh. Here is my Ajax code for calling the inserting page:
<script type="text/javascript">
var i = jQuery.noConflict();
i(document).ready(function(){
i('#myForm').on('submit',function(e) {
i.ajax({
url:'insert.php',
data:$(this).serialize(),
type:'POST'
});
e.preventDefault();
});
});
</script>
Now every time i write in the textbox and hit the submit button the data gets entered but it remains in textbox and i have to press the delete button to erase it.
Question: how can I make so my data gets cleared when I press the submit button?
You can reset the form in the ajax success handler
var i = jQuery.noConflict();
jQuery(function ($) {
$('#myForm').on('submit', function (e) {
$.ajax({
url: 'insert.php',
data: $(this).serialize(),
type: 'POST',
context: this
}).done(function () {
this.reset();
});
e.preventDefault();
});
});
document.getElementById('myForm').reset(); // In Javascript
$("#myform")[0].reset(); // In jQuery Fashion
You can reset form fields on the completion as suggested by arun or on success as below
var i = jQuery.noConflict();
jQuery(function ($) {
$('#myForm').on('submit', function (e) {
$.ajax({
url: 'insert.php',
data: $(this).serialize(),
type: 'POST',
success:function(data) {
$('#myForm')[0].reset();
}
});
e.preventDefault();
Hope it helps
Related
I've small JS code which is not working as per my need.
Actually my backend PHP code contains so many functions which i want to process by pressing submit button and meantime i also want to show the status "Scanning" in place of submit button and when the data got fully processed, then i want to show "Completed" Status in place of submit button.
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
$(#response).show();
$(#form).hide();
}
});
});
});
</script>
You can simply show whatever you want when user clicks the button. And when you get the response you can change to whatever you want. Something like.
This is just an example of mocking your ajax request.
var $button = $("#btn");
$button.click(function() {
$button.text("Scanning...");
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 5000);
});
promise.then(function(){
$button.text("Done");
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn"> Submit </button>
You can use beforeSend...
beforeSend is a pre-request callback function that can be used to modify the jqXHR..
You can refer here for more detail.
And you can follow my code below for your ease.
..
Javascript:
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
let submitBtnEl = $(this).find('button[type="submit"]'); //submit button element
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
beforeSend: function( xhr ) {
submitBtnEl.html('Scanning'); //the submit button text will change after click submit
},
success: function () {
$(#response).show();
$(#form).hide();
submitBtnEl.html('Completed'); //the submit button text will change after the form is completely submit
}
});
});
});
</script>
.
.
HTML:
<form>
<input type="text" name="input1" />
<button type="submit">Submit</button>
</form>
.
.
For your ease, you can try the code on this fiddle
I would like to get an id from a button. I need this id in my ajax request. This is my button:
<form>
<div class="form-group">
<button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delete</button>
</div>
</form>
I'm getting the id of the button this way:
<script type="text/javascript">var JcarID = this.id;</script>
Finally my Ajax Request.
$('[name="deletecar"]').click(function (e)
{
var JcarId = this.id;
e.preventDefault();
$.ajax({
type: "POST",
url: '{{ action('CarController#delete', [$user->id, $car->id])}}',
success: function (data)
{
// alert(data);
}
});
});
Thx for reading!
SOLUTION
Changed some bits in my code. I changed the url of my request.
$('[name="deletecar"]').click(function (e)
{
e.preventDefault();
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/deletecar/'+this.id,
success: function (data)
{
// alert(data);
}
});
});
Hard to guess what is your requirement yet either if you want to get the button id value
this.attr('id'); or this.prop('id');
Or if you want to set the id value of button
$('[name="deletecar"]').attr('id', yourvalue)
I think you want to use JcarId rather $car->id in ajax request. Here what you can do rather than directly using PHP code in ajax call.
$('[name="deletecar"]').click(function (e)
{
var JcarId = this.id;
e.preventDefault();
$.ajax({
type: "POST",
url: '/CarController/delete',
data: {'carId':JcarId}
success: function (data)
{
// alert(data);
}
});
});
So I'm trying to send the form info to php with ajax form every second, but for some reason it doesn't want to.
Here is my latest attempt, I tried every other similar combination(like put everything in the function or just put everything into the setInterval).
$(document).ready(function() {
var ajaxCall=function() {
$("#myForm").ajaxForm(function(e) {
$.ajax({
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data) {
document.getElementById("result").innerHTML=data;
}
});
});
}
setInterval(ajaxCall,1000);
});
EDIT
Solved with M.M answer, thank you for the help!
Simply change ajaxForm to ajaxSubmit
See this (question) and this (documentation) for more information on AjaxForm vs AjaxSubmit
Essentially AjaxForm submits when the user clicks the button and AjaxSubmit does it immediately so your code should be:
$(document).ready(function()
{
var ajaxCall=function()
{
$("#myForm").ajaxSubmit(function(e)
{
$.ajax(
{
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data)
{
document.getElementById("result").innerHTML=data;
}
});
});
}
setInterval(ajaxCall,1000);
});
Update after comment explanation
$(document).ready(function(){
//live feed
var ajaxCall=function(){
$("#myForm").ajaxSubmit(function(e){
ajax_submit();
});
}
setInterval(ajaxCall,1000);
//real submit
$("#myForm").ajaxForm(function(e){
ajax_submit();
});
function ajax_submit(){//ajax_code
$.ajax({
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data) {
document.getElementById("result").innerHTML=data;
}
});
}
});
If you wish to differentiate the feed from the submit you can pass a parameter to the ajax_submit function
Getting rid of the ajaxForm() call seems to accomplish what you are trying to do:
$(document).ready(function() {
var ajaxCall = function() {
$.ajax({
type: 'post',
url: 'php1.php',
data: $("#myForm").serialize(),
success: function(data) {
document.getElementById("result").innerHTML = data;
}
});
}
setInterval(ajaxCall, 1000);
});
I'm sure there's a simple explanation for this but I haven't been able to find the right words to use when searching for answers.
When users fill out the form .InvoiceForm it submits via Ajax. After it's submitted remove the .InvoiceForm class and add .UpdateInvoice. When a user submits a .UpdateInvoice form it explains that they are about to make a change and they have to click to say "Yes I want this to be updated".
The issue is that unless I refresh the page so that the form is loaded with the .UpdateInvoice form, I don't get the confirmation which means it's still submitting as a .InvoiceForm form. Is there anything I can do to fix this?
Edit to show code:
Code that runs if there's no record
$('.InvoiceForm').submit(function(e) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
$(this).removeClass('InvoiceForm');
$(this).addClass('UpdateInvoice');
$(this).find('.btn').val('Update');
$(this).find('.id').val(data.invoice_id);
$(this).find('.btn').removeClass('btn-default');
$(this).find('.btn').addClass('btn-danger');
$(this).find('.AddRow').removeClass('hide');
$(this).find('.invoiceDetails').html(data.returnedData);
$(this).parent().next().find('.grade').focus();
}
});
return false;
};
Code that runs if there is a record being updated
$('.UpdateInvoice').submit(function(){
var r = confirm("Are you sure you want to make this update?");
if (r == true) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
alert('This row has been updated');
$(this).find('.total').html(data);
}
});
} else {
}
return false;
});
The function for .UpdateInvoice doesn't run unless I refresh the page.
Thanks for your help.
You bind a click event on '.UpdateInvoce' before it even being created, hence it'll not work. I think you need to use .live() in order to make it works. See document here: jQuery's live()
HTML:
<button id="click_me" class="new">Click Me</button>
<div class="result" />
Script:
$(function () {
$('.new').click(function (e) {
$('.result').text("Im new !");
$(this).removeClass("new");
$(this).addClass("update");
// Bind UpdateInvoice's click event on the fly
$('.update').live(bindUpdate());
});
function bindUpdate() {
$('.update').click(function (e) {
$('.result').text("Update me !");
});
}
});
jsfiddle's demo
I have the following code which is supposed submit a form via Ajax without having to reload the page:
$( document ).on('submit', '.login_form', function( event ){
event.preventDefault();
var $this = $(this);
$.ajax({
data: "action=login_submit&" + $this.serialize(),
type: "POST",
url: _ajax_login_settings.ajaxurl,
success: function( msg ){
ajax_login_register_show_message( $this, msg );
}
});
});
However for some reason, despite the event.preventDefault(); function which is supposed to prevent the form from actually firing, it actually does fire.
My question is, how do I prevent the above form from reloading the page?
Thanks
don't attach a listener on document instead use a on click handler on the submit button and change the type to button.
<button id="form1SubmitBtn">Submit</button>
$('#form1SubmitBtn').click(function(){
//do ajax here
});
Happy Coding !!!
for instance you can write like this
$(".login_form").on('submit', function( event ){
var $this = $(this);
$.ajax({
data: "action=login_submit&" + $this.serialize(),
type: "POST",
url: _ajax_login_settings.ajaxurl,
success: function( msg ){
ajax_login_register_show_message( $this, msg );
}
});
event.preventDefault();
});
You can use jquery and ajax to do that. Here is a nice piece code below that doesn't refresh the page but instead on submit the form gets hidden and gets replaced by a thank you message. The form data is sent to an email address using sendmail.php script.
Assuming your form has 3 input fields - name, email and message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function() {
jQuery("#button").click(function() {
var name=jQuery('#name').val();
var email=jQuery('#email').val();
var message=jQuery('#message').val();
var dataString = 'name='+ name + '&email=' + email + '&message=' + message;
jQuery.ajax({
type: "POST",
url: "sendmail.php",
data: dataString,
success: function() {
jQuery('#contact_form').html("<div id='message'></div>");
jQuery('#contactForm').hide();
jQuery('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>Thank you for your submission. We will be in touch shortly.</p>").hide()
.fadeIn(1500, function() {
});
}
});
return false;
});
});
</script>
On top of your form tag just add this to display the thank you message.
<div id='message'></div>
Enjoy coding!!!!!!!