I want to passivate form action because i submit the form with js. But if there is form action js doesn't work and page redirects action url. I remove form tags and put div tags with #combination id but it didn't work neither
js:
$("#combination").submit(function(){
var url = "www.myurl.com/?view=listen&";
var i = 0;
$("input:checked").each(function(){
url += "tag[" + i + "]" + $(this).val() + "&";
i++;
});
alert(url);
location.href = url;
});
html:
<form id="combination" action="" method="get" name="combination" target="_self">
<?php foreach($top_tags as $top_tag):?>
<input type="checkbox" name="tag[]" value="<?php echo $top_tag['tag_name'];?>" /><?php echo $top_tag['tag_name'];?><br />
<?php endforeach;?>
<input name="" type="submit">
</form>
you have to prevent the default behavior of the form with "preventDefault" and than start your ajax-call or what ever ;).
$("#combination").submit(function(event){
event.preventDefault();
var url = "www.myurl.com/?view=listen&";
var i = 0;
$("input:checked").each(function(){
url += "tag[" + i + "]" + $(this).val() + "&";
i++;
});
alert(url);
location.href = url;
});
The problem you really could not call the handler this way:
http://api.jquery.com/submit/
handler(eventObject)A function to execute each time the event is triggered.
basically what happend, instead of submitting form you did redirection.
Think about chain:
you call submit method for form, using jquery.
while the event triggered for form, but before the form actually submitted you change the location.
this cancels submitting and instead redirect you to whatever
If you really want things doing this way you may do it into the two ways:
redirection on the server side after the form is submitted
as it was said use ajax http://api.jquery.com/jQuery.ajax/ submitting into the handler and make disable default action either way
$("#combination").submit(function(event){
event.preventDefault();
// code here
});
OR
$("#combination").submit(function(event){
// code here
return false;
});
Related
I have a question that's blowing my mind: how do I send a form ID stored in a PHP variable to my AJAX script so the right form gets updated on submit?
My form is a template that loads data from MySQL tables when $_REQUEST['id'] is set. So, my form could contain different data for different rows.
So, if (isset($_REQUEST["eid"]) && $_REQUEST["eid"] > 0) { ... fill the form ... }
The form ID is stored in a PHP variable like this $form_id = $_REQUEST["eid"];
I then want to use the button below to update the form if the user changes anything:
<button type="submit" id="update" class="form-save-button" onclick="update_form();">UPDATE</button>
and the following AJAX sends the data to update.php:
function update_form() {
var dataString = form.serialize() + '&page=update';
$.ajax({
url: 'obt_sp_submit.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: dataString, // serialize form data
cache: 'false',
beforeSend: function() {
alert.fadeOut();
update.html('Updating...'); // change submit button text
},
success: function(response) {
var response_brought = response.indexOf("completed");
if(response_brought != -1)
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn(); // fade in response data
$('#obt_sp')[0].reset.click(); // reset form
update.html('UPDATE'); // reset submit button text
}
else
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn();
update.html('UPDATE'); // reset submit button text
}
},
error: function(e) {
console.log(e)
}
});
}
I'd like to add the form's id to the dataString like this:
var dataString = form.serialize() + '&id=form_id' + '&page=update';
but I have no idea how. Can someone please help?
The most practical way as stated above already is to harness the use of the input type="hidden" inside a form.
An example of such would be:
<form action="#" method="post" id=""myform">
<input type="hidden" name="eid" value="1">
<input type="submit" value="Edit">
</form>
Letting you run something similar to this with your jQuery:
$('#myform').on('submit', function(){
update_form();
return false;
});
Provided that you send what you need to correctly over the AJAX request (get the input from where you need it etc etc blah blah....)
You could alternatively include it in the data string which; I don't quite see why you would do.. but each to their own.
var dataString = form.serialize() + "&eid=SOME_EID_HERE&page=update";
Sounds like a job for a type=hidden form field:
<input type="hidden" name="eid" value="whatever">
You have to write the string dynamically with PHP:
var dataString = form.serialize() + "&id='<?php echo $REQUEST['eid'] ?>'+&page=update";
On the server you can write Php code on the document, and they will be shown as HTML/JS on the client.
Rooms are an array
window.location = "booking_status.php?array="+ JSON.stringify(rooms);
sending from javascript to php page
on php page url show full array value which are store in array in page address bar url
like that
http://localhost/zalawadi/booking_status.php?array=[{%22id%22:10,%22rate%22:100}]
I want to prevent this data which show in url %22id%22:10,%22rate%22:100
I am decoding on php page any other way to send array data from javascript to php page
The only way to send data to another page without showing them in the url is to use POST.
Basically, you can put your data into an invisible form input :
<form method="post" id="form" action="booking_status.php">
<input name="array" id="array" type="hidden" value="" />
</form>
Send
<script type="text/javascript">
function sendForm(){
document.getElementById('array').value = JSON.stringify(rooms);
document.getElementById('form').submit(); //fixed syntax
}
</script>
You can use a hidden form and the post method. Then you would use $_POST instead of $_GET.
<form action="script.php" onsubmit="this.firstChild.value=JSON.stringify(value);">
<input type="hidden" value="" />
Link text
</form>
You can use a POST request, however this would require generating and submitting a form:
// assuming `rooms` already defined
var frm = document.createElement('form'), inp = document.createElement('input');
frm.action = "booking_status.php";
frm.method = "post";
inp.type = "hidden";
inp.name = "array";
inp.value = JSON.stringify(rooms);
frm.appendChild(inp);
document.body.appendChild(frm);
frm.submit();
Why not just POST the data instead then?
For example, with jQuery:
$.ajax({
type: "POST",
url: "booking_status.php",
data: JSON.stringify(rooms),
success: // add success function here!
});
The advantage is you're not passing some horrific URL. As an added bonus, this example is also asynchronous, so the user doesn't see any refresh in their browser.
Non-Framework Version
If you don't wish to use jQuery, you can do this with pure Javascript, using the XMLHttpRequest object, like so:
var url = "get_data.php";
var param = JSON.stringify(rooms);
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
// Request has gone well. Add something here.
}
}
http.send(param);
due to some circunstances of my code, i'm using the following button of a form to call a jquery function:
<form id="formElem" name="formElem" enctype="multipart/form-data" action="" method="post">
....
<button name='enviar_candidatura' id='enviar_candidatura' value='enviar_candidatura' onclick='return false;' type='submit'>Enviar Candidatura</button>
...
The jquery function that is called:
$('#enviar_candidatura').bind('click',function(){
var form = $('#formElem');
var conta_Duplicates;
conta_Duplicates=dadosImportantes();
//alert("Deu");
var preenchimentoForm=true;
//alert("Contasssss"+conta1);
//var eventos=$countEventos;
var eventos=conta_Duplicates[2];
//alert("Wiggins"+eventos);
//var empregos=$countEmpregos;
var empregos=conta_Duplicates[1];
//var cursos=$countCursos;
var cursos=conta_Duplicates[0];
//alert($countEmpregos);
/*if($('#formElem').data('errors')){
preenchimentoForm=false;
dadosFormularios(form, preenchimentoForm, cursos, empregos, eventos);
return false;
}
else{*/
dadosFormularios(form, preenchimentoForm, cursos, empregos, eventos);
//}
});
Now what i need is to receive in this function the formElem so that i can define here the action="" of the form and call it using form.action="index.php....".
As you can see in the code above, i tried using
var form = $('#formElem');
however, that doesn't work, i tried:
form.action = 'index.php?pagina=candidaturasB&'+ qstringA;
form.submit();
but without success :/
try this
form.attr("action", 'index.php?pagina=candidaturasB&'+ qstringA)
form.submit();
i think there are no method .action , so you need to set action as attribute
form is jQuery object, it dosn't have action property. You should use attr method:
form.attr('action', 'index.php?pagina=candidaturasB&'+ qstringA);
Since form is a jQuery object it doesn't have the property action. Try this:
form.attr('action', 'url');
I want to perform an onclick and onsubmit at the same time, is this possible? Or if this is bad practice how can I merge the two codes to perform both events?
I have this piece of code checking a mandatory field on the form tag:
onsubmit="return formCheck(this);"
I then have this piece of code on the submit button for the same form:
onClick="jQuery.facebox({ ajax: (\'wishlist.php?emailme=true&name=\' + this.form.name.value + \'&country=\' + this.form.country.value + \'&email=\' + this.form.email.value + \'&department=\' + this.form.department.value) }); return false;"
The problem I have is that on clicking the submit button it completely ignores the onsubmit code. How can I merge them together?
UPDATE I want it to check the mandatory fields first then send the form if all is ok.
UPDATE: I've pasted the whole code here, I'm really struggling as this was done by a previous developer. If someone could literally put the solutions into the code that would be great. I'll up the reward.
Put your onClick code in the same function as the onSumbit code.
UPDATE
At the end of your onClick code you return false;, this stops the normal propagation of events and stops the onSubmit event from firing. So if you want the submit button to submit the form, remove return false; from it's onClick handler.
When you click a submit button you will fire a click event on the button and a submit event on the form in which the button is nested (unless you stop the propagation of events with something like return false;).
So you really only need a submit event handler that does the job of both of your current handlers.
Also since it appears that you have jQuery Core included in your page you can attach event handlers like this:
$(function () {
$('#form-id').on('submit', function () {
var $this = $(this);//$this refers to the form that is being submitted
jQuery.facebox({
ajax : 'wishlist.php?emailme=true&name=' + $this.find('#name').val() + '&country=' + $this.find('#country').val() + '&email=' + $this.find('#email').val() + '&department=' + $this.find('#department').val()
});
//now we run your normal onSubmit code and return it's return value of this event handler
return formCheck(this);
});
});
If you are sending the whole form to the jQuery.facebox function then you can use jQuery's .serialize() function to create the necessary query-string:
$(function () {
$('#form-id').on('submit', function () {
jQuery.facebox({
ajax : 'wishlist.php?' + $(this).serialize()
});
return formCheck(this);
});
});
Here is a demo: http://jsfiddle.net/vAFfj/
Docs for .serialize(): http://api.jquery.com/serialize
Note that .on() is new in jQuery 1.7 and in this case is the same as .bind() of older versions.
UPDATE
If you want to check the return value from the formCheck() function before running the facebox plugin then you can do this:
$(function () {
$('#form-id').on('submit', function () {
//check if the form data is valid
if (formCheck(this) === true) {
//if the form data is valid then run the facebox plugin
jQuery.facebox({
ajax : 'wishlist.php?' + $(this).serialize()
});
//also return true to stop running this function
return true;
}
//if the form data is not valid then return false to stop the submission of the form
return false;
});
});
Make the onclick function submit the form.
Not sure if you have a specific requirement for using both onSubmit() and onclick(), but this might help.
Here's the HTML:
<form id="my_form">
Name: <input type="text" id="name" size="20" />
<br />Country: <input type="text" id="country" size="20" />
<br />Email: <input type="text" id="email" size="20" />
<br />Department: <input type="text" id="dept" size="20" />
<br /><input type="submit" id="submit" value="Login" />
</form>
And here's the JS:
$(document).ready(function() {
$('#my_form').submit(function() {
var name = $('#name').val();
var country = $('#country').val();
var email = $('#email').val();
var dept = $('#dept').val();
/* Validate everything */
if (name != '' && country != '' && email != '' && dept != '') {
/* Validation succeeded. Do whatever. */
jQuery.facebox({
ajax : 'wishlist.php?emailme=true&name=' + name + '&country=' + country + '&email=' + email + '&department=' + dept
});
}
else {
alert('Validation failed.');
}
return false;
});
});
Now, you can do two things:
1) If you're using AJAX to do your form stuff, you might want to keep the return false; in the second-last line, as this will prevent your form from submitting.
2) If you want to post your form anyway, just remove return false;. You can also post your form using $('#my_form').submit() whenever you want.
Here's the fiddle:
http://jsfiddle.net/vAFfj/1/
Hope this helps.
I suggest you to write a separate function which do the same task as onClick event.
First check if all required fields have been entered on onSubmit event, if no return false else if all required fields have been entered call the function which perform the same job as function in 'onClick' event.
First of all, you don't need both actions. In your scenario you only need to use the onSubmit attribute on the form tag.
Second, it would be a lot better (for too many reasons) if the actions on the attributes would contain references to functions, and not inline code.
That said, I would change the code as follows :
//some js file included in the page's header
function formSubmitActions(element) {
if (formCheck(element)) {
jQuery.facebox({
ajax : 'wishlist.php?emailme=true&name=' + element.name.value
+ '&country=' + element.country.value
+ '&email=' + element.email.value
+ '&department=' + element.dept.value
});
return true;
}
return false;
}
//the form
<form [...] onsubmit="return formSubmitActions(this)">
[...]
Hope it helps!
there are 2 issues in your code,
1 - form can be submitted by pressing "enter" on any input field. so the onclick event wouldn't be triggered.
2 - if the user clicks the button (assuming you've added a few hacks and both the onclick and onsubmit events are triggered), but the formcheck returns false, the form wouldn't be submitted, but the click event will be successful (you'll have a request sent to wishlist.php)
my suggestion would be as below,
onsubmit = "readyToSubmit(this); return false"
function readyToSubmit(a){
if(formCheck(a)){
jQuery.ajax({
url : ...,
success : function(data){a.submit()}
})
}
}
You submit form in the onclick event now (jQuery.facebox({ ajax:) so simple move this to on submit event handler (in the bottom of formCheck function after all validations passed)
.click(function(e)
{
e.preventDefault();
// click code
});
.submit(function(e)
{
// submit code
});
and ajax async param to FALSE
Why not just make put them together? the submit will occur on submit and on click so you can do
onsubmit="return formCheck(this);jQuery.facebox({ ajax: (\'wishlist.php?emailme=true&name=\' + this.form.name.value + \'&country=\' + this.form.country.value + \'&email=\' + this.form.email.value + \'&department=\' + this.form.department.value) }); return false;"
You can do one thing, just write code for submitting your form, like $('#form_id').submit();, instead of return false;. So it will submit the form, after completion of .onclick() code functionality.
Try combining the two like this:
onClick="if (formCheck(this)) { jQuery.facebox({ ajax: (\'wishlist.php?emailme=true&name=\' + this.form.name.value + \'&country=\' + this.form.country.value + \'&email=\' + this.form.email.value + \'&department=\' + this.form.department.value) });} return false;"
i made this form:
<form id="form" name="msgform" method="" action="">
<input type="text" size="40" id="msg" name="message"/>
<input type="submit" id="button" name="clicker" value="click" />
</form>
and this jquery script:
$(document).ready(function(){
$("#button").click(function(){
$("#form).submit(function(){
var submision= $("#form).val();
$.post("txt/process.php", submision, function(data){
alert(data);
});
});
});
});
and this is the process.php file:
<?php
echo $_POST['message'] . "";
?>
now when i click the button the form is submited, but it sends it using the GET method because i can see it in the adress bar, but it never gets sent to the php file, and i checked to see if the names are correct and if i specify the POST method it still doesnt go to the php file.
is the server or browser ignoring the code? or am i doing the whole thing wrong?
thanks
Please find the following code, it works and please go through with the documentation, it will tell you that what the mistake was being done.
$(document).ready(function(){
$("#button").click(function(){
$("#form").submit(function(){
/* var submision= $("#form).val();
THIS DOESN'T WORK TO GET ALL OF THE ELEMENTS IN
FORMAT TO PASS TO $.post EVENT,
We can do this as I did in following example
*/
$.post("txt/process.php", { msg: $("#msg").val() }, function(data){
alert(data);
});
/* Also you didn't put return false statement just at the end
of submit event which stops propagating this event further.
so it doesn't get submitted as usually it can be without ajax,
So this stops sending the form elements in url. This was because
by default if you define nothing in method property for form
then it consider it as GET method.
*/
return false;
});
});
});
Let me know please you are facing any issue.
You don't need to register the submit event for the form inside the click handler of the button. As it is a submit button it will automatically try to submit the form for which you register the corresponding handler:
$(function() {
$('#form').submit(function() {
// Get all the values from the inputs
var formValues = $(this).serialize();
$.post('txt/process.php', formValues, function(data) {
alert(data);
});
// Cancel the default submit
return false;
});
});
$("#form).submit(function(){
see if this selector is missing a "
$("#form").submit(function(){