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(){
Related
I'm trying to send a form with AJAX and without submit button. Everything works just fine with submit button, but if I try to submit the form by clicking something else it won't work.
I searched for an answer for quite a while, but didn't find anything useful so far.
function ajaxSubmit(){
var showHideForm = jQuery('#dashboard-hki-subjects-form').serialize();
$.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: showHideForm,
success:function(data){
$('#formMessage').html(data);
}
});
return false;
}
$('.show-hide-subject-button').click(function(){
var subject = $(this).attr('subject');
$('#hide-subject').attr('value',subject);
});
$('#dashboard-hki-subjects-form').submit(ajaxSubmit);
I'm using Wordpress, so the AJAX is handeled with admin-ajax.php.
What if you just use an enter key handler...
Try this:
<input type="text" name="txt"/>
$('#txt').keydown(function (e){
if(e.keyCode == 13){
console.log('you pressed enter!'); //prints to the browser console...
ajaxSubmit(); //the function you described in your question...
}
})
You have to bind the ajaxSubmit() to whatever there is you're clicking, otherwise there simply will be nothing on your page to trigger it. E.g., if you want your form to be submitted whenever you click on the .show-hide-subject-button element, you have to call ajaxSubmit() explicitly:
$('.show-hide-subject-button').click(function(){
var subject = $(this).attr('subject');
$('#hide-subject').attr('value',subject);
ajaxSubmit();
});
I have an AJAX call that passes data to another php file, createTest2.php, as below.
But the createTest2.php file throws error
Notice: Undefined index: sample in C:\xampp\htdocs\TestProj\Test\createTest2.php on line 2
caller.php
$(document).ready(function(){
$("#button_submit").click(function()
{
$.ajax({
type:"POST",
url:"createTest2.php",
data:{sample : "test"},
success:function()
{
alert("success");
}
});
});
});
createTest2.php
<?php
$test_name = $_POST['sample'];
echo $test_name;
?>
Total stab in the dark here but I'm guessing you have something like this
<form action="createTest2.php">
<!-- some elements here -->
<input type="submit" id="button_submit">
</form>
In which case, you should prevent the default action on the button, eg
$("#button_submit").on('click', function(e) {
e.preventDefault();
// and the rest of your ajax code
});
What's happening is your form's default method is GET and it is submitting normally, thus $_POST isn't populated.
Ideally, you should never blindly accept user input. I'd start with some checks in your PHP file
if (!isset($_POST['sample'])) {
http_response_code(406);
throw new Exception('sample data not submitted via POST');
}
$test_name = $_POST['sample'];
Secondly, catching click events on form submit buttons is rife with problems. For one, there's more than one way to submit a form. You should catch the form's submit event instead, eg
<form id="myForm" action="createTest2.php">
<!-- etc -->
<button type="submit">Go</button>
</form>
and the JS
$('#myForm').on('submit', function(e) {
e.preventDefault();
$.post(this.action, { sample: 'test' }).done(function(data) {
alert('Success');
});
});
I'm trying to submit a little contact form.
Here is my jquery to POST:
<script>
$(document).ready(function(){
function submit_contact()
{
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", {
contact_text: $("[name='contact_text']").val(),
contact_email: $("[name='contact_email']").val(),
}, function(data){
console.log( data );
});
}
});
</script>
Here is my html that handles the form:
<form method="post" >
<textarea id="contact_me_text" name="contact_text">Ask me anything!</textarea>
<div>
<input type="text" name="contact_email" value="Email"/><br/><br/>
<a id="contact_submit" href="javascript:submit_contact()">Submit</a>
</div>
</form>
Everything seems to look ok but the form is not submitting. I've run the .php file through a regular submit and it works fine.
Any thoughts?
You need to declare your function outside of $(document).ready() and then call it using anything.
Why can't I ?
As Local Variables cannot be accessed from outside, similarly local functions cannot also be accessed.
Try this:
<script>
$(document).ready(function(){
function submit_contact()
{
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", {
contact_text: $("[name='contact_text']").val(),
contact_email: $("[name='contact_email']").val(),
}, function(data){
console.log( data );
});
}
$('#contact_submit').on('click', function(){
submit_contact();
return false;
});
});
</script>
and then remove the JS inside HREF attribute.
You need to declare the function outside ready function of jQuery. Moreover you can use serializeArray to determine data to send. By using this you will not need to mention every control name. On server side you can receive the input with same names you have mentioned in your form.
function submit_contact()
{
var params = $("#formId").serializeArray();
$.post("http://www.domain.com/wp-content/themes/toronto/handlers/contact.php", params, function(data){
console.log( data );
});
}
I found a tutorial here : http://tutorialzine.com/2009/08/creating-a-facebook-like-registration-form-with-jquery/ (please take a look)
It's a nice tutorial, I followed everything there and remove extra stuff I don't want , like the functions.php with generate_function option as I am not in need of birthday etc. stuff.
All I want is a NAME(usrname) , EMAIL(email) , Password(password) , when the user click on "REGISTER" button (which is the form submit button), the script I got from the tutorial will send the data over to "regprocess.php" which contains validation check codes like checking if the submitted form data is empty.
But when I click REGISTER , the data is not sent back (the error message) from the "regprocess.php" nor the success message.
When i check with my firebug , the JSON response is showing the full php code like the one below(scroll down).
Here's my code :
HTML-
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript" src="register.js"></script>
<form id="regForm" action="regprocess.php" method="post">
<label for="usrname">Name:</label>
<input id="usrname" name="usrname" type="text" value="" class="nor">
<label for="email">Email:</label>
<input id="email" name="email" type="text" value="" class="nor">
<label for="password">Password:</label>
<input id="password" name="password" type="password" value="" class="nor">
<table><tr><td style="width:290px;"><div id="error"> </div></td><td><input name="register" type="submit" value="Register" id="regbtn"><center><img id="loading" src="images/load.gif" alt="Registering..." /></center></td></tr></table>
</form>
Okay the Ajax script is in "register.js" above.
Ajax script(register.js)-
$(document).ready(function(){
$('#regForm').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
hideshow('loading',1);
hideshow('regbtn',0);
error(0);
$.ajax({
type: "POST",
url: "regprocess.php",
data: $('#regForm').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
hideshow('regbtn',1);
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error(act,txt)
{
hideshow('error',act);
if(txt) $('#error').html(txt);
}
CSS:
Regbtn is the submit button , it's visibility is set to visible
loading is set to hidden
error is set to hidden
When a user click on Regbtn , loading visibility will become visible while Regbtn hides(visibility:hidden).
It's done in the Ajax script(register.js).
Okay now the php:
PHP(regprocess.php)-
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
This checks whether the username , email and password data is empty , if yes , returns a message which will be displayed in the Error(#error in html) , it also checks whether email provided is valid.
If everything else is right , user will be directed to registered.html
But i think the script can't get the error message back from the php.
I hope someone can help me. Thanks.
Have a nice day.
hmm not too much of an answer but what I do on my forms is a I submit via ajax and put the result from the php page in the parent of the form.
below is the plugin in code. it works when the form is a child of a div by default.
(function($){
$.fn.extend({
//pass the options variable to the function
ajaxForm: function(options)
{
//Set the default values, use comma to separate the settings, example:
var defaults =
{
target: 'div'
}
var options = $.extend(defaults, options);
return this.each(function()
{
var o=options
$(this).submit(function(event)
{
event.preventDefault();//stop from submiting
//set needed variables
var $form = $(this)
var $div = $form.parent(o.target)
$url = $form.attr("action");
//submit via post and put results in div
$.post( $url, $form.serialize() , function(data)
{ $div.html(data) })
})
});
}
});
})(jQuery);
note this will run for every form so change it as you would wish.
whatever you want to display just echo on the php page. also this is made for post and the php page will access anything just like any other form being with post.
also it wouldn't be hard to modify if you felt necessary to send as json instead.
You need to put php tags around the php code, like this:
<?php
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
?>
i have this form:
<form id="myform" name="myform" action="test.php" method="post">
<input type="text" name="shout-in" id="proShoutIn" maxlength="80" />
<img src="post.gif"/>
</form>
how can i do a ajax post so that i can use if (isset($_POST['shout-in'])){..do something..}?
i need to get the value that gets entered in the <input> and do a post with it.
any ideas?
thanks
$('#add_shout').click(function () {
var $form=$('#myform');
$.post($form.attr('action'), $form.serialize());
});
$.post() - $.ajax() shorthand for the POST method
.serialize() - creates a text string in standard URL-encoded notation
With the 3rd (optional) parameter of $.post() you can specify a callback function which will receive anything that was sent back as its only parameter. It will run when the AJAX query successfully finished (so you can do DOM modifications that depend on the AJAX call, etc.).
You also might want to prevent default form submission (in a lot of browsers pressing Enter in the input field would trigger it) and run the AJAX submission:
$('#myform').submit(function (e) {
$('#add_shout').click();
e.preventDefault();
});
$.post("test.php", $("#myform").serialize(),
function(data) {
// do something with the response
}
);
$("#myform").submit(function (e) {
$.post(this.action, $(this).serialize(), function (data) {
//handle response
});
//prevent form from submitting. In jQuery, do not use return false
e.preventDefault();
}
Nettuts plus:
Submit A Form Without Page Refresh using jQuery