I have two forms on a page (one is being grabbed by AJAX). I need them both to be posted, so I serialize the second one and send it in a post using jQuery before submitting the first one. However, only the first form appears to be getting posted. The odd thing is though, if I put an alert after the serialized post it works as expected. What exactly is my problem here?
$("#submit").livequery('click', function() {
var form = $("#second_form");
var action = form.attr("action");
var serialized_form = form.serialize();
$.post(action, serialized_form);
//alert('test');
$("#first_form").submit();
return false;
});
Is there any better way to post two forms and then redirect to a new page on a button press? I tried posting both of them using the method above and then using window.location to change pages but I had a similar problem.
Much thanks!
You might try submitting "first_form" in a callback from the post of "second_form". I believe that the submit of "first_form" is unloading the page which causes the second post to be aborted. Doing the post of "first_form" in the callback from "second_form" will ensure that the initial post is complete before the second post begins.
$("#submit").livequery('click', function() {
var form = $("#second_form");
var action = form.attr("action");
var serialized_form = form.serialize();
$.post(action, serialized_form, submit_first);
});
function submit_first(val) {
$("#first_form").submit();
}
Related
I have an HTML form that is trigged with AJAX to submit using a Rails backend. However, after submitting the first time, the form stops submitting. From reading other posts, I realize part of the problem is that the issue is related to including $(document) and not the form submit handler in the JQUERY call, but changing it to something like $('.new_todo form').submit will return the page as a JSON object instead of just the instantiated object {} response that I get with using $(document) in the Jquery.
I'm essentially trying to create an object and then to keep appending it to the index page, which works on the first submit, but as noted not on subsequent ones.
I'd really appreciate any insight because I've been staring at this for hours and while tons of answers address similar challenges (unbinding etc), nothing I found successfully addresses this use case.
The current AJAX call is:
$(document).on('submit', '.new_todo', (e) => {
e.preventDefault()
$.ajax({
type: "POST",
url: "/todos",
data: {
'authenticity_token': $("input[name='authenticity_token']").val(),
'todo': {
'name': $("#todo_name").val()
}
},
success: function(response) {
$("#todo_name").val("")
$("#todo_location").html("")
$("#todo_date").html("")
let newTodo = new Todo(response)
let todoHtml = newTodo.formatIndex()
$('.todo-list').append(todoHtml)
}
})
})
The controller action for my create is:
def create
#todo = Todo.new(todo_params)
#todo.save
render json: #todo
end
Thank you!!
Elaborating on an example from the very good post by Felix Kling I wrote some jQuery code to authenticate a user. If the authentication is successful the window.location object should be assigned/replaced to a new URL.
The redirection occasionally fails, even though the user is authenticated correctly: based on the values of sessionStorage('Auth') the looks of the menus for an authenticated user are modified by some other JS code, so I know when the credentials were entered correctly.
Here is my code.
$(document).ready(function() {
$('#submit').click(function() {
var webServiceHref = window.location.href;
var webServicePath = webServiceHref.slice(0,webServiceHref.lastIndexOf("/"));
var serviceUrl = webServicePath + "/login.php";
$.post(serviceUrl,
{
Email: $("#Email").val(),
Password: $("#Password").val()
}).done(function(data, status) {
var json = JSON.parse(data);
if (json.valid == true){
sessionStorage.setItem('Auth', true);
sessionStorage.setItem('FirstName', json.FirstName);
sessionStorage.setItem('Email', json.Email);
$("#messageLine").val("Authentication succeded");
$(location).attr('href', webServicePath + "/welcome.html");
// window.location.href = webServicePath + "/welcome.html";
} else {
sessionStorage.clear();
$("#messageLine").val("Incorrect Username or Password");
}
});
}); // click
}); // ready
This behavior does not depend from the way the redirection is called:
I left in my code, commented out, some of the JS and jQuery
combinations of methods (window.location.assign, window.location.replace etc.) suggested in numerous posts on SO.
I have even tried .reload() without success.
In Chrome inspector I can even see the callback statements being executed, the assignment of the new URL being made, but when the function returns the window object sometimes does not change, and sometimes ... it does.
Perhaps the assignment of the URL is queued after other event which causes the original login.html page to be reloaded?
What am I missing? Am I using the deferred object incorrectly?
Thank you in advance for your help.
If your "#submit" element is actually submitting a form (e.g. it is an input of type "submit" within a form), that could cancel the page redirection. E.g. when no action is specified on the form, it just reloads the same page, preventing your modification of window.location.href from having any effect.
See also that post: javascript redirect not working anyway
You have 3 easy possible solutions:
Turn your element/button into a normal one (not a submit).
Prevent the element/button from submitting the form (function (event) { event.preventDefault(); /* rest of your code */}).
Attach your main callback on the form submit event. The user is then able to trigger the action by hitting "Enter", not just by clicking on the submit button.
I have a use case of sending form submission data to different server, before submitting the form to its action target.
So I need to delay form submission until I receive response given from AJAX request.
My limitation is that I can't use jQuery functions as I am developing my own library set for the product, which must be lite enough.
Now, I could have done something like unbind("submit") event on the form using jQuery, which could be called as callback in the AJAX function. But again, I've limited options.
My current form tracking code goes as:
form.onsubmit = function() {
event.preventDefault();
var url = "/lead/track/trackId/" + trackId;
var data = {};
for (var prop in fields) {
data[prop] = document.getElementsByName(prop)[0].value;
}
data['planId'] = planId;
data['visitorId'] = visitor_id;
var http_request = new XMLHttpRequest();
http_request.onreadystatechange = function(){
if (http_request.readyState == 4 )
{
setTimeout(function() {document.forms[0].submit();}, 0);
}
}
event.preventDefault() completely removes the submit action. If I remove this line, form goes to submission without waiting for AJAX response.
document.forms[0].submit() also doesn't helps. Its not receiving a form object, and displays "object is not a function". It could because this code is loaded asynchronously from a remote file.
Have already seen multiple jQuery alternatives. So, I need a specifically need a native Javascript based solution.
Thanks
I am using jQuery (latest) and have a entirely ajax through post login form. The form is monitored by this code:
$("form").live("submit", function(event) {
event.preventDefault();
var input = {};
input.url = $(this).attr('action');
input.data = $(this).serializeArray();
var output = Site.getResponse(input);
if(output.success) {
params = {};
params.title = 'Dashboard';
params.url = '/user/dashboard';
Page.instance().load(params);
}
});
So, essentially the browser should still recognize the post because it happens from the form's submit, I just use jQuery to stop that submit so I can process it. Is there a way to "trick" modern browsers into saving the password for my site without iframes, please.
IMHO the best way to handle login is to add this line to the end of the login script
header("Location: " . $_SERVER['HTTP_REFERER']);
or some constant url, depending on what you want. This way the page doesn't change and the form submits, therefore the browser remember's the password.
I know that a submit button in HTML can submit a form which opens the target page, but how do I cause a jQuery ajax call to POST information to a new page and also display the new page. I am submitting information that is gathered by clicking elements (which toggle a new class called "select") and then identifiers from these items with the new class are added to a string and POSTed to the new page. This new page will use this data to provide a summary of the selections from the previous page. I currently can get it to POST the data to a new PHP page but it seems to be the ajax function simply remains on the current page (which is great for some things, just not this), not redirecting to the new page. how might I go about doing this?
here's the script section:
//onload function
$(function() {
//toggles items to mark them for purchase
//add event handler for selecting items
$(".line").click(function() {
//get the lines item number
var item = $(this).toggleClass("select").attr("name");
});
$('#process').click(function() {
var items = [];
//place selected numbers in a string
$('.line.select').each(function(index){
items.push($(this).attr('name'));
});
$.ajax({
type: 'POST',
url: 'additem.php',
data: 'items='+items,
success: function(){
$('#menu').hide(function(){
$('#success').fadeIn();
});
}
});
});
return false;
});
any pointers would be great!! thanks
edit:
thanks for the help, I've changed my script to :
//onload function
$(function() {
//toggles items to mark them for purchase
//add event handler for selecting items
$(".line").click(function() {
//get the lines item number
var item = $(this).toggleClass("select").attr("name");
});
$('#process').click(function() {
var items = [];
//place selected numbers in a string
$('.line.select').each(function(index){
items.push($(this).attr('name'));
});
$('#items').attr('value',items);
$('#form').submit()
});
return false;
});
First of all I discourage using ajax here as you are not using it for the purpose for which it is intended to, and you are forcing it to do a reload.
You can do something like this in the success of ajax
success: function(){
window.location = "the new url you wanted to load";
}
Edit:
Why not do a normal post with form action attribute set to the page you want to post to and you can access all the variables of the form in that posted page, or alternatively you can concatenate or store in array all your values and store this array in a hidden variable and access this variable in the posted script.
Ajax posts by definition won't to a page load. But you can do whatever you want in your success handler. So just change the document location there:
success: function(){
$('#menu').hide(function(){
$('#success').fadeIn();
});
window.location = 'http://www.example.com/elsewhere';
}
Oftentimes a POST will return a HTTP 301 or 302 redirect. In that case, you can get the returned header information from the XHR object, which is passed into the callback functions.
complete: function( xhr ) {
// assume we got a redirect; the new URL will be in the Location header
window.location = xhr.getResponseHeader( 'Location' );
}