can I use the submit button to activate an AJAX function? - php

I have an HTML form that currently just posts the data directly to a PHP file. I want to update the code so that the submit button sends the data to a JavaScript function so that I can create an AJAX function. Is it possible for the submit button to activate a JavaScript function rather than posting to a php file? The only thing I have come up with is below, which quite obviously does not work:
<html>
<head>
<script type="text/javascript">
function ajax(){
//...
}
</script>
</head>
<body>
<form action="ajax();">
<!-- ... -->
<input type="submit" value="Submit" />
</form>
</body>
</html>

You can give the "submit" input a "click" handler that explicitly prevents the default behavior from being carried out.
<input type='submit' value='Submit' onclick='ajax(event)'>
Then in the function:
function ajax(event) {
if ('preventDefault' in event) event.preventDefault();
event.returnValue = false; // for IE before IE9
// ...
}
edit #Esailija points out correctly that another option is to handle the "submit" event on the <form> element instead. The function would look pretty much the same, in fact exactly the same, but you'd wire it up like this:
<form id='yourForm' onsubmit='ajax(event)'>
That will also trap things like the "Enter" key action, etc.

Of course you can. But it's more useful to call your Javascript function in the input like this :
<input type="submit" value="Submit" onclick="ajax();" />
And remove the action part in the form.

I jQuery you can use event.preventDefault(); otherwise just use return false;
http://jsfiddle.net/mKQmR/
http://jsfiddle.net/mKQmR/1/

Pointy is correct... just add a click handler to the submit button, however make sure the last line of the click handler returns "false" to prevent the form from actually being posted to the form's action.
<html>
<head>
<script type="text/javascript">
function ajax(){
//...
return false;
}
</script>
</head>
<body>
<form action="thispage.htm">
<!-- ... -->
<input type="submit" value="Submit" onclick="ajax();" />
</form>
</body>
</html>

Related

passing form post with WYSIWYG

I am trying to pass form values through post form but nothing shows.
using this HTML5 Text Editor http://suyati.github.io/line-control/
I'm using this method for form and php code
<?php
if(isset($_POST['submit'])){
echo $_POST['txtEditor'];
}
?>
html form i am using
<form method="post">
<textarea name="txtEditor" id="txtEditor" ></textarea>
<input name="submit" type="submit" value="Submit">
</form>
and the java script is
<script src="WYSIWYG-Text-Editor/editor.js"></script>
<script>
$(document).ready(function() {
$("#txtEditor").Editor();
});
</script>
Have checked the doc and apparently you need to set the value by yourself, here is a solution:
Add some code to your initialization code:
<script>
$(document).ready(function() {
$("#txtEditor").Editor();
$('form').submit(function () {
$('#txtEditor').val($('#txtEditor').Editor('getText'));
});
$('#txtEditor').Editor('setText', $('#txtEditor').val());
});
</script>
On form submit we actually set the textarea value with what the user input in the WYSISWYG.
In the next line of code we set the value of the WYSISWYG with what value comes in the textarea (as you requested in your comment).

Run a PHP script on click of a button?

I have a php file which I want be executed when I click on a button. I have been using the following code to achieve the same:
<form action="test.php" method="post">
<input type="submit" value="Run Script" name="submit">
</form>
The code seems to take me to test.php file, but I want to be redirected back to the page where I was. Can is be possible to run this test.php on click on a button and not get redirected? Something like running the script in background?
Please let me know if you guys need further clarification.
Any help will be highly appreciated.
Thanks in advance guys!
you will need to use AJAX
<script>
function doTheFunction(){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","URL_OF_PHP_FILE",true);
xmlhttp.send();
}
</script>
<button onclick"doTheFunction();">Run the script</button>
You need to do an ajax call and prevent the forms submit.
Html:
<form onsubmit="return doAxajCall();"> </form>
js Code:
function doAjaxCall(){
//do ajax call however you want
return false; //prevents the form from submitting
}
Easy way;
Make the action of your form 'self' like this;
<form action="#" method="post">
<input type="submit" name="submit" value="Do PHP">
</form>
Then test for submission at the top of the page like this;
if (isset($_POST['submit'])) {
// do stuff
}
in your instance 'test.php' has to included in the original file.
at the bottom of you php file
header('Location: lastPage.php');
or do some tricks using ajax.
code:
<!-- including jquery.min.js cdn -->
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<input type="submit" value="Run Script" id="submit" name="submit" />
<!-- now set ajax call for button -->
<script>
$("#submit").click(function(){
$.ajax({
url:'test.php',
type:'POST',
success:function(response){
alert('test.php file executed');
}
});
});
</script>

Why is my form submitting twice?

