HTML form submit not working after being loaded with ajax - php

so I am loading a portion of a page using jquery/ajax.
On the page the user sees, there is a "menu" where they select the date of the signup form they want to see. All the forms are hosted on another page, each one inside a div id'd with the respective date of the form. When the user clicks and item on the menu, there is an ajax call that displays the correct form on the user's page, pulling it from the other page by it's parent div and id.
The plugin I am using for the signup forms (it is a Wordpress site) has the page reload when you click Sign up, which then takes you to a form to fill out. I have it so that the user's page does not reload, but via ajax shows the form. This all works great - the only problem now is when the user clicks to submit the form. This should be a normal form submit not using ajax, as I am not sure how to modify the plugin code to utilize it. For some reason, the form is never actually submitted although the user's page does reload.
*NOTE: I am currently using the same exact signup form for each date, but once it is functional it will be a different signup form for each. This should not effect any functionality.
link to page user sees: summitsharks.net/volunteer-signup-page
link to page forms are hosted on: summitsharks.net/formhost
jquery/ajax code:
;(function($){
var ahref1;
$(document).ready(function(){
$(document).on('click', '.entry-content li a', function(e){
e.preventDefault();
ahref1 = $(this).attr('href');
$('#formloader').load('/formhost ' + ahref1);
return false;
});
});
$(document).ready(function(){
$(document).on('click', '.entry-content #formloader a', function(e){
e.preventDefault();
var ahref2 = $(this).attr('href');
$('#formloader').load(ahref2 + ' ' + ahref1);
return false;
});
});
})(jQuery);
PHP code of file that (I think) handles form submit:
http://pastebin.com/PeXB4Afi
I am looking for a solution that successfully signs the user up. If somebody knows how to alter the plugin code to accept ajax submission, or normal submission that actually works, either one is perfectly fine with me.
Thanks a lot for looking through and thanks in advance for your help!

The form is expected to be posted from it's original URL, including the HTTP GET parameters ?sheet_id=1&task_id=1&date=2016-06-30. Updating the form's action attribute to make it post to the proper URL can be done by changing
$('#formloader').load(ahref2 + ' ' + ahref1);
to
$('#formloader').load(ahref2 + ' ' + ahref1, function() {
$('#formloader form').attr("action", ahref2 + ' ' + ahref1 );
});
However, using AJAX to post the form, this can be skipped:
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
})
The utility method formdata (see code snippet below) converts jQuery's serializeArray() result to a proper hash.
In the working example below, I've moved the installation of form click handlers into the .load completion handler, rather than relying on jQuery to fire a second document ready event after injecting the form.
;jQuery(function($) {
$('.entry-content li a').off('click').on('click', function(e) {
var ahref1 = $(this).attr('href');
$('#formloader').load( "/formhost " + ahref1, function() {
$('.entry-content #formloader a').off('click').on('click', function(e) {
e.preventDefault();
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
});
return false;
});
});
return false;
});
});
function formdata(form) {
var data = {};
for ( var i in d = form.serializeArray() )
data[d[i].name] = d[i].value;
return data;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
UPDATE: Here is a code snippet that can be pasted in the browser's Javascript console:
$ = jQuery;
$('.menu-volunteermenu-container li a').off('click').on('click', function (e) {
loadFormSelector($(this).attr('href'));
return false;
});
$('#formloader').on('load', function(){console.log("FORMLOADER UPDATD")});
function loadFormSelector(ahref1)
{
console.log("Loading form selector");
$('#formloader').load('/formhost ' + ahref1, function ()
{
console.log('form selector loaded');
$('.entry-content #formloader a').off('click').on('click', function (e)
{
e.preventDefault();
loadForm(ahref1, $(this).attr('href') );
return false;
});
});
}
function loadForm(ahref1, ahref2)
{
var ahref = ahref2 + ' ' + ahref1;
console.log('Loading form', ahref);
$('#formloader').load(ahref, function () {
console.log('form loaded', arguments);
$('#formloader form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: ahref,
type: 'POST',
data: $.param(formdata($(this))),
success: function (data, status, jqXHR) {
$('#formloader').html( $(data).find( ahref1 ) )
}
});
return false;
});
$('#formloader a').on('click', function () {
loadFormSelector(ahref1);
});
return false;
});
}
function formdata(form) {
var data = {
};
for (var i in d = form.serializeArray())
data[d[i].name] = d[i].value;
return data;
}
It is refactored to show the 2-layer approach more clearly.

