Submit form sending through user1_id and newmsg without page refresh - php

How would I go about submitting the below form without a page refresh using Ajax? I'm needing to send the user1_id via 'toid' and the content from the textarea 'newmsg'.
FORM
<form action="insert.php" method="POST" class="form_statusinput">
<input type="hidden" name="toid" value="<?php echo $user1_id ?>">
<span class="w">
<textarea class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off"></textarea>
</span>
<button type="submit" value="Submit">Feed</button>
</form>

1) Add an ID to form, lets say "myform".
2) Then you can get all all fields from this form and send it using AJAX (dont forget to include jQuery):
var form_data = $("#myform").serialize();
$.ajax(
{
url: 'script.php',
type: 'POST',
cache: false,
data: form_data,
success: function(message)
{
...
},
error: function(message)
{
...
}
});

If jQuery is an option, it is quite easy.
See jQuery.post(): http://api.jquery.com/jQuery.post/
// Example: send form data using ajax requests
$.post("test.php", $("#testform").serialize());
There are many options depending on what you need to do with the return values, it's best to just read the documentation in this case.

Related

How to send part of form data using JQuery & Ajax to php without submit button

I have an application for rating a service. A on the form page has inputs for comment, giving it a star etc.
I want to make it in a way that when a user clicks on a star it should send the value of the star input to a php script for processing without having to click on the submit button. I thought of using separate forms for this, however, i just want to use one form because different forms will bring the layout.
HTML Form
<form action="" method="POST">
<input type="text" name="name">
<textarea name="comment"></textarea>
<input type="radio" name="rate" value="1">
<input type="radio" name="rate" value="2">
<button type="submit" name="submit">Submit</button>
</form>
JQuery for the sending rate to php
$("input[name=rate]").change(function(event){
var rating_num = $(this).val();
$.ajax({
url: '../handlers/rating.php',
type: 'POST',
data: rating_num,
cache: false,
contentType: false,
processData: false,
beforeSend:function(){
},
success: function (data) {
alert(data);
}
});
})
rating.php
echo $_POST['rating_num'];
The output I get is "undefined index:rating_num"
The above code is just a sketch.
First of all, you can debug your $_POST variable with var_dump function.
However, the reason why you have this error is that you need to put an object in the 'data' parameter.
{
...
data: {
rating_num: rating_num
},
...
}
Also, you could use $.post instead of $.ajax. See examples in jQuery API documentation.
$.post('rating.php', {rating_num: rating_num})
.done(function(data) {
console.log(data);
});

how to serialize HTML form data which is inside php loop

I have a HTML form which is inside PHP loop and trying to send that form data via ajax.
If the php loop executes 3 times, all the form data is sent out.
tried to update the form name dynamically. but not aware of how to send that via ajax.
HTML form: this form is inside php loop
<form action="" method="post" name="cartForm">
<input type="hidden" name="item_id" value="<?php echo $row['productID']; ?>" />
<input type="submit" name="submit" value="Add to cart" class="button btn" onclick="addCartFun()" />
</form>
Ajax call:
function addCartFun(){
$.ajax({
url: '/cartHand.php',
type: 'POST',
dataType: 'json',
data: $("form[name=cartForm]").serialize(),
success: function(){
}
});
}
I expect that if I click that submit button, only data corresponding to the form has to be sent.
Thanks.
It's working fine now. I dynamically generated the form name and made that ajax call inside the call inside the loop. Thanks.
AJAX call:
$("form[name=<?php echo $formName ?>]").submit(function({
$.ajax({
url: '/cartHand.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(){}
});
});
Form Name:
<form action="" method="post" name="<?php echo $formName ?>"></form>

To make html form run two actions

Is it possible to submit two forms using a single submit button?
like if a user clicks submit on a form, that form runs test.php and form.php with the variables still intact?
If not then is it possible when the user clicks submit on a form it runs only test.php then test.php runs form.php with the variables still intact.
I don't think this is possible on a normal form submission, but you can try to utilize an AJAX request on both forms on demand. (This is just an example, not tested, just a guide or an idea.).
<!-- forms -->
<fieldset><legend>Form #1</legend>
<form id="form_1" action="test.php">
<label>Username: <input type="text" name="username" /></label>
<label>Password: <input type="text" name="password" /></label>
</form>
</fieldset>
<br/>
<fieldset><legend>Form #2</legend>
<form id="form_2" action="form.php">
<label>Firstname: <input type="text" name="fname" /></label>
<label>Lastname: <input type="text" name="lname" /></label>
</form>
</fieldset>
<button id="submit" type="button">Submit</button>
<!-- the forms is just an example -->
<!-- it would be weird to separate such fields in to different forms -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').on('click', function(){
$.ajax({
url: $('#form_1').attr('action'),
data: $('#form_1').serialize(),
type: 'POST', // or whatever get
dataType: 'JSON', // or whatever xml script html
success: function(response) {
}
});
$.ajax({
url: $('#form_2').attr('action'),
data: $('#form_2').serialize(),
type: 'POST', // or whatever get
dataType: 'JSON', // or whatever xml script html
success: function(response) {
}
});
});
});
</script>
The form can have only one action, if you want to pass data to a different page then you can do that by calling an ajax function..

Making Ajax Form Use Native Wordpress

