Just wanted to ask, how will i submit my form through ajax using javascript.
Here's my code:
<script>
function show_edit(bugid,device)
{
document.getElementById('updateform').style.visibility='visible';
document.getElementById('U_bugid').value=bugid;
document.getElementById('U_device').value=device;
}
function hide()
{
document.getElementById('updateform').style.visibility='hidden';
}
</script>
Here's my hidden form
<div id"update_form" >
<form onsubmit="ajax_submit();">
<fieldset>
<label for="maskset">MASKSET</label><input type='text' name='bugid' id='U_bugid' readonly >
<label for="device">DEVICE</label><input type='text' name='device' id='U_device' readonly>
<label for="reason">Comments</label><textarea rows=10 cols=40 name='reason'></textarea>
<input id="S_update" class='S_update' value="Update Data" type="submit" >
</form>
</fieldset>
</div>
Can i put it this way below, when i click submit it will immediately submit through ajax code together with my new comment(from textarea):
function show_edit(bugid,device)
{
var maskset;
document.getElementById('updateform').style.visibility='visible';
document.getElementById('U_bugid').value=bugid;
document.getElementById('U_device').value=device;
function ajax_submit()
{ //code in submitting ajax i already know; }
}
Will this work?
It seems that what you want to do is to stop the submition of your code you need to add onsubmit="return ajax_submit()" to your HTML and make sure the function return false.
function ajax_submit()
{
return false;
}
By the looks of your code you would greatly benefit from getting with jQuery in order to select DOM elements as it will simplify your life greatly.
On that note it would make your life a hell of a lot easier using jQuery Ajax. Specially if you read up on jQuery AJAX functions .
$.post("test.php", { bugid: $('#U_bugid').val(), device: $('#U_device').val() } );
Related
After researching this for too many hours I finally decided to post the question myself, as what is working for others, doesn't seem to work for me. Please keep in mind that I am fairly new to ajax and jquery, but as I am on a deadline with my current project I wont have time to go through it all.
I have the following html form:
<div class="form">
<form id="savePlacemarkForm" method="post" action="createPlacemark.php">
<div>
<input type="text" id="placemarkName" name="placemarkName" placeholder="Name:"/>
</div>
<div>
<input type="text" id="placemarkAddress" name="placemarkAddress" placeholder="Adress:"/>
</div>
<div>
<input type="text" id="placemarkTag" name="placemarkTag" placeholder="Tags:"/>
</div>
<div>
<textarea id="placemarkDescription" name="placemarkDescription" placeholder="Description" rows="1" cols="1"></textarea>
</div>
<div>
<input id="latitude" type="text" name="latitude"/>
</div>
<div>
<input id="longtitude" type="text" name="longtitude"/>
</div>
<button class="md-close" id="savePlacemark" onclick="createPlacemark();"/>Save</button>
</form>
<button class="md-close">Cancel</button>
<script src="my_script.js" type="text/javascript"></script>
</div>
As you see I have the action set to createPlacemark.php which takes input from these fields and saves it to my DB, which works fine!! However since this should work without redirecting or resubmitting the page, meaning ajax! I include my_script.js which looks like this:
$("#savePlacemark").click( function() {
$.post( $("#savePlacemarkForm").attr("action"),
$("#savePlacemarkForm :input").serializeArray();
});
clearInput();
});
$("#savePlacemarkForm").submit( function() {
return false;
});
function clearInput() {
$("#savePlacemarkForm :input").each( function() {
$(this).val('');
});
}
As you see it does the post for me, which works, but for some reason the return false; doesnt seem to work for me, as I am continuously redirected to the before mentioned php file.
Any help would be greatly appreciated! thx!
Try the following. The .submit() function actually triggers a submit for the form. Take this out of the script since you don't need it when you've already posted the values with $.post.
$("#savePlacemark").click( function() {
$.post( $("#savePlacemarkForm").attr("action"),
$("#savePlacemarkForm :input").serializeArray();
});
clearInput();
});
function clearInput() {
$("#savePlacemarkForm :input").each( function() {
$(this).val('');
});
}
try this
<button onclick="return createPlacemark();">Save</button>
it may help you.
I have an HTML form that I submit after changing the action with some javascript. Two different buttons can do the submit.
The interesting thing is that I was trying to debug it and inserted an alert after changing the action and before submitting the form. The form is submitted without the alert ever being displayed. To make sure it's actually performing the javascript, I added an alert before changing the action. That alert displays; the alert after changing the action does not.
<form name='FormSelect' method='post' action='Undefined'>
...
<button onclick="SubmitForm('class')">Submit</button>
...
<button onclick="SubmitForm('student')">Submit</button>
...
</form>
<script type="text/javascript">
function SubmitForm(target){
alert("Action 1: " + document.FormSelect.action);
if (target=="class") {
document.FormSelect.action = "ClassAction.php";
} else {
document.FormSelect.action = "StudentAction.php";
}
alert("Action 2: " + document.FormSelect.action);
// document.FormSelect.submit();
}
</script>
Is that the expected sequence of events?
Any button placed inside form element will cause submit action. To prevent this you can add type="button" to button elements, or make you submit callback return false;
<button type="button" onclick="SubmitForm('class')">Submit</button
see http://jsfiddle.net/yD2Uu/
As the others have already pointed out the form will be submitted anyway if you don't cancle the event. I want to suggest a JavaScript free solution to your problem.
<button formaction="ClassAction.php">Submit</button>
<button formaction="StudentAction.php">Submit</button>
It's not supported in IE < 10 though. But you can still use your function as a fallback then, just a bit more elegant ;)
function SubmitForm(button){
button.form.action = button.formaction;
}
A better solution is to give the buttons a name each and submit to Action.php and let the server get the value of the named button
$student = filter_var($_POST["student"], FILTER_SANITIZE_STRING); // php5 cleaning
when you have
<form method="post" action="Actions.php">
<input type="submit" name="student" value="John Doe" />
<input type="submit" name="student" value="Jane Doe" />
<input type="submit" name="student" value="Whatever Doe" />
</form>
Otherwise if you must
Try this
<form method='post' action='Undefined'>
...
<input type="button" value="Class" onclick="SubmitForm(this)" />
...
<input type="button" value="Student" onclick="SubmitForm(this)"/>
...
</form>
<script type="text/javascript">
var actions = {
"class":"ClassAction.php",
"student":"StudentAction.php"
}
function SubmitForm(button){
button.form.action = actions[button.value];
button.form.submit();
}
</script>
Thanks to Yauhen Vasileusky's example, I started removing code between my 1st & 2nd alerts and found that the problem seems to be the following IF statement:
if (document.FormSelect.FormName.value.substr(0,19)=="ObservationRequest_" || document.FormSelect.FormName.value=="StudentReg2013rx" || document.FormSelect.FormName.value=="Toddler Update Form v3rx")
{
document.FormSelect.action = "GenerateXDP.php";
}
When I remove it, both alerts are displayed. So the answer to my question is that changing the action does not submit the form; it was some other error in my code that made it appear as if that was the case.
I am using javascript validation for my input box from javascript-coder and it works fine on my non-ajax pages but when I use ajax to POST inputs the script runs through without stopping even if validation fails. I tried an example from here but when I tried the suggestion the validation didn't work at all. In my ajax script I can get everything to work with jquery validation by simply putting this in before posting data:
var frm = $(this).closest('form');
if($(frm).valid()){
But I really want to stick with this validation library so I am hoping someone in the community more familiar javascript and maybe even this validation library can help me find an equivalent because I haven't been able to find anything in all the documentation that allows you to test if validation failed or not before moving my ajax script forward.
My form:
<form method="post" name="send_message_frm" id="send_message_frm">
<div style="margin-top:20px;"></div>
<fieldset>
<div class="clear"></div>
<div style="margin-top:20px;"></div>
<label>Product Group Name:</label>
<input name="desc" class="text-input medium3-input required" type="text" id="desc" value="">
<div style="color:red;" id='send_message_frm_desc_errorloc' ></div>
<div style="margin-top:20px;"></div>
</fieldset>
<input name="user" class="text-input medium3-input" type="hidden" id="user" value="<?php echo $myid ; ?>">
<div style="margin-top:20px;"></div>
<input type="submit" id="send-message" name="submit" value="Send" class='button' />
<div style="margin-top:20px;"></div>
</form>
<script type="text/javascript">
var frmvalidator = new Validator("send_message_frm");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("desc","alnum","Only numbers and letters are allowed");
frmvalidator.addValidation("desc","req","Please enter a description");
</script>
My Ajax script:
<script type="text/javascript">
$(document).ready(function(){
//Validate form....what can I put here to test if validation is completed properly????
//onclick handler send message btn
$("#send-message").click(function(){
$(this).closest('form').submit(function(){
return false;
});
var frm = $(this).closest('form');
$("#ajax-loading").show();
var data = $(frm).serialize();
$(frm).find('textarea,select,input').attr('disabled', 'disabled');
$.post(
"productgroup_add.php",
data,
function(data){
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").prepend(data);
}
);
}
);
});
</script>
After reviewing the validation script, I discovered (as suspected) that it attaches the validation method to the form's OnSubmit event handler, which sounds about right...
this.formobj.onsubmit = form_submit_handler;
But... it also attaches itself to the form object:
this.formobj.validatorobj = this;
which has a method that you can call to validate your form:
if (!this.runAddnlValidations())
To run the validations, it looks like you can just do something like:
if(!document.forms[0].validatorobj.runAddnlValidations()) return;
i have a form which has a button that submits the form. I need to do something before submits happen. I tried doing onClick on that button but it happens after the submit.
I can't share the code but, generally, what should I do in jQuery or JS to handle this?
If you have a form as such:
<form id="myform">
...
</form>
You can use the following jQuery code to do something before the form is submitted:
$('#myform').submit(function() {
// DO STUFF...
return true; // return false to cancel form action
});
Update; for newer JQuery versions (to avoid deprecation warnings), try:
$('#myform').on('submit', function() {
// ...
return true;
});
Assuming you have a form like this:
<form id="myForm" action="foo.php" method="post">
<input type="text" value="" />
<input type="submit" value="submit form" />
</form>
You can attach a onsubmit-event with jQuery like this:
$('#myForm').submit(function() {
alert('Handler for .submit() called.');
return false;
});
If you return false the form won't be submitted after the function, if you return true or nothing it will submit as usual.
See the jQuery documentation for more info.
You can use onclick to run some JavaScript or jQuery code before submitting the form like this:
<script type="text/javascript">
beforeSubmit = function(){
if (1 == 1){
//your before submit logic
}
$("#formid").submit();
}
</script>
<input type="button" value="Click" onclick="beforeSubmit();" />
make sure the submit button is not of type "submit", make it a button. Then use the onclick event to trigger some javascript. There you can do whatever you want before you actually post your data.
Form:
<form id="formId" action="/" method="POST" onsubmit="prepareForm()">
<input type="text" value="" />
<input type="submit" value="Submit" />
</form>
Javascript file:
function prepareForm(event) {
event.preventDefault();
// Do something you need
document.getElementById("formId").requestSubmit();
}
Note: If you're supporting Safari (which you probably are) you'll need to pull in a polyfill for requestSubmit()
I am implementing search and when i put nothing in search box this must be remain on same page what will be java script coding for that.
i just create function in java script and return false if string is null on button click it is not working.
As your text makes no sense I must guess what you want to say.
You want your search form to not submit if field is empty and user clicks on search
on form attributes you use onsubmit
<form action="/" method="post" onsubmit="return checkForm(this)">
<input type="text" name="searchText" id="searchText" />
<input type="submit" value="search" />
</form>
now you check if searchText has any text and return true or false
<script type="text/javascript">
function checkForm(form){
if(form.searchText.value == ''){
return false;
}
return true;
}
</script>
I recommand to use JQuery for this kind of functionality, eg:
for the following form
<form action="/myaction" method="post" id="myForm">
<input type="text" value="" name="something1" />
<input type="text" value="" name="something2" />
<input type="submit" />
</form>
and in the same HTML file or in a separate JS file included via html HEADERS :
$(function () {
$("#myForm").submit(function() {
return ($(this).children("input").val()=='') ? false : true;
});
});
or if you don't like ternary expression:
$(function () {
$("#myForm").submit(function() {
doSubmit = true;
if ($(this).children("input").val()=='') {
doSubmit = false;
}
return doSubmit;
});
});
Using it this way, the function assume that all the fields of the form are not empty before posting data.
One other advantage of this method is that it doesn't alter the view code (this is some no intrusive javascript fashion) and can be much more easy to work with.
Hope it help.