make a $.post before form action takes place - php

I have a form and when the user clicks the submit button I want to run a separate PHP script before the form-action (going to the next page) gets executed.
Of course I can stop the form-action with evt.preventDefault(); and then I can fire my jquery $.post call but then I cannot 'resume' or undo this preventDefault call, as far as I can see.
So what is the best way to execute a script that process some information after a user clicks the submit button BUT before the user gets redirected to the next page defined in the form action tag?
(Of course I could just carry over the data and perform whatever I want on the next page – but in this case, I would like to keep it separate).
Thanks for any suggestions!

You can try something like this:
var posted = false;
$('form').on('submit', function(ev) {
if ( ! posted ) {
ev.preventDefault();
$.post(url).done(function() {
posted = true;
$('form').trigger('submit');
});
}
posted = false;
});
Or more succinct, using extra parameters:
$('form').on('submit', function(ev, posted) {
if ( ! posted ) {
ev.preventDefault();
$.post(url).done(function() {
$('form').trigger('submit', [true]);
});
}
});

Your $.post call can be run synchronously, so the form would not submit until you've got a response from the server.
You can submit the form programmatically, perhaps in your callback function.

prevent default on form, then run post, on success of post, target the form by id and use .submit();
$('#submit-button').click(function(e) {
e.preventDefault();
$.post({
url:'url',
success:function() {
$('#formid').submit()
}
});
});

Go head with your evt.preventDefault().
Make an $.ajax() call to run your php script.
In the $.ajax() success/failure callback, check the output of the php script you want to run, and accordingly make a $.post call (or not).

You can always hook the click event, and do your stuff.
When you are done you just do $(form).submit();
Working example
$("#submitbutton").click(function(e) {
e.preventDefault();
// do your ajax stuff here.. $.post().
$("#form").submit();
});

You can use just use the native submit function instead of jQuery's submit() which goes through the event handler again
$('form').submit(function(e){ // change form to your form id
e.preventDefault();
var el = this; // store this form in variable
$.post('/echo/html/',data,function(d){ // your post function
el.submit(); // trigger native submit function in success callback
});
});
FIDDLE

In your form tag, add onsubmit="myfunction()"

Related

how to pass data to server without using form submit in laravel 4?

I'm a new user of laravel. I have problem in pass data to server in laravel 4.2. I didn't use a form submit, I use javascript to refer action of form such the code below:
$(document).ready(function(){
$(".delete_action").click(function(event){
$("#deletecategory").prop('href','/admin/category/'+ event.target.id +'/delete');
});
});
and my modal of delete like this:
×
​​​​​​​ Are you sure want to delete this category?
Yes
No
When i click Yes, it doesn't do anything. I hope to get some solution from you!
You can use http://api.jquery.com/jquery.ajax/ for this.
$('#yourOkButton').click(function(){$.ajax(...);});
In the documentation of $.ajax is everything written down.
You need to include an ajax call... to actually submit data...
Like so...
$(document).ready(function(){
$(".delete_action").click(function(event){
// incase the button is inside a form, this will prevent it from submitting
event.preventDefault();
// get your url
var url = '/admin/category/'+ event.target.id +'/delete';
// Create alert to confirm deletion
var conf = confirm("Are you sure you want to Delete this?");
if(conf){
// If they click yes
// submit via ajax
$.ajax({
url:url,
dataType:'json',
success:function(data){
//put anything you want to do here after success
// Probably remove the element from the page since you deleted it //So if the button is part of a parent div that needs to be removed.
}
});
}
});
});
You could also use $.get instead of $.ajax to shorten the code some more...
$.get(url, function(data){
//remove element after success
});
But I realize youre trying to pass the url to a modal window, and then submitting that modal window. So you need to attach the ajax call to the modal window button. Not like above, which is just opening an alert window. Its the easier way, but less fancy looking. If you really want a modal. You need to attach the above code to the modal confirm button. But the gist is the same.

Form submits 1st via jQuery, 2nd via PHP

