ajax request page redirecting - php

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.

Related

how to load another page when clicking a button in another page and pass values to the loaded page in jquery?

I have a button in a page. On clicking the button it should go to another page and that page should be viewed. Also I want to pass some values to the second page when the button is clicked and display the passed values in the second page.
I have written a code in ajax but it is not working.
<script>
$(document).ready(function(){
$(".chk").click(function(){
if($('input.checkin:checked').val()){
var apikey = '60CF3C2oh7D+Q+aHDoHt88aEdfdflIjFZdlmsgApfpvg8GXu+W8qr7bKM33cM3';
var password = 'fHdfvxk';
var endpoint = 1;
var method = 'ProcessPayment';
var dataString = 'APIKey='+apikey+'&APIPassword='+password+'&ddlSandbox='+endpoint+'&ddlMethod='+endpoint;
$.ajax({
type: "POST",
url: "responsive.php",
data: dataString,
cache: false,
success: function(result){
}
});
//window.location.href= 'http://localhost/m/responsive.php';
}
else{
alert("Please Accept the terms and conditions and continue further!!!!");
}
}); });
</script>
I have written a code in ajx when button click, but it will only pass the values to that page. But the page cannot be viewd. Can anyone suggest a solution for this ?
Instead of using ajax you can redirect to the page.
<script>
$(document).ready(function(){
$(".chk").click(function(){
if($('input.checkin:checked').val()){
var apikey = '60CF3C2oh7D+Q+aHDoHt88aEdfdflIjFZdlmsgApfpvg8GXu+W8qr7bKM33cM3';
var password = 'fHdfvxk';
var endpoint = 1;
var method = 'ProcessPayment';
//var dataString = 'APIKey='+apikey+'&APIPassword='+password+'&ddlSandbox='+endpoint+'&ddlMethod='+endpoint;
// use location href instead of ajax
window.location.href = "responsive.php?APIKey='+apikey+'&APIPassword='+password+'&ddlSandbox='+endpoint+'&ddlMethod='+endpoint;
}
else{
alert("Please Accept the terms and conditions and continue further!!!!");
}
});
});
</script>

HTML form submit not working after being loaded with ajax

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.

What is the best way to prevent page reload using Jquery(ajax)?