SO for some reason my form is submitting two times with a single button press. This is my first time using jquery Form plugin, and I imagine that jquery is submitting once and the form is "naturally" submitting as well. I have seen that the remedy is to attach a "return false" to the onSubmit event handler of the form. I thought I am doing that, but obviously it is not working.
Can anyone help?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>User form entry </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.validate.js"></script>
<script src="jquery.passwordStrength.js"></script>
<script src="jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#signupForm').ajaxForm(function() {
var queryString = $('#signupForm').formSerialize();
$.post('process.php', queryString);
});
});
</script>
</head>
<body>
<form id="signupForm" action="process.php" onsubmit="return false" method="post">
<fieldset class="password">
... form goes here
<button type="submit" name="formSubmit" value="submit">Click to submit</button>
</form>
<div id="results"></div>
</body>
</html>
I have tried adding onsubmit="return false" to the form element, but then I have no submission at all. I have also tried adding "return false;" to the jQuery, but then I still have double submissions. What am I missing? This seems to be the standard methodology according to the jQuery Form Plugin site.. how is my form different?
(By the way, just to be clear.. I am not talking about the problem of having multiple consecutive form submits by pressing the button repeatedly. My problem is "one submit button push = two submits".)
$('#signupForm').ajaxForm(function() {
var queryString = $('#signupForm').formSerialize();
$.post('process.php', queryString);
});
This is submitting it twice .... the ajaxForm method once and then the post() the second time
The ajaxForm method handles the form sumbission for you ... you dont need to add the post() method ... the function inside of ajaxForm is a callback, executed on success ...
$('#signupForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
this code would show the alert after the successful post ... simple example here -> http://jquery.malsup.com/form/
You should also remove the onsubmit attribute from the form ...
Update
If you want to show results ... do it like this :
$(document).ready(function() {
$('#signupForm').ajaxForm({ target: '#results' });
// this will output the responseText from the submitted form to the target DOM element
});
avoid using
<button type="submit" name="formSubmit" value="submit">
so naturally your submit button will do one submit and your jquery will do another submit
use this
<input type="button" name="formSubmit" value="submit">
Try using this:
onsubmit="void(0);"
Don't use a submit button. Use a regular button.

AJAX file upload onchange as opposed to onsubmit

I am using the following code to effect an iframe that allows an ajax file upload on submit of the form without refresh.
This works as expected
window.onload=init;
function init() {
document.getElementById('form').onsubmit=function() {
document.getElementById('form').target = 'iframe';
}
}
What i would like to do is the same thing but 'onchange' of the file field input, i.e. when the user has chosen a file, to autmatically trigger the init() function and thus upload the file. I have tried with this code:
document.getElementById('file').onchange=function(){...
This doesn't work, and i'm completely stuck. Any ideas?
Many thanks
This should work for you
<script type="text/javascript">
window.onload = function() {
// add old fashioned but reliable event handler
document.getElementById('file_input').onchange = function() {
// submit the form that contains the target element
this.form.submit();
}
}
</script>
<iframe name="my_iframe"></iframe>
<form target="my_iframe"
action="your/file.ext"
method="post"
enctype="multipart/formdata">
<input type="file" name="my_file" id="file_input">
<!-- for no js users -->
<noscript>
<br/>
<input type="submit">
</noscript>
</form>
i think something like .live() will solve your issue hopefully, comment if you want more info on how to use it...
Give the file input element an id and:
$(document).ready(function(){
$(element).change(function(e){
fileInfo = e.currentTarget.files[0];
init();
});
});

jquery form plugin & programmatic submit

There are similar questions at SO, but none that seem to address this.
Below is a very simplified variant of my situation. Drupal/PHP site -- I have a form w/ submit button that I am using jquery.form plugin to ajax-ly submit. It works fine if I use the submit (#submit) button.
Now, I want to programmatically fire that button using another button (#submit2) outside of the form. I can do that using jquery click() function, but the content coming back isn't going to the ajax target as I would expect.
I do not have much freedom to re-organize this code, else i would.
(Note I tried to make this code easy for you to run by src-ing jquery and the form plugin from my website.)
Ideas? Thanks!
<?php
if ($_REQUEST['submit'] == 'Submit') {
print 'ajax returns ... ' . $_REQUEST['text'];
exit;
}
?>
<html>
<head>
<script type="text/javascript" src="http://enjoy3d.com/scripts/jquery-1.2.6.js"></script>
<script type="text/javascript" src="http://enjoy3d.com/scripts/jquery.form.js"></script>
<script type="text/javascript">
$(function() {
$('#form').ajaxForm( { target: $('#span') } );
$('#submit2').click( function() { $('#submit').click(); } );
});
</script>
</head>
<body>
<span id='span'>target span</span>
<form method='post' id='form'>
<input type='text' name='text' size='50' />
<input type='submit' id='submit' name='submit' value='Submit'/>
</form>
<input type='submit' id='submit2' name='submit2' value='Submit Too?' />
</body>
</html>
I managed to solve a similar situation to yours. If the only objective of simulating a click on submit1 is to submit the form, you might try:
$('#submit2').click(function() {
$('#form').trigger('submit');
});
You may also need to return false immediately after triggering the form submit button from the non-form submit button click event code. For example:
<script type="text/javascript">
$(function() {
$('#form').ajaxForm({ target: $('#span') });
$('#submit2').click(function() { $('#submit').click(); return false; });
});
</script>
It works for me. Is that what you are looking for?
Have you tried giving a name to the form, and instead of
$('#submit2').click( function() { $('#submit').click(); } );
doing
$('#submit2').click( function() { document.myForm.submit(); } );
That should do the same thing as having the submit button clicked if the form has been ajaxified.

Categories