Form submitting to old action after changing the action via jQuery - php

This seems that this should be so simple but it's not working. What I'm doing is getting the old action, adding an ID to the end, and setting the form action to that. Here's the code:
var action = $('#update-schedule-form').attr('action');
$('#update-schedule-form').attr('action', action + '/1');
I can see that the form's action gets changed in FireBug and in Chrome's inspector. However, when I click the submit button, it still sends it to the original action. For example, it shows "/controller/action/1" in code but submits to "/controller/action". Any ideas what is going on here?
UPDATE
It turns out that the framework I'm using, Yii, stores the original form action address for it's ajax validation routines. I wasn't seeing the form submit in Firebug, I was seeing the validation trying to validate the form before submission. I have no idea where Yii stores the URL it uses or how to change it (should be using the form action, but apparently it's not), so I just modified my controller and made the ID parameter optional. Now the validation runs happily and the form submits correctly.

Maybe you should try to use prop instead of attr.
var action = $('#update-schedule-form').prop('action');
$('#update-schedule-form').prop('action', action + '/1');
Check this answer for .prop() vs .attr()

Are you submitting the form via jQuery or with submit html button? Try a different way of submitting it.
Also, try updating the action this way.
var action = jQuery('#update-schedule-form').get(0).getAttribute("action");
jQuery('#update-schedule-form').get(0).setAttribute('action', action + '/1');
Edit: it may be where your code is positioned, but if there's no error, it is hard to tell, it's probably not the problem.

Related

Form post action from smarty template