Summary: I have a:
1) main page (Main.php)
2) simple .js script file (dashboard.js)
3) one other simple .php file (form1.php)
4) process.php, a file that processes the information sent by .js file (process.php)
Just like tumblr, I am trying to recreate the same "nav" experience - clicking the several options, replacing the main panel with the new code and when filling up the some form, send that info to BD and present the result in the Main.php
Everything is going well but the last step. After clicking the nav button (main.php), bringing the new form through javascript (dashboard.js + form1.php), filling up that form, I click the button and instead of not reloading the page (jquery->ajax), it sends me to the process.php file and presents me the result.
I have tried not to reload with "return false" and "event.preventdefault()" and still the same result.
JS Code
$('form.ajax').on('submit', function() {
event.preventDefault();
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(html){
event.preventDefault();
$("ol#list-feed").append(html);
document.getElementById('set-width1').value='';
document.getElementById('tags').value='';
}
});
event.preventDefault();
return false;
});
You haven't defined event:
$('form.ajax').on('submit', function(event) {
event.preventDefault();
//...
});
You need to change the first line to:
$('form.ajax').on('submit', function(event) {
otherwise the event variable inside the function is undefined.
try like this
$('form.ajax').on('submit', function(event) {
event.preventDefault();
//do other works here
}
or remove event.preventDefault() from everywhere and before the end of this function just use return false.
This should work
$('form.ajax').on('submit', function(event) {

Ajax - multiple validation

I have set up some ajax code to validate multiple fields inside a form using php. The code works like a charm, but I wanna minimize the javascript used.
As you can see at the code below, Im getting the getElements('input') ... that validates all input fields and then getElements('textarea') that validates... ya u know! ;o) Textarea is the last line in the code below and the javascript after that is the same as inpt
I'm validating the input, textarea, selection list, checkbox, etc. in my controller using php, but the code after getting the elements is the EXACT SAME.
So I was thinking that I might could make a switch case or if else with javascript to loop the elements and only write the duplicated javascript once....
Could that be done?
window.addEvent('domready', function(){
$('container').getElements('input').addEvent('keyup', function(e){
//stop the input-tag event
e = new Event(e).stop();
//identify which item was activated
var querystring = this.title;
var value = this.value;
var myXHR = new XHR({
method: 'get',
onSuccess: function(e){
var myString = myXHR.response.text;
var myStringArray = myString.split("###RAWR###");
$(myStringArray[1]).innerHTML = '<em class="checking"> </em>';
setTimeout( ajax , 3500 );
function ajax(){
$(myStringArray[1]).innerHTML = '<em class="'+myStringArray[2]+'">'+myStringArray[0]+'</em>';
}
}
});
myXHR.send('index2.php?option=com_component&task=validate&value='+value, querystring);
});
$('container').getElements('textarea').addEvent('keyup', function(e){
You can put the tagnames in an array loop it and call a function with your validation.
window.addEvent('domready', function(){
var tagNames = ["input", "textarea", "select"];
for (var i = 0; i < tagNames.length; i++)
{
validate(tagNames[i]);
}
});
function validate(tag)
{
$('container').getElements(tag).addEvent('keyup', function(e){
//stop the input-tag event
e = new Event(e).stop();
//identify which item was activated
var querystring = this.title;
var value = this.value;
var myXHR = new XHR({
method: 'get',
onSuccess: function(e){
var myString = myXHR.response.text;
var myStringArray = myString.split("###RAWR###");
$(myStringArray[1]).innerHTML = '<em class="checking"> </em>';
setTimeout( ajax , 3500 );
function ajax(){
$(myStringArray[1]).innerHTML = '<em class="'+myStringArray[2]+'">'+myStringArray[0]+'</em>';
}
}
});
myXHR.send('index2.php?option=com_component&task=validate&value='+value, querystring);
});
}

Other jquery functions NOT working after successful ajax function

EDIT
JQUERY-AJAX REQUEST CODE:
<script type="text/javascript">
$(document).ready(function(){
$(".form").submit( function(e) {
e.preventDefault();
var form = $(this);
var div_add_comment = $(form).parent();
var div_comments = $(div_add_comment).parent();
$.ajax({
type: "POST",
data: $(form).serialize(),
url: "includes/comment.php",
success: function(msg){
$(div_comments).html(msg);
}
});
return false;
});
});
</script>
JQUERY SHOW ALL - COLLAPSE COMMENTS CODE
<script type="text/javascript">
$(document).ready(function(){
$('.see_all').click(function(){
var thisItem = $(this);
thisItem.parent().find('#comment2').slideDown('fast');
thisItem.parent().find('.collapse').css('display','inline-block');
thisItem.css('display','none');
return false;
});
$('.collapse').click(function(){
var thisItem = $(this);
thisItem.parent().find('#comment2').slideUp('fast');
thisItem.css('display','none');
thisItem.parent().find('.see_all').css('display','inline-block');
return false;
})
})
</script>
JQUERY REMOVE DEFAULT VALUE TEXT UPON FOCUS - TEXTAREA
<script type="text/javascript">
$(document).ready(function(){
var Input = $('textarea[name=comment]');
var default_value = Input.val();
$(Input).focus(function() {
if($(this).val() == default_value)
{
$(this).val("");
}
}).blur(function(){
if($(this).val().length == 0)
{
$(this).val(default_value);
}
});
})
</script>
Please let me know if you need anything else, I have the damndest of time copying code and formatting it in these posts.
END EDIT
I am having a weird little problem. I have created a jquery-ajax function to transfer data from a comments section of my page. The page has an instance of this form under each user post. So this page will have X amount of posts with X amount of comments for each posts, like a social network. My ajax request sends, recieves and displays the data perfectly BUT I have two other jquery functions called on elements inside that no longer work after the ajax function returns the html. All the other ones not acted upon by the ajax function STILL WORK. I have the checked and rechecked the response html from the ajax function and it is identical to the html of a standard post-comment instance.
Please let me know what you would like to see or if you have questions.
Thanks, your help is always appreciated!
Be sure to bind the jQuery functions in such a way that the element doesn't have to exist.
$('ul').on('click', 'li', function(){ /* do something */ });
This will execute on LIs that have been added after the binding of the function.
In your case you would want to bind to the parent of the comments section and target the elements that have the click behavior.
$('.comments')
.on('click', '.see_all', function(){...})
.on('click', '.collapse', function(){...})
.on('focus', 'textarea[name=comment]', function(){...})
.on('blur', 'textarea[name=comment]', function(){...})
Try removing the $() from form.
You have this:
var form = $(this);
var div_add_comment = $(form).parent();
var div_comments = $(div_add_comment).parent();
It should be this:
var form = $(this),
div_add_comment = form.parent(),
div_comments = $(div_add_comment).parent();
Since you declared var form = $(this); you don't need to wrap form...how you have it now is the equivalent of $((form))
Not sure if this will fix your problem, but jQuery may be getting hung up on this since you are spawning children from $(this).

Categories