Related

How do I pass value from a input to another input and automatically load base on the input?

On first.php
I use jquery location.href ="www.localhost.com/second.php?text="+param to pass the input parameter to second.php (on hitting enter).
code for first.php:
$(document).ready(function() {
$("#txt").keypress(function() {
var name = $("#txt").val();
if (event.keyCode == 13) {
location.href = "http://www.localhost.com/second.php?text="+param;
}
});
});
On second.php
I get the value using $("#").val(decodeURIComponent($.urlParam("text")));
However I cannot get it to load automatically after the second page loads. So I am force to let the input value and data load when the input field is click.
here is the jquery:
$("#txt").one("mouseup", function() {
$("#txt").val(decodeURIComponent($.urlParam("text")));
var variable = $("#txt").val();
$.post("xxxx.php", {
text: variable
}, function(data, status) {
$("#show").html(data);
return;
});
});
I finally figure it out the answer to the question. To load the data immediately on second page(second.php) the Jquery script I added was:
$(document).ready(function() {
$(function() {
$("#txt").val(decodeURIComponent($.urlParam("text")));
var variable = $("#txt").val();
$.post("xxxx.php", {
text: variable
}, function(data, status) {
$("#show").html(data);
return;
});
});
});
There wasn't any need to add a listener for the window to load. The listener is already in the library.

ajax request page redirecting