I've the following problem...
My application uses the php, smarty templates and jQuery.
Inside the smarty template there is defined a form with POST method.
The action parameter of the form is defined as follows:
action={if isset($search_place)} {link->somePhpFunction($search_place) {/if}
...because I need to change the action depending on the POSTED parameter.
The input (text) with the "search_place" name is defined inside the form.
The submit button is linked to the jQuery function, as I need to perform some actions on the client side (value check, autocomplete, etc.).
When the button is clicked, I need to
The problem is that when I post the form by the jQuery button, the form will not take the
When the button is clicked then the jQuery handler is called where some checks/corrections are performed and then the page with the form is displayed.
The problem is, that before defining the action parametr from the form the search_place variable in not known and the php function is not called at all.
I've also tried to set a cookie in the button handler and to set the form action to the {$smarty.cookies.search_place} value but the problem changed into another one - the form allway performes action of the previous button click so it is necessary to click the button TWO TIMES to get the correct results.
It is also necessary to mention that there is no way to transfer the needed action parameter to the jQuery event handler as the php function selects the correct one from the large table in database. If this is possible, then it would be easy to change the action parameter from the jQuery function...
The only way I know is to use AJAX to get the right parametr and assign the correct action parametr from the button event handler but it is not the right solution for me as many of my site visitors have not the browser javascipt enabled.
The solution could be also to perform (programmaticaly) one more click on the button from the jQuery event handler but I don't know how to do it...
Any help or idea how to solve this issue will be greatly appreciated...
Thank you in advance. JaM
Try the following:
<form onsubmit="return validationFunction()">
and let this function validate the data and return true if correct and false if not.
now for the js. don't call something like
$("#someForm").submit();
instead use:
if(validationFunction()){
$("#someForm").submit();
}
Update
finally if your validationFunction will do some server-side work
Then instead some variable like
var formSubmitted = false;
then onSubmit return false; and set the formSubmitted to true, and do your ajax call, and when the ajax call is done, check the formSubmitted if it's true then submit the form if not then show some error...

jQuery + Gravity Forms: Perform jQuery on bad validation

I use some jQuery on a current gravity form. However, when I submit the form and it comes back with bad validation, I lose some of the jQuery targets.
I'm curious how I can swap out $(document).ready(function() { with something that will call my jQuery once the fields are reloaded with bad validation.
I've tried $("#gform_submit_button_1").click(function() { however, that's too soon. It needs to happen when the new fields come back from ajax.
There is actually a hook provided for use here: gform_post_render
This jQuery hook is fired every time the form is rendered to allow custom jQuery to be executed. This includes initial form load, going to the next/previous page on multi-page forms, form rendered with validation errors, confirmation message displayed, etc.
jQuery(document).bind('gform_post_render', function(){
// code to trigger on AJAX form render
});
http://www.gravityhelp.com/documentation/gravity-forms/extending-gravity-forms/hooks/javascript/gform_post_render/
For some reason Gravity Forms still hasn't added a jQuery hook for failed form validation. What they recommend doing is checking for the existence of div.validation_error.
jQuery(document).on('gform_post_render', function(e, form_id) {
if ( jQuery('div.validation_error').length > 0 ) {
console.log('Form validation error.');
}
});
You'll notice I'm not specifying a parent when I check for the validation error element: jQuery('div.validation_error'). If you have multiple forms on the page this would cause issues. The form_id parameter that is returned contains the form's ID in the database (e.g. 1, 2, 35, etc.) but I'm not sure if this value matches the forms ID in the HTML, e.g. <form id="gform_1">. If it does match, then it's good practice to specify the parent, so you could do:
if ( jQuery('div.validation_error', '#gform_' + form_id).length > 0 ) {
Maybe somebody else could weigh in and let us know if the form's HTML ID will always match the form's database ID.
Gravity forms does supply a gform_confirmation_loaded hook, but I don't think this will work in your case since it's not loading the confirmation, but the error state form. They don't have a hook for this but I've had success using jquery delegated events. I use the .gform_wrapper as my first selector and then target the fields I want to actually target.
See this documentation for more info:
http://api.jquery.com/on/#direct-and-delegated-events
http://www.gravityhelp.com/documentation/gravity-forms/extending-gravity-forms/hooks/filters/gform_confirmation_loaded/
One solution is: catch the submit event and start a interval that checks your form for changes and then calls your function:
$('#your-form').submit(function(){
html = $('#your-form').html();
iv = setInterval(function(){
If($('#your-form').html != html){
yourfunc();
clearInterval(iv);
}
}, 200);
});
function yourfunc(){
//your stuff
}
This is however not very neat and it will only work if the html is actually changed after the Ajax call.

PHP 'beating' javascript function call?

I've got a bit of a weird problem.
I'm creating a location based web app that is using a javascript function to get a user's GPS coordinates. I have a form with a submit button, and when that submit button is clicked, the function is called (onclick='getCoords()"). The javascript then sets that values of two hidden fields (latitude and longitude) to the GPS coords.
My issue is this: PHP is 'beating' the javascript in the sense that the field values aren't being set in time, so that each value becomes a 0. I've done a bunch of testing, and this is definitely the issue. If I do something like set a seperate button to run the javascript function, the run the form everything works fine.
Any ideas on how to solve this problem?
Gists:
https://gist.github.com/2425419
https://gist.github.com/2425394
https://gist.github.com/2425391
Along the lines of what Volkner said, block submit using a submit handler (call preventDefault), then submit at the end of itsWorking. You can either call .submit() to do the submission, or use AJAX.
I think the crux of your problem is that an <input type="image"> will submit a form just as sure as <input type="submit"> will.
However, to fix this as is, add event as a parameter to both the call and declaration of getUserLocation(event).
Then edit your JavaScript as follows:
function getUserLocation(event) {
event.preventDefault(); // prevents form from submitting
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(itsWorking, notWorking);
}
else {
alert("Dang! Your browser doesn't support finding your location, use the zipcode method below.");
}
};
function itsWorking(position) {
var lat = position.coords.latitude;
var longi = position.coords.longitude;
var finalLat = Math.round(lat*1000000)/1000000
var finalLong = Math.round(longi*1000000)/1000000
$("#longi").val(finalLong);
$("#lati").val(finalLat);
document.getElementById('findoneform').submit(); // submits form since we were successful
};
But like I originally stated, it seems if you used an img tag instead of <input type="image">, that would prevent the form from sending in the first place (and maybe you did this on purpose, because you wanted to have two ways to submit the form?).
This issue happens because the page unloads (submits the form) before the geolocator's done doing its thing, but this way, we stop the form from submitting, and itsWorking() only gets called AFTER the geolocator has done its thing, so we don't submit the form until the end of itsWorking() when we've done everything we wanted to do.

PHP - Add form element before submit - Buy Button

I need to dynamically add form elements to an HTML form as soon as the Submit button is clicked but before the POST data is sent to a server. The new elements must be "read" from a PHP file on my server.
HISTORY:
Currently my HTML form has "hidden" fields that are submitted to another server for processing. I have no control over the other server. My problem is that anyone can edit these hidden fields.
How can I dynamically add form elements to the POST data as soon as the form is submitted?
You can try it this way:
First disable the submit by changing the submit button type from 'submit' to 'button' (or whatever)
Put in onclick on that button to a javascript routine (here i use submit_form()).
Create an empty div within your form. (here i call it with id = 'dynamic')
Using jquery, this is the submit_form().
I think you will need to give it some time for these elements to bind properly before submitting. Maybe a short time delay before $("#myForm").submit();
Here is the code for the submit_form() function:
function submit_form()
{
$("#dynamic").append("<input type='hidden' name='input1' value='whatever'>");
$("#dynamic").append("<input type='hidden' name='input2' value='whatever'>");
$("#myForm").submit();
}
You can post the data to your server and after it post again to the external server with the new elements attached.
Your job is done on server side.
See also:
php server-to-server post?
If you need any control over what is submitted to the other server, you have to do that yourself. Make the form submit to your own server, then validate it, add your data and re-submit it to the other server.
You can use the CURL extension in PHP to post data from your server.

jQuery and IE8: Form action and submit problem

I have some code that isn't doing what I want it to in IE8. When you hit the "preview" submit button, a bit of Javascript jumps in and changes the form's action to franchisepreview.php. This sets a session variable so when you go back to the form you won't loose anything. Hitting "Update" or "Insert" goes straight to a query that inserts a franchise.
In IE8 the Javascript isn't jumping in. It submits the form without ever changing the action.
The bit of jQuery I'm using:
The bind:
jQuery("#preview").bind("click", changeForm);
The function changeForm:
function changeForm(event)
{
alert("Before: "+ jQuery("#franchiseform").attr("action"));
jQuery("#franchiseform").attr("action", "franchisepreview.php");
alert("After: "+ jQuery("#franchiseform").attr("action"));
jQuery("#franchiseform").submit();
}
Maybe try chaining to make sure the attribute is set before the form is submitted:
jQuery("#franchiseform").attr("action", "franchisepreview.php").submit();
Doesn't look like .attr() accepts a callback.

Categories