I have a form which when submitted is processed via jQuery ajax call to a PHP script.
The 1st time the form is submitted, jQuery catches the event, runs the ajax call and PHP script and returns the data from the PHP script putting it in the required HTML elements.
However, if the submit button is pressed a 2nd time, the form is submitted normally and jQuery is unable to "preventDefault" so to speak. So the whole page is reloaded.
the jQuery code
$(document).ready(function() {
// catch form submittion
$('#user_account_form').submit(function(ev) {
// prevent default action and propagation
ev.preventDefault();
ev.stopPropagation();
// pull data from the form attributes
var href = $(this).attr('action');
var postData = $(this).serializeArray();
// run the ajax call
var request = $.ajax({
url: "view/jquery/" + href,
type: "post",
data: postData,
dataType: "json"
});
// ajax call completed?
// -- echo returned data to elements
request.done(function(data) {
// put the refreshed form (provided by PHP script) in the #user_account element
$('#user_account').html(data.form);
// put the system message (provided by PHP script) in the #sysmsg element
$('#sysmsg').html(data.sysmsg).delay(2000).fadeOut(100);
});
// on fail, log to console
request.fail(function(jqXHR, textStatus, errorThrown) {
console.log('error processing form data: ' + textStatus + " [" + errorThrown + "]");
});
});
});
the PHP code
this is basically a simple script that checks the entered data from the form
against the data in the database. If the entered password equals the database
password the database is updated, otherwise it will only return a system message
to the user that the password was incorrect.
I believe the fault is that I'm missing something in my jQuery code that makes jQuery catch the 2nd, 3rd, 4th, etc. submission.
Try:
$('#user_account_form').on('submit', function(ev) {});
Instead of:
$('#user_account_form').submit(function(ev) {});
This is because as I understood, your submit button is in the data that is refresh from the back end, which means that the button is not bound to any events as it's a completely new button. jQuery on will bind the event to all instances of that element, even if they are created in the future.
Important: If you use jQuery < 1.7, instead of on() use live().
Maybe try to use a counter so you'll know how many time you've clicked on your submit btn
$(document).ready(function() {
var counter = 0;
// catch form submittion
$('#user_account_form').submit(function(ev) {
// If first click
if(counter === 0){
// Do the preventDefault and ajax thing
}
else{
// Do nothing or what you expect for a >2nd click
}
// Increment counter
counter++;
})
});
After reading your posts about the PHP script building a completely new form and therefore not binding the submit button preventing jQuery from catching subsequent submissions, I figured "Why build a whole new form if I only need to refresh 1 or 2 fields?".
So I changed my PHP script to return only the data from the database of the changed fields and send that in a json format to my jQuery script. Then adjusted my jQuery script to read the json object, and put the new values into the corresponding fields.
Now it works as intended.
changed jQuery code
....
request.done(function(data) {
$('#email').val(data.email);
$('#sysmsg').html(data.sysmsg).delay(2000).fadeOut(100);
});
changed PHP code
....
$email = $main->getUserDetails('email');
$array = array("sysmsg" => $msg, "email" => $email);
$data = json_encode($array);
echo $data;
Thanks for your input all, it helped me figuring out what to change to improve my code.

Jquery load Php file

Am currently using a Jquery load function to load php content into Div. But when I use my php e-mail form it turns all white an the index page is lost(the main layout I mean). Is there anyway I can use Jquery to load Insch.php back into the div even when it needs to be executed?
<form id="contactform" method="POST" action="insch.php"> <--- this is my Form
$('.menut').click(function () {
var phpFile = $(this).attr('id') + '.php';
/* alert(phpFile)*/
$.get(phpFile, function (data) {
$('#box1').html(data);
});
return false;
}); <---- my Jquery load function(on index)
I see you add returning data directly into $("#box1"). If your php file returns Html you should set dataType:'html' in the ajax request.
Sorry, your question is kinda hard to understand. I'm kinda guessing, but it sounds like you're asking how to submit the form without the page refreshing. If so, you could do something like this:
$('.menut').click(function() {
var phpFile = $(this).attr('id') +'.php';
$('#box1').load(phpFile, function() { // <-- this is your ready function
// once the form has been added to the page,
// add the 'submit' event listener
$('#contactForm').submit(function(e) {
// prevent the form from submitting regularly (causing a page refresh)
e.preventDefault();
// get the data from the form
var data = $(this).serialize();
// submit the form via AJAX and put the response in #box1
$('#box1').load($(this).attr('action'), data);
});
});
});
UPDATE:
Your ready function is the function you create in your AJAX call to be executed when the content is done loading (when the content is ready). It may also be called a callback function, complete function, or a success function.
Take a look at the comment I added on the fourth line of code above. I have pointed out what I'm referring to as your ready function.
In your question, you used this:
$.get(phpFile, function (data) {
$('#box1').html(data);
});
Which is equivalent to:
$('#box1').load(phpFile);
This loads the response (your form) from phpFile into #box1. The function (data) { ... } is your ready function. That is where you should bind the submit event to the form.
If you switch to the load() method as I am suggesting, then you would just pass a new function (which will be your ready function) as the second parameter to the load() method, which is the solution I've given in my original answer.