I am loading a form named staff_view.php in main.php through ajax. It's loading fine but when I submit form to staff_post.php it's redirecting to it instead of showing in console, before I add the code for loading form using ajax it was posting fine but after it's redirecting.
Here is my code
$(document).ready(function() {
$('.content_load').load('staff_view.php');
$('ul#nav li a').click(function() {
var page = $(this).attr('href');
$('.content_load').load(page);
$('form.ajax').on('submit', function() {
var that = $(this);
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
});
clearAll();
return false;
});
});
function clearAll(){
$("form :input").each(function(){
$(this).val("");
});
}
Because it's a form, and because you wish to submit via AJAX instead of the usual "redirect-to-page" method that forms automatically use, you must suppress the default action.
Change this:
$('form.ajax').on('submit', function(){
var that = $(this);
etc.
to this:
$('form.ajax').on('submit', function(e){ // <=== note the (e)
e.preventDefault(); // <=== e used again here
var that = $(this);
etc.
You need to prevent default action when you click anchor tag, and that is redirects you to the link in your href attribute
$('ul#nav li a').click(function(e){
e.preventDefault();
var page = $(this).attr('href');
$('.content_load').load(page);
// code...
This is what cause your redirection
I could be wrong, but it looks like you might have a race condition to load the page and attach the submit listener. The page might load after the $('form.ajax') bit is executed.
$('.content_load').load(page); // Race condition?
$('form.ajax').on('submit', function() {
One fix would be to move the following code into a completion callback:
$('.content_load').load(page, function() {
$('form.ajax').on('submit', function(e) {
e.preventDefault();
// ...
});
Also, add the e.preventDefault(); to prevent the form from actually submitting.

How to request page content by clicking a div with jQuery mobile?

I am trying to fetch data form a callback page (php) and load it into a html div with jQuery mobile. This should happen if a user clicks on another div.
What I actually got is
$.('#home-button').bind('vclick', function( e ) {
$.get('homeCallback.php',function(data){
$('#displayContent').append(data).trigger('create');
},'html');
});
Where #home-button is the div that should trigger the event and #displayContent the div where the content should be put in.
The request should be able to pass some parameters, too. Like homeCallback.php?param=1 but it could also use the post method.
The callback does not have to be html only, it could also be possible that the callback php script provides JSON data or anything.
I am not a JS crack so I have problems solving this issue. Thanks for your help!
Edit:
So I found a solution on my own:
$(document).ready(function() {
$.ajaxSetup ({
cache: false
});
var ajaxLoader = '<img src="images/ajax-loader.gif" alt="loading.." />';
var loadUrl = "homeCallback.php";
$('#home-button1').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option1',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
$('#home-button2').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option2',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
});
And this is what homeCallback.php simply does..
<?php
if( isset($_GET["option1"] ))
echo "option1";
if( isset($_GET["option2"] ))
echo "option2";
So far.
$.('#home-button').bind('click', function() {
$.ajax({
url: "homeCallback.php",
type: "POST",
data: ({param: 1, param2: 2}),
success: function(html){
$("#displayContent").html(html);
}
});
});

ajax in form, then jquery to display filled form fields

I have a form that requires a physical address. Once the user enters the full address, I have a button that says "Verify address". I want to be able to click that button, trigger an ajax call that will call a file in the server which will get the longitude and latitude of that address, then return to the form with those coordinates, and display a div with them. Dont worry about figuring out the coordinates. Im just trying to figure out the whole ajax call and jquery display upon response from the server. Thanks
So, I did this to have things working:
$(document).ready(function() {
//if verify button is clicked
$('#verify').click(function () {
var address = $('input[name=address]');
var city = $('input[name=city]');
var state = $('input[name=state]');
var zip = $('input[name=zip]');
var country = $('select[name=country]');
//organize the data for the call
var data = 'address=' + address.val() + '&city=' + city.val() + '&state=' + state.val() + '&zip=' + zip.val() + '&country=' + country.val();
//start the ajax
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//alert (html);
if (html!='error') {
//show the pin long and lat form
$('.form2').fadeIn('slow');
} else alert('Error: Your location cannot be found');
}
});
//cancel the submit button default behaviours
return false;
});
});
process.php returns the longitude and latitude back in a variable as: "longitude,latitude". How do I access that data back in the front end so I can populate the form fields with it? Thanks a lot for the great responses.
I hope this is helpful. This would be a generic AJAX call to a php page:
$.ajax({
type: "POST",
url: "scripts/process.php",
data: "type=query&parameter=" + parameter,
success: function (data) { //Called when the information returns
if(data == "success"){
//Success
} else {
//Fail
}
},
error: function () {
//Complete failure
}
});
The jQuery function you need is jQuery.get().
You can find other details here: http://api.jquery.com/category/ajax/
Sorry for the scarce details but you haven't provided source code.

something wrong with this jquery?

i have these two jquery scripts on my html page, one of them loads more results(like pagination), and the other one replies to users messages, just like twitter!
the replies works(inserts username into textbox), when the page is on default, but when i load more results, the loaded results wnt insert the username into the textbox!! these are the two scripts,
the replies jquery:
function insertParamIntoField(anchor, param, field) {
var query = anchor.search.substring(1, anchor.search.length).split('&');
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2);
if (kv[0] == param) {
field.val(kv[1]);
return;
}
}
}
$(function () {
$("a.reply").click(function (e) {
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this,"reply_name",$("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").focus()
$("#inputField").val($("#inputField").val() + ' ');
e.preventDefault();
return false; // prevent default action
});
});
the loadmore jquery script:
$(function() {
//More Button
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ul.statuses").append(html);
$("#more" + ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
EDIT: when i load more posts, and i click reply the page is refershed, so that ends up with loaded data being hidden again!!
If the reply button is being replaced by the ajax, this might be a workaround.
$(function () {
$("a.reply").live(click, function (e) {
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this,"reply_name",$("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").val($("#inputField").val() + ' ').focus();
e.preventDefault();
});
});
Also... If the status_id, reply_name , replyto info is contained within your reply button, make sure these data exists for each reply button after the more button is clicked.

Categories