I have a form that uses Ajax to send a serialized forms data to send to a php file called contact-submit
i know i should wrap the contents of that page in a function...and add it to the functions.php file
i plan on calling the function MyContactForm
but i dont know the proper syntax to serialize the form and post the data to the function
heres what i have so far ...*keep in mind i left out the form fields...because we are focusing on the script part of this ...if the form is serialized...should grab everything
html
<form id="contactform" action="<?php echo home_url('contact-submit'); ?>" method="post">
<input class="textbox required" type="text" name="name2" id="name" value="Your Name" />
<input class="submit" value="Send" type="submit" alt="Send message" name="submit" />
</form>
script
jQuery("#postform").validate();
var AjaxSubmit = function(){
var btnText=jQuery('#contactform .submit').val();
// inform client that data is been sent:
jQuery('#contactform .submit').val('Sending...');
jQuery('#contactform .submit').attr('disabled', true);
jQuery.ajax({
type: 'POST',
url: jQuery('#contactform').attr('action'),
data: jQuery('#contactform').serialize(),
// successful POST - display result in success div:
success: function(msg){
jQuery('#contactform .form, #contactform .contacthead').slideUp(500,function(){
jQuery('#contactform div.success').removeClass('hiddne').fadeIn(500);
});
},
error: function(response) {
jQuery('#contactform .submit').val(btnText);
jQuery('#contactform div.error').html(response.statusText).slideDown(500);
}
});
}
jQuery("#contactform").validate({
submitHandler: AjaxSubmit
});
});
My Question is.....what is the proper syntax for serializing a form and passing the data to a php function?

onclick form send via ajax no page refresh

I've been racking my brains for days looking at examples and trying out different things to try and get my form to submit with Ajax without a page refresh. And Its not even sending the data now.. I don't know what I'm doing wrong..Can someone run through my ajax and form please.
Toid is the users id and newmsg is the text in which the user submits. The two values get sent to the insert.php page.
I would really appreate the help. I'm new to Ajax, and I look at some of it and don't have a clue. If I finally got it working, It may help me realize what I've done wrong. I am looking up tutorials and watching videos..but it can be very time consuming for something that would be simple to someone in the know on here. It maybe that I've got the wrong idea on the ajax and it makes no sense at all, sorry about that.
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function() {
homestatus()
event.preventDefault();
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
});
return false;
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
</div>
</form>
INSERT.PHP
$user1_id=$_SESSION['id'];
if(isset($_POST['toid'])){
if($_POST['toid']==""){$_POST['toid']=$_SESSION['id'];}
if(isset($_POST['newmsg'])&isset($_POST['toid'])){
if($_POST['toid']==$_SESSION['id']){
rawfeeds_user_core::create_streamitem("1",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
}else{
rawfeeds_user_core::create_streamitem("3",$_SESSION['id'],$_POST['newmsg'],"1",$_POST['toid']);
Try using firebug to identify bugs in your code. It's a really good companion for developing javascript. Nearly all of your bugs led to error messages in the firebug console.
You had several errors in your code, here is the corrected version:
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var toid = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + content + "&newmsg=" + newmsg,
success: function(){alert('success');}
});
});
});
And here the corrected html:
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id; ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed">
</div>
</form>
Actually onsubmit event has to be used with form so instead of
<input type="submit" id="button" value="Feed" onsubmit="homestatus(); return false" >
it could be
<form id="myform" method="POST" class="form_statusinput" onsubmit="homestatus();">
and return the true or false from the function/handler, i.e.
function homestatus()
{
//...
if(condition==true) return true;
else return false;
}
Since you are using jQuery it's better to use as follows
$("form#myform").on('submit', function(event){
event.preventDefault();
var toid = $("#toid").val(); // get value
var content = $("#newmsg").val(); // get value
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + toid + "&newmsg=" + content,
success: function(data){
// do something with data
}
});
});
In this case your form should be as follows
<form id="myform" method="POST" class="form_statusinput">
...
</form>
and input fields should have a valid type and value attribute, Html form and Input.
I think you should read more about jQuery.
Reference : jQuery val and jQuery Ajax.
change the form to this
<form id="myform" ... onsubmit="homestatus(); return false">
you don't need the onsubmit attribute on the submit button, but on the form element instead
homestatus might be out of scope
function homestatus () {
var toid = $("#toid").attr("toid");
var content = $("#newmsg").attr("content");
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+content+"&newmsg="+ newmsg,
success: function(){
}
});
}
This isn't tested, but try this (I annotated some stuff using comments)
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
// not sure what this does, so let's take it out of the equation for now, it may be causing errors
//homestatus()
// needed to declare event as a param to the callback function
event.preventDefault();
// I think you want the value of these fields
var toid = $("#toid").val();
var content = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid="+toid +"&newmsg="+ content,
success: function(){
}
});
return false;
});
});
</script>
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" / >
</div>
</form>
It's a lot easier to let .serialize() do the work of serializing the form data.
The submit handler also needs event as a formal parameter, otherwise an error will be thrown (event will be undefined).
With a few other changes, here is the whole thing:
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
homestatus();
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: "insert.php",
data: formData,
success: function(data) {
//...
}
});
});
});
</script>
<form id="myform" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed" >
</div>
</form>
Unless you are omitting some of your code, the problem is this line:
homestatus()
You never defined this function, so the submit throws an error.
You may want to take a look at jQuery (www.jquery.com) or another js framework.
Such frameworks do most of the stuff you normally have to do by hand.
There are also a bunch of nice helper functions for sending form data or modifying html elements

Categories