Update SQL with JQuery and AJAX

I have an RSVP box on my website where I want people to click the tick or cross image depending on whether they are coming or not. I currently have a PHP system that updates a SQL database but it reloads the page.
I have tried this code:
$(document).ready(function() {
var options = {
url: 'process.php',
type: 'post',
data: 'attending',
success: success
};
// bind to the form's submit event
$('.attending').click(function {
$(this).ajaxSubmit(options);
return false;
});
function success(responseText, $form) {
$(".attending").hide();
$(".success").fadeIn();
}
});
The RSVP buttons are links with tags
But I am strugling with this, any help would be appreciated!
Thanks
The ajaxSubmit function is part of the jquery forms plugin ... are you including that plugin with the page? (You didn't tag the question with jquery-forms-plugin, so I'm guessing no) If this is your first go at jQuery ajax, I'd recommend using the .ajax method first, even though it's more lines of code, to get an understanding of what's going on there.
You missed the brackets after declaring the function in your click handler, try this:
// bind to the form's submit event
$('.attending').click(function() {
$(this).ajaxSubmit(options);
return false;
});
Or better yet:
// bind to the form's submit event
$('.attending').click(function(e) {
e.preventDefault();
$(this).ajaxSubmit(options);
});

JQuery Colorbox and Forms

I have a form which I want to submit and show in Colorbox.
The form is Mals Ecommerce View Cart.
See: https://www.mals-e.com/tpv.php?tp=4
I want it to Show the Cart contents in a colorbox iframe. Is this possible to do using the FORM method rather than the Link method?
here the best answer..
add this to your submitbutton : id="SearchButton"
then use this:
$(document).ready(function() {
$("input#SearchButton").colorbox({href: function(){
var url = $(this).parents('form').attr('action');
var ser = $(this).parents('form').serialize(); //alert(url+'?'+ser);
return url+'?'+ser;
}, innerWidth:920, innerHeight:"86%", iframe:true});
});
test at: http://wwww.xaluan.com or http://wwww.xaluan.com/raovat/
I recently faced this problem, spent some time searching the solution and found this:
$("#submit_button").click(function () { // ATTACH CLICK EVENT TO MYBUTTON
$.post("/postback.php", // PERFORM AJAX POST
$("#info_form").serialize(), // WITH SERIALIZED DATA OF MYFORM
function(data){ // DATA NEXT SENT TO COLORBOX
$.colorbox({
html: data,
open: true,
iframe: false // NO FRAME, JUST DIV CONTAINER?
});
},
"html");
});
I.e. Colorbox uses submitting the form via standard jQuery methods. Hope this helps someone.
Try
$("input#formsubmit").colorbox({title: function(){
var url = $(this).parents('form').attr('action');
}});
Not tested, I just took the syntax from the Colorbox page. You'd have to give your submit button an id of "formsubmit" for the above to work.
you can open colorbox independently using:
jQuery.colorbox({href:,iframe:true, opacity:0.6 ,innerWidth:760,innerHeight:420,title:});
and you can call this function on any event like:
jQuery("document").ready(function(){ jQuery.colorbox.. });
when u submit a form send a query parameter along with it. When after submission you reach back the form. see if that parameter is populated.
and then call jQuery.colorbox()

Categories