as title states I'm struggling with making delayed post submission so ajax call can complete.
So far I've this, any ideas why it wouldn't work?
//Jquery
jQuery(document).ready(function($) {
$("#save").on("click", function(e){
//Prevent submission of post data before ajax success in function reverse_geocoding
e.preventDefault();
//ajax
reverse_geocoding(lat_onclick,lng_onclick,true);
}
});
function reverse_geocoding(latitude,longitude,submit) {
//get country/city/state using lat and long data
jQuery.ajax({
url: "<?php bloginfo('template_url'); ?>/reverse-geocoding.php",
type: "GET",
data: "latitude=" + latitude + "&longitude=" + longitude,
cache: false,
success: function (data){
var response = jQuery.parseJSON(data);
},
complete: function() {
if (submit) {
$("#add_to_map").submit();
}
}
});
}
});
//End Jquery
html part:
<form method="post" name="update_profile_maps" id="add_to_map" action="">
//some inputs here.
</form>
Rather than using a <submit> tag, use a normal <button> (which is not of type submit; note that type submit is the default). When the button is clicked, fire your ajax and then submit the form using JavaScript if the ajax completes successfully.
Related
I have a form calling submitting as follow
<form action="" method="post" id="member_form" onsubmit="return json_add('member','<?php echo ($admin->getnew_id()); ?>','0','slider_form');">
The problem I have is to get the $new_id before submitting the form from another function class.
this is not working
It keep running the funtion getnew_id() and generate the ID before it is saved
I need the process as follow.
Form Open
User complete form
onsubmit it need to do follow.
a. get new id = $new_d
b. then do
return json_add('member','','0','slider_form');">
I tried the following but dont work
$("form").submit(function(){
$.ajax({
url:"lastid.php",
type:'POST',
success:function(response) {
var $new_id = $.trim(response);
return json_add('member-add',$new_id,'0','slider_form');
alert("Submitted");
}
});
The problem seems to be in the third step.
What you should do is prevent the form from submitting and handle it in ajax.
you need onsubmit="return false" to prevent the form from submitting
Next, handle the submission in ajax
$("form#member_form").submit(function(){
$.ajax({
url: "lastid.php",
type: "POST",
data: { // this is where your form's datas are
"json": json_add('member-add',$new_id,'0','slider_form'),
"key": $("form#member_form").serialize()
},
success: function(response) {
var $new_id = $.trim(response);
alert("Submitted");
// alerting here makes more sense
}
// return json_add('member-add',$new_id,'0','slider_form');
// returning here do nothing!
});
You can read more about using ajax in jQuery here
I am facing issue, i f i am using ajax call, the return false not working..
and form submitted sucessfully.. I want that when i get response 1 form don't submit.. but on ajax request response form still submitting please help me..
here is code:
<form action="<?php echo base_url(); ?>do/add/review" method="post" name="dologin" id="dologinsubmitreview" onSubmit="return showpopupbox();">
function showpopupbox(){
var strs = $("form").serialize();
var autocompleteURL = "<?php echo base_url(); ?>grahak/save_record_session?rnd=" + Math.random() +"&sessiondata="+ $("form").serialize();
$.ajax({
url : autocompleteURL,
async: false,
cache: false,
method : "POST",
success : function(respd)
{
if(respd == 1){
$("#classiconpopupbx").show();
return false;
}
else {
return true;
}
}
});
}
You need to redesign your flow. Javascript is asynchronous, which means that the form is submitted LONG before the AJAX call is complete.
Instead, use jQuery on to bind to the event, capture the event in the function, and run event.preventDefault() immediately which will stop the form from submitting. THEN run your AJAX call.
In your AJAX success function, you'll need to decide what to do when it comes back "truthy". Without knowing more about your desired outcome, it's impossible to advise how to handle that piece.
<!-- remove the inline onsubmit script handler -->
<form action="<?php echo base_url(); ?>do/add/review" method="post" name="dologin" id="dologinsubmitreview">
// no-conflict safe document ready
jQuery(function($) {
// Bind to the form submit here, and call event.preventDefault immediately
$('#dologinsubmitreview').on('submit', function(event) {
event.preventDefault();
showPopUpBox(event);
}
function showpopupbox() {
var strs = $("form").serialize();
var autocompleteURL = "<?php echo base_url(); ?>grahak/save_record_session?rnd=" + Math.random() +"&sessiondata="+ $("form").serialize();
$.ajax({
url : autocompleteURL,
async: false,
cache: false,
method : "POST",
success : function(respd) {
if(respd == 1){
$("#classiconpopupbx").show();
} else {
// Do what you need to do here if the AJAX is true
}
}
});
}
});
One way you can do this is to prevent the submit, always, then if your Ajax call returns true, post the form (and tell the code to allow it this time):
For starters, don't mix inline event handlers with jQuery. The jQuery way is better:
// Start by not allowing submit
var allowSubmit = false;
$('form').submit(function(){
var $form = $(this);
// Only run the ajax if this is not a "real" submit
if (!allowSubmit){
// do the ajax call
$.ajax({
url: ...
success: function(respd){
if(respd == 1){
$("#classiconpopupbx").show();
}
else {
allowSubmit = true;
$form[0].submit(); // important - bypass jQuery event handler
}
}
});
}
// Conditionally allow the form to submit
return allowSubmit;
});
I have a form from which I want latitude and longitude and I want want load this without submit button.
<form method="post" id="myform" action="" >
<input type='hidden' value='' name='latitude'/>
<input type='hidden' value='' name='longitude'/>
</form>
I tried
document.getElementById("myForm").submit();
But it causes infinite loop and I want it on the same page so I am not giving action.
I add this function but still not working.
function send_data(lat, lon) {
document.getElementById('place_lon').innerHTML = lat + ' : ' + lon;
// $("input[name='lattitude']").val(lat);
// $("input[name='longitude']").val(lon);
$j = jQuery.noConflict();
$j(document).ready(function() {
$j('#myform').submit(submit_myform);
});
function submit_myform() {
$j.ajax({
url: window.location.href,
type: 'POST',
data: $j(this).serialize(),
dataType: 'json', //data type of Ajax response expected from server
success: myform_success //callback to handle Ajax response and submit to Paypal
});
return false;//prevent normal browser submission, since the form is submitted in the callback
}
function myform_success(response) {
//this is called whenever the ajax request returns a "200 Ok" http header
//manipulate the form as you wish
$("input[name='latitude']").val(lat);
$("input[name='longitude']").val(lon);
// $j('#lattitude').val(lat);
// $j('#longitude').val(lon);
//submit the form (to the form's action attribute)
document.forms['#myform'].submit();
}
}
What happens is that as soon as form is loaded it submits itself, then loads again and submits etc.
Try using AJAX request to send data to the server.
$.ajax({
type: "POST",
url: window.location.href,
data: $('#myForm').serialize()
});
I have ajax request:
<script>
$("#abc_form_submit").click(function(e) {
e.preventDefault();
//........
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $("#abc_form").serialize(), // serializes the form's elements.
success: function(data)
{
if(data.success == 'false') {
// show errors
} else {
// SUBMIT NORMAL WAY. $("#abc_from").submit() doesnt work.
}
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
And php
.....
return $this->paypalController(params, etc...) // which should redirect to other page
.....
How should i make that ajax request if success, submit form normal way, because now if I redirect (at PHP) its only return response, but i need that this ajax request would handle php code as normal form submit (if success)
Dont suggest "window.location" please.
I would add a class to the form to test if your ajax has already occured. if it has just use the normal click funciton.
Something like:
$('form .submit').click(function(e) {
if (!$('form').hasClass('validated'))
{
e.preventDefault();
//Your code here
$.post(url, values, function(data) {
if (success)
{
$('form').addClass('validated');
$('form .submit').click();
}
});
}
}
Why don't you use a result variable that you update after a succesful AJAX request?
<script>
$("#abc_form_submit").click(function(e) {
e.preventDefault();
// avoid to execute the actual submit of the form if not succeded
var result = false;
//........
$.ajax({
type: "POST",
url: url,
dataType: 'json',
async: false,
data: $("#abc_form").serialize(), // serializes the form's elements.
success: function(data)
{
if(data.success == 'false') {
// show errors
} else {
// SUBMIT NORMAL WAY. $("#abc_from").submit() doesnt work.
result = true;
}
}
});
return result;
});
</script>
I've had this issue before where I needed the form to submit to two places, one for tracking and another to the actual form action.
It only worked by submitting it programatically when you put the form.submit() behind a setTimeout. 500ms seems to have done the trick for me. I'm not sure why browsers have trouble submitting the form programatically when they are attempting to submit them traditionally, but this seems to sort it out.
setTimeout(function(){ $("#abc_from").submit(); }, 500);
One thing to keep in mind though once it submits, that's it for the page, it's gone. If you still want whatever processes are running on the page to run, you will need to set the target of the form to _blank so that it will submit in a new tab.
I am using ajax to update the db with a new folder but it refreshes the page after ENTER is hit.
on my form I have onkeypress="if(event.keyCode==13) savefolder();"
here is the javascript code that I have: what it does basically is after you hit enter it calls the function savefolder, savefolder then sends a request through ajax to add the folder to the db. Issue is it refreshes the page... I want it to stay on the same page.
any suggestions? Thank you
<script>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
// ajax request to add the folder
jQuery.ajax({
type: 'get',
url: 'addfolder.php',
data: 'foldername=' + foldername + '&foldercolor=' + foldercolor,
beforeSend: function() { alert('beforesend');},
success: function() {alert('success');}
});
return false;
}
</script>
This is working:
<form>
<input type="submit" value="Enter">
<input type="text" value="" placeholder="search">
</form>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
jQuery.ajax({
type: 'get',
url: '/echo/html/',
//data: 'ajax=1&delete=' + koo,
beforeSend: function() {
//fe('#r'+koo).slideToggle("slow");
},
success: function() {
$('form').append('<p>Append after success.</p>');
}
});
return false;
}
jQuery(document).ready(function() {
$('form').submit(savefolder);
});
http://jsfiddle.net/TFRA8/
You need to check to see if you're having any errors during processing (Firebug or Chrome Console can help). As it stands, your code is not well-formed, as the $(document).ready() is never closed in the code you included in the question.
Simply stop the propagation of the event at the time of the form submission
jQuery(document).ready(function($) {
$("#whatever-form-you-are-pulling-your-values-from").submit(function(event) {
var foldername = $('#foldername').val();
var foldercolor = $('#foldercolor').val();
event.stopPropagation();
// ajax request to add the folder
$.ajax({
type: 'get',
url: '../addfolder.php',
data: 'ajax=1&delete=' + koo,
beforeSend: function() { fe('#r'+koo).slideToggle("slow"); },
success: function() { }
});
});
Since by default on a form the enter button submits the form, you need to not only handle this with your own code, but cancel the event after.
Try this code instead:
onkeypress="if(event.keyCode==13) {savefolder(); return false;}"
The onkeypress event will that the return value of the javascript and only continue with it's events if it returns true.