How can I use jQuery to submit a form without refreshing? - php

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

Related

jQuery trigger previously defined onclick from link in new window

I am submitting a form using jquery onclick. On the PHP side, it checks to see if there is already an existing document by the same name. If true, a small form is returned in the response with 3 options, dependent on the record data. Those options are displayed in a message window. One of those selections needs to resubmit the previous form data, substituting the new name.
The problem is, the change name form does not exist when the page is loaded and thus does not recognize the ClickCheck class in the new form.
How can I resubmit this form with the new DocName?
The submit in the main form (actually this is one of four submits)
<a class="ClickCheck" id="Create" href="javascript:void(0)">Create Bill</a>
The jQuery:
$('.ClickCheck').click(function()
{
var ButtonID = $(this).attr('id');
$('#Clicked').val(ButtonID);
var Form = $('#TheForm');
if(ButtonID == "Save")
{
// Do save code
}
else
{
var FormData = Form.serialize();
$.ajax(
{
type: "POST",
url: "scripts/Ajax.php",
data: FormData,
success: function(response)
{
$('#MWContent').html(response);
$('#MessageWindow').show();
}
});
}
});
Then, in the response, I have:
<form id="ChangeName" name="ChangeName">
Use another name:
<input type="text" id="DocName" name="DocName" size="60" maxlength="60" value="" placeholder="Document Name" />
<a class="ClickCheck" id="NewName" href="javascript:void(0)">Go</a>
</form>
The idea is to have the "NewName" resubmit the form (with the new name, of course.) I can, of course, detect that in the click function.
You can attach the click() event to the document to make it global.
$(document).on('click', '.ClickCheck', function(e){
e.preventDefault() // <<<< Either this
// Do stuff
return false // <<<< Or this
})
http://api.jquery.com/on/
Also don't use href="javascript:void(0)", use return false or e.preventDefault() in the callback function.

Submitting form with AJAX without button

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();
});

jQuery .Post after javascript:submit_contact()

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 );
});
}

jquery validate with multiple submit buttons does not recognise second submit action

I am using the jquery validate plugin to validate and submit a form on my page which has multiple submit buttons to run different functions.
One submit button runs using the $post method while the other uses the standard action method.
(Please stick with me if my terminology is wrong)
The problem I am having is that if I submit the form using the first button, then try again using the second button, it trys to run the first action again on the second submit.
Here's my code which will hopefully make things clearer...
<form id="myForm" action="add.php">
<input type="submit" id="myfunction" />
<input type="submit"​ id="add" />
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​<input type="text" name="myvalue" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
and my validate code...
$("#myForm input[type=submit]").click(function(e) {
if (e.target.id == 'myfunction') {
$("#myForm").validate({
submitHandler: function(form) {
$.post('myfunctionpage.php', $("#myForm").serialize(), function(data) { });
}
});
} else if (e.target.id == 'add') {
$("#myForm").validate({
rules: {
name: {
required: true,
}
}
});
}
});​
Why don't you seaprate the code into two segments?
$("#myfunction").click(function(e) {
$("#myForm").validate({
submitHandler: function(form) {
$.post('myfunctionpage.php', $("#myForm").serialize(), function(data) { });
}
});
}
$("#add").click(function(e) {
$("#myForm").validate({
rules: {
name: {
required: true
}
}
});
}
You need to stop the form submission in the $.post case. Try returning false from the click event handler, that should stop the event from bubbling to the form and causing it to submit.
Personally I hook into the submit event on the form element instead of click events on the buttons. The reason is that many users submit forms by placing the cursor in a text box and then pressing enter. No click event ever occurs and your code is bypassed...
also, its been a while since i used the validate plugin, but i think you're using it wrong calling validate() after a form has been submitted. check the docs for proper use.
Just in case someone is looking for that.
Simple after the first submit use $("#myForm").validate().destroy(); in order to clear "form data".
https://jqueryvalidation.org/Validator.destroy/

is the browser or server ignoring the code?

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(){

Categories