I have the following simple form:
Here is my code behind the form:
<form action="javascript:void(0);" method="post">
<fieldset>
<legend>ROOM EQUIPMENT</legend>
<div class="inline_inputs">
<div class="input_box">
<input type="checkbox" name="equipment" value="computer" id="computer">
<label for="computer">Computer</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="projector" id="projector">
<label for="projector">Projector</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="whiteboard" id="whiteboard">
<label for="whiteboard">Whiteboard</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="visualiser" id="visualiser">
<label for="visualiser">Visualiser</label>
</div><!-- .input_box -->
<div class="input_box">
<input type="checkbox" name="equipment" value="desk" id="desk">
<label for="desk">Desk</label>
</div><!-- .input_box -->
</div>
</fieldset>
<div class="buttons">
<input type="submit" class="reg_button" value="GET ROOMS" />
</div><!-- .buttons -->
And finally here is how I am making the AJAX request on the same page where this form sits:
<script>
$('form').submit(function(){
var str = $(this).serialize();
$.ajax({
url: "userLogic.php",
cache: false
}).done(function( html ) {
$("#rooms_wrap").append(html);
});
});
I am fairly new to PHP and I'm having an issue with the form submission. When I make a selection, my selection is not sent to the userLogic.php file. I get a print out of:
Sorry, You have not made a selection.
This is coming from the PHP code that sits inside the userLogic.php file which is this:
<?php
include("connect.php");
$items = array_key_exists('equipment', $_POST) ? $_POST['equipment'] : '';
if(!empty($items))
{
if ($_POST["equipment"] == "computer") {
echo "checked computer!";
} else if($_POST["equipment"] == "projector")
{
echo "checked projector!";
$sql = "SELECT room_name, day_avail, from_time, to_time, equip_name
FROM rooms
JOIN equipment ON (equipment.room_id = rooms.room_id)
JOIN room_availability ON (room_availability.room_id = rooms.room_id)
WHERE equip_name='Projector'
GROUP BY day_avail";
$myData = mysql_query($sql,$conn) or die(mysql_error());
} else if($_POST["equipment"] == "whiteboard")
{
echo "checked whiteboard!";
} else if($_POST["equipment"] == "visualiser")
{
echo "checked visualiser!";
} else if($_POST["equipment"] == "desk")
{
echo "checked desk!";
}
} else {
echo "> Sorry, You have not made a selection.";
}
?>
Look up the arguments for $.ajax. You're not POSTing... And you're not POSTing data, either.
type: "POST"
and
data: str
needs to be in:
$('form').submit(function(){
var str = $(this).serialize();
$.ajax({
url: "userLogic.php",
cache: false,
type: "POST",
data: str
}).done(function( html ) {
$("#rooms_wrap").append(html);
});
});
Doesn't seem you are posting your data..do it like this.
$.ajax({
url: "userLogic.php",
cache: false,
type: "POST",
data: str,
//rest of your code
Related
I have this script that allows me to send data to the database without reloading the page. The form data is sent to file process.php.
At the end of the process, inside the div box of the form is printed a notice that everything went ok
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '.formValidation', function(){
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'submit.php',
data : data,
success : function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
});
return false;
});
});
</script>
Page success.php:
foreach( $_POST as $key => $value ) {
$sql = "INSERT INTO tbl_".$key."(nome_".$key.") VALUES ('$value')";
$result = dbQuery($sql);
}
print "ok";
And the div box for the notice <div class="result"></div>
The problem: I have many div box with a form and when I print the notice of success, it happen into all the <div>, because the call notification is always .result
success: function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
What I want: Print the success notice in its own div depending on the form that I sent.
Thanks
EDIT: The html interested
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form> <!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
<?php
$comune = "SELECT * FROM tbl_comune ORDER BY nome_comune ASC";
$result_comune = dbQuery($comune);
if (dbNumRows($result_comune) > 0) {
while($row_comune = dbFetchAssoc($result_comune)) {
extract($row_comune);
?>
<option value="<?php echo $id_comune; ?>"><?php echo $nome_comune; ?></option>
<?php
}
} else {
?>
<option value="">Non ci sono dati</option>
<?php
}
?>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
If the form is in a div and the result is next to the form, you can do sibling:
$form.next(".result").html(data);
or elsewhere in the same parent:
$form.parent().find(".result").html(data);
or in your case
$form.find(".result").html(data);
Like this - note I have removed all the unnecessary hiding.
$(function() {
$(document).on('submit', '.formValidation', function(e) {
e.preventDefault();
var data = $(this).serialize();
$form = $(this); // save a pointer to THIS form
$result = $form.find(".result");
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
success: function(data) {
$result.html(data);
$form.fadeOut(500, function() {
$result.fadeIn(500)
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form>
<!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
I am using jquery serialize and Ajax to capture form values and process them with Ajax using json as data Type, but no values are being returned. I have tried various ways to try and see why this is happening, but to no avail. There is no errors being returned in firebug or chrome. I would be grateful if someone could check my code and point out my error. Thanks
html code
<!--- Form to add box -->
<div id="boxaddform" style="display:none;">
<div class="dialogTop_padd"></div>
<form id="BA_boxform" name="BA_boxform" method="post">
<fieldset>
<legend><span></span>Select Company</legend>
<div class="spacer"></div>
<div class="formMessage">Click again to open</div>
<div class="fld_fld">
<div>
<label for="BA_customer">Company:</label><br />
<select name="BA_customer" id="BA_customer">
<option SELECTED VALUE="">Select a Company</option>
<?php
do {
?>
<option value="<?php echo $row_Recordsetcust['customer']?>"><?php echo $row_Recordsetcust['customer']?></option>
<?php
}
while ($row_Recordsetcust = mysql_fetch_assoc($Recordsetcust));
$rows = mysql_num_rows($Recordsetcust);
if($rows > 0)
{
mysql_data_seek($Recordsetcust, 0);
$row_Recordsetcust = mysql_fetch_assoc($Recordsetcust);
}
?>
</select>
<div class="spacer"></div>
<!--- displays the address and dept from the change function -->
<div id="BA_dept"></div>
<br />
<div id="BA_address"></div>
</div>
</fieldset>
<div class="dialogTop_padd"></div>
<!--- fieldset for service level -->
<fieldset>
<legend>Service Level</legend>
<div class="spacer"></div>
<div>
<label for="BA_service">Service level:</label>
<select name="BA_service" id="BA_service">
<option SELECTED VALUE="">Select an option</option>
<option value="Standard">Standard</option>
<option value="Rapid">Rapid</option>
</select><br />
</div>
</fieldset>
<div class="dialogTop_padd"></div>
<!--- fieldset for box # -->
<fieldset>
<legend>Box Details</legend>
<div class="spacer"></div>
<div>
<label for="BA_box">Box#:</label><br />
<input id="BA_box" name="BA_box" type="text" size="32" maxlength="128" value = "" /><br />
</div>
<div>
<label for="BA_destdate">Destroy date:</label>
<input id="BA_destdate" name="BA_destdate" type="text" size="32" maxlength="128" value = "" /><br />
</div>
</fieldset>
<div class="dialogTop_padd"></div>
<!--- fieldset for authorisation -->
<fieldset>
<legend>Authorisation</legend>
<div class="spacer"></div>
<div>
<label for="BA_authorised">Requested By:</label>
<input id="BA_authorised" name="BA_authorised" type="text" value="<?php echo $_SESSION['kt_name_usr']; ?>"><br />
</div>
</fieldset>
<!--- div to show callback result from ajax via dialog -->
<div id="BA_addbox"></div>
<br />
<input type="submit" name="submit" value="Submit Intake" />
<input type="reset" name="cancel" value="Clear Form" />
<!--- buttons to submit form and reset form to default status -->
<!-- <button id="BA_submit" class="submitbutton icon-right ui-state-default2 ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span>Add Box</button>
<button type="reset" id="BA_reset" class="resetbutton icon-right ui-state-default2 ui-corner-all"><span class="ui-icon ui-icon-circle-plus"></span>Reset</button>
--><br />
</form>
</div>
jquery code
$(function() {
$("#BA_customer").live('change', function() {
if($(this).val()!="")
$.get("/domain/admin/getDept.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_dept").html(data).show();
});
$.get("/domain/admin/getOptions.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_address").html(data).show();
});
});
});
//Begin function to submit box intake form
$(function() { // Function to add box
$("#boxaddform").dialog({
autoOpen: false,
resizable: false,
modal: true,
title: 'Submit a box intake request',
width: 550,
height: 400,
beforeclose: function (event, ui) {
$("#BA_addbox").html("");
$("#BA_dept").hide();
$("#BA_address").hide();
},
close: function (event, ui) {
//$("#BA_boxform").get(0).reset();
$("#BA_addbox").html("");
}
});
});
$(function(){
$("#boxaddform").submit(function(){
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "/domain/admin/requests/boxes/boxesadd.php",
data: formdata,
dataType: 'json',
success: function(msg){
//$("#confirm_department").hide();
/*
var $dialog = $('<div id="dialog"></div>')
.html('Your intake was successfully submitted and will be viewable in the reporting area.<br /><br />Thank you.');
$dialog.dialog({
autoOpen: true,
modal: true,
title: 'Box intake submission successfull',
width: 400,
height: 200,
draggable: false,
resizable: false,
buttons: {
Close: function() {
$( this ).dialog( "close" );
}
}
});
*/
//alert('You have succesfully submitted your ' + msg.company + ' report. Thank you.');
//console.log(msg);
//$("#BA_addbox").html("You may now close this window.");
//$("#formImage .col_1 li").show();
$("#BA_boxform").get(0).reset();
$("#boxaddform").hide();
}
});
return false;
});
});
// End function to submit box intake form
php code
<?php
$dept = mysql_real_escape_string($_POST['BA_dept']);
$company = mysql_real_escape_string($_POST['BA_customer']);
$address = mysql_real_escape_string($_POST['BA_address']);
$service = mysql_real_escape_string($_POST['BA_service']);
$box = mysql_real_escape_string($_POST['BA_box']);
$destroydate = mysql_real_escape_string($_POST['BA_destdate']);
$authorised = mysql_real_escape_string($_POST['BA_authorised']);
$form = array('dept'=>$dept, 'company'=>$company, 'address'=>$address, 'service'=>$service, 'box'=>$box, 'destroydate'=>$destroydate, 'authorised'=>$authorised);
$result = json_encode($form);
echo $result;
?>
The problem in your code is that you are serializing a DIV, what is incorrect.
The solution would be to serialize only the FORM included in your DIV with a Javascript code like:
...
$(function(){
$("#boxaddform").submit(function(){
var formdata = $('#BA_boxform').serialize();
$.ajax({
type: "POST",
url: "/domain/admin/requests/boxes/boxesadd.php",
data: formdata,
dataType: 'json',
success: function(msg){
...
}
});
return false;
});
....
Also, remember that serialize will only care for INPUT, SELECTand TEXTAREA controls as a normal FORM submit would do (http://api.jquery.com/serialize/).
I am trying to load comments from a php file using ajax.
index.php
<div id="commentsonpost" value="<?php echo $_GET['post'];?>">
</div>
<script type="text/javascript">
$(document).ready(function() {
var postid = $('#commentsonpost').attr("value");
alert(postid);
var dataString = 'getpostcomm=1&postid='+ postid;
$.ajax({
type: "get",
url: "getcomments.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
alert("re");
$("#commentsonpost").append(html);
}
});
return false;
});
</script>
getcomments.php
if(isset($_GET['getpostcomm'])){
$var=$_GET['postid']; // Adding this line causing problems
$querycomm = "select U.fname,U.lname,U.usernick,C.bcommentid,C.comment,C.date,C.visible from blogcomments as C natural join users as U where C.visible=1 and U.visible=1 and C.bpostid='{$var}' ORDER BY C.date ASC";
$resultcomm = mysql_query ( $querycomm, $connection );
echo "<div id='pcomments'>";
while($commentonpost=mysql_fetch_array($resultcomm)){
if($commentonpost['visible']==1){
echo '
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;" id="comment'.$commentonpost['commentid'].'">
<div style="width:10%;float:left;"><a href="profile.php?user='.$commentonpost['usernick'].'" >'.$commentonpost['fname']." ".$commentonpost['lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;">'.$commentonpost['comment'].'</div>
<div style="width:8%;float:right;margin-left:2%;">
';
if($commentonpost['usernick']==$_SESSION['user_nick']){
echo ' <form action="" method="post">
<input type="submit" name="delcomm" value="X" class="delcombutton" id="'.$commentonpost['commentid'].'">
</form>
';
}
echo '<h5 class="msg">'.datetime($commentonpost['date']).'</h5>
</div>
<br/>
</div>
';
}
}
echo "</div>";
echo '
<form name = "form" method = "post" action="" onsubmit="return validateform()" style="width:100%">
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;">
<div style="width:10%;float:left;"><a href="profile.php?user='.$_SESSION['user_nick'].'" >'.$_SESSION['user_fname']." ".$_SESSION['user_lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;"><textarea placeholder="Comment..." name="commenttext" id="commenttext" class="inputcomment" ></textarea></div>
<br>
<input type="submit" id="'.$_POST['post'].'" name="SubmitComment" value="Comment " class="commentbutton" style="font-size:1em;width:100px;float:right;margin-top:4px;margin-right:9%;">
</div>
</form>
</div>
';
}
Whenever i add that $var=$_GET['postid']; line in getcomments.php ajax script stop working. As soon as i remove $var=$_GET['postid']; from getcomments.php, excluding query part(obviously) form is displaying correctly.
Any ideas?
At ajax better set data fields as array values as:
$.ajax({
type: "get",
url: "getcomments.php",
data: {'getpostcomm':1,'postid':postid},
And at your PHP you have to sanitize your Id.. (if its int you may at least cast (int) )...
$var = (int) $_GET['postid'];
Also at your PHP add check if isset($_GET['postid'])...
if(isset($_GET['getpostcomm']) && isset($_GET['postid'])){
var dataString = 'getpostcomm=1&postid='+ toString(postid);
I decided to have my first go with ajax to submit my data but I'm having problems. The form seems to reset but no data is sent to the database, I'm probably missing something obvious here:
jQuery (currently included in the header of my file)
<script>
// jQuery to submit form data via AJAX to add a recovery pack
$.ajax({
type:'POST',
url: 'addrpack.php',
data:$('#rpack_add_form').serialize(),
success: function(response)
{
$('#rpack_add_form').find('.form_result').html(response);
}}
</script>
The PHP/HTML form
<form id="rpack_add_form" class='small_form' name='rpack_form' method='post' onsubmit="return submitForm();">
Contract:
<select id="contract_select" name="contract" onchange="showContract(this)">
<option value='0'>Select Contract</option>
<?php
$sth = $conn->query("SELECT * FROM `contracts`");
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
echo '<option value='.$row['contracts_id'].'>'.$row['contracts_name'].'</option>';
}
?>
</select>
<div id="contract1" class="admin_box">
Prefix: <input name='prefix' type='text' id='prefix'><br />
Number: <input name='number' type='text' id='number'><br />
Suffix: <input name='suffix' type='text' id='suffix'><br />
</div>
<div id="contract2" class="admin_box">
<p>Sapce for 2nd form at a later date</p>
</div>
<div id="contract3" class="admin_box">
<p>Sapce for 3rd form at a later date</p>
</div>
Received:
<select id="select_receive" name="received" onchange="showLocation(this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select><br />
<div id="location_box" style="display: none; padding-top: 5px;">Location: <input name='location' type='text' id='location'></div>
<input class='button' type=submit value='Add Recovery Pack' name='add_rpack'>
</form>
<div class="form_result"> </div>
<a class='hide_div' href='javascript:void(0);' onclick='hideRdiscDiv()'>Close</a>
The PHP for addrpack.php (this code works fully when I remove the ajax part from above and just submit as normal)
<?php
session_start();
include_once 'config.php';
include_once 'connect.php';
$prefix = $_POST['prefix'];
$number = $_POST['number'];
$suffix = $_POST['suffix'];
$contract = $_POST['contract'];
$received = $_POST['received'];
$location = $_POST['location'];
//Check if a number has been entered
if (empty ($number))
{
echo "You need to enter a number";
}else
{
$sth = "INSERT INTO `rpacks` (rpacks_prefix, rpacks_number, rpacks_suffix, rpacks_contract, rpacks_receive, rpacks_location) VALUES (:prefix, :number, :suffix, :contract, :received, :location)";
$q = $conn->prepare($sth);
$q->execute(array(':prefix'=>$prefix,':number'=>$number,':suffix'=>$suffix,':contract'=>$contract, ':received'=>$received, ':location'=>$location));
echo "Added";
}
Probably a syntax error - missing );
$('#rpack_add_form').submit(function(){
$.ajax({
type:'POST',
url: 'addrpack.php',
data:$('#rpack_add_form').serialize(),
success: function(response)
{
$('#rpack_add_form').find('.form_result').html(response);
}
});
return false;
});
$.ajax({
type:'POST',
url: 'addrpack.php',
data:{"data":$('#rpack_add_form').serialize()},
success: function(response)
{
$('#rpack_add_form').find('.form_result').html(response);
}
});//Syntax misatke
Not sure what your onsubmit="return submitForm();" in form does but you have to stop the submit button from sending the data and instead make it use your ajax function.
$(function(){
$('.button').click(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url: 'addrpack.php',
data:$('#rpack_add_form').serialize(),
success: function(response) {
$('#rpack_add_form').find('.form_result').html(response);
}
});
});
});
I am grabbing the values of several input fields with the help of an Ajax/JS function. The issue is that the values of the textbox are not being echoed. I checked with the firebug tool and it shows that the post is performed but there is a blank value. Why is the PHP not echoing the value when the JS function submits it?
EXAMPLE
JS
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>
HTML
<form action="" method="post" enctype="multipart/form-data" id="contact_form" name="form4">
<div class="row">
<div class="label">Contact Name *</div> <!-- end .label -->
<div class="input">
<input type="text" id="contact_name" class="detail" name="contact_name" value="<?php echo isset($_POST['contact_name'])? $_POST['contact_name'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['contact_name']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
<div class="row">
<div class="label">Email Address *</div> <!-- end .label -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['email']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
</form>
You need to use .serialize() on the form probably
Friend first understand the Javascript behaviour.
When you post a form, it becomes one request to the server. At the same time when you send an ajax to server it becomes another separate request to the server
So you should either do form post or ajax.
As you are using ajax here you, in the ajax request you have to pass data separately in data parameter
<script type="text/javascript">
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
data: $('#contact_form').serialize(), // check this line
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>