Ajax query not returning data - php

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/).

Related

AJAX Method not working

I have a form, when i click on submit i dont want the page to refresh, thats why i added AJAX to achieve this as you can see. The problem is that its not working.
<form id="formFooter" action="" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<h3>Background Color</h3>
<input class="form-control" placeholder="(e.g. 00ff00)" type="text" name="backgroundColor">
<h3>Font Color</h3>
<input class="form-control" placeholder="(e.g. 00ff00)" type="text" name="fontColor">
<h3>Opacity</h3>
<input class="form-control" placeholder="(Pick a value between 0 and 1 e.g. 0.3)" type="text" name="opacity">
<br/>
<br/>
<button class="form-control" id="run" type="submit" name="submit">Generate footer</button>
</form>
<div id="showData"> </div>
<script type="text/javascript">
$('#run').on("click", function (e) {
var formData = new FormData($('#myForm')[0]);
$.ajax({
url: "script.php",
type: 'POST',
data: formData,
success: function (data) {
$('#showData').html(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
Here is the script.php:
<?php
function footerPreview ()
{
echo "<h3>Preview:</h3>";
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
//style
$backgroundColor = $_POST['backgroundColor'];
$fontColor = $_POST['fontColor'];
$opacity = $_POST['opacity'];
echo "<div id='generated_footer_date' style='background-color:$backgroundColor; color:$fontColor; opacity: $opacity; ' >$trademark $date $company </div>";
}
// generate result for the head
function rawHead()
{
$head = htmlspecialchars('<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Raleway:200" rel="stylesheet">
</head>',ENT_QUOTES);
echo "<pre><h4>Put this code inside your head tags</h4>$head</pre>";
}
// generate result for the body
function rawBody ()
{
$body1of5 = htmlspecialchars('<div id="footer_date">',ENT_QUOTES);
$body2of5 = $_POST["trademark"];
$body3of5 = date("Y");
$body4of5 = $_POST["companyName"];
$body5of5 = htmlspecialchars('</div>',ENT_QUOTES);
echo "<pre><h4>Put this code inside your body tags</h4>$body1of5 $body2of5 $body3of5 $body4of5 $body5of5 </pre>";
}
// generate result for the CSS
function rawCSS ()
{
$opacity = $_POST['opacity'];
$backgroundColor = $_POST['backgroundColor'];
$fontColor = $_POST['fontColor'];
echo
"<pre>
<h4>Put this code in your websites stylesheet</h4>
color:$fontColor;
background-color:$backgroundColor;
opacity:$opacity;
width:100%;
text-align:center;
padding-top:15px;
height:50px;
font-family: 'Raleway', sans-serif;
right: 0;
bottom: 0;
left: 0;
position:fixed;
</pre>";
}
// Generate eveything by one click
if(isset($_POST['submit']))
{
footerPreview();
rawHead();
rawBody();
rawCSS();
}
?>
When i click on submit nothing happens. I want the script.php to be generate on the same page without refreshing.
You can make it very simple your Ajax Request as:
First of all no need to use FormDate here, because you don't have any file input in your <form>, so you can use serialize() data in your request as:
var formData = $("#myForm").serialize();
Second, you are just printing the HTML in your PHP, it means you just need to print html, so you can use dataType=HTML here as:
dataType: "html",
Third, one more thing will help you in debugging, add print_r($_POST) in your script.php file at top and check the console.
Modified Request:
$(document).ready(function(){
$("#run").click(function(){
var formData = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "script.php",
data: formData,
dataType: "html",
success: function(response)
{
$('#showData').html(response);
},
beforeSend: function()
{
//any loader
}
});
return false;
});
});
Update:
From your comment: yeah it shows after submit. It shows this : Array
( [trademark] => [companyName] => [backgroundColor] => [fontColor] =>
[opacity] => ) – Kevin Aartsen 6 mins ago
Look at this array, you don't have submit in the result of $_POST so you have two options to change this:
1) You can use count() function for checking if(count($_POST) > 0).
2) Or you can use <input type='submit' name='submit'> instead of <button type='submit' name='submit'>
$(document).ready(function() {
$('#run').on("click", function (e) {
e.preventDefault();
alert('inside ajax call');
var formData = new FormData($('#myForm')[0]);
$.ajax({
url: "script.php",
type: 'POST',
data: formData,
success: function (data) {
$('#showData').html(data);
alert('ajax call success');
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form id="formFooter" action="" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<h3>Background Color</h3>
<input class="form-control" placeholder="(e.g. 00ff00)" type="text" name="backgroundColor">
<h3>Font Color</h3>
<input class="form-control" placeholder="(e.g. 00ff00)" type="text" name="fontColor">
<h3>Opacity</h3>
<input class="form-control" placeholder="(Pick a value between 0 and 1 e.g. 0.3)" type="text" name="opacity">
<br/>
<br/>
<button class="form-control" id="run" type="submit" name="submit">Generate footer</button>
</form>
<div id="showData"> </div>
try above code and remove alert when it works for you :)

Print success notice in their own div depending on the form that I sent

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>

execute jquery .submit AFTER ajax success return new form

I believe my problem has something to do with the fact that my first form RETURNS a new form via ajax success .html(result) AFTER DOM has executed. My jquery within DOM isn't being recognized because elements aren't visible until after the submit of first form. HOW to get my $("#fullFormMA").on(submit,(function(e){ to execute is eluding me. Here is my html
<?php
session_start();
require_once('functions.php');
include('header.htm');?>
<title>Membership Application</title>
<meta name="description" content="">
</head>
<body>
<div id="container">
<div id="loginBanner">
<?php include ("loginMenu.php"); ?>
<?php include ("bannerIcons.php"); ?>
</div> <!--end loginBanner-->
<div id="header" class="clear">
</div> <!--end header-->
<div id="content"><div class="content">
<div id="colLt">
<?php include('tabContent.php');?>
<?php include('leftSidebar.php');?>
</div>
<div id="colRt"><div class="content">
<h1>New Member Application</h1>
<ul><li>submitting an application</li><li>submitting payment</li></ul><h6>Step #1—the application</h6>Please enter an email which will ultimately be used as your website username. This email will remain as your private email.</p><br><br>
<form method="post" name="checkUserMA" id="checkUserMA">
<label class="clear" style="width:120px">Username/Email<br><span class="small"></span></label>
<input type="text" name="usernameMA" id="usernameMA" class="green" style="width:300px;"/><br><br>
<input type="submit" id="checkUserMA" class="submit" value="Submit" />
</form>
<div class="clear"></div>
<div id="errorMA" style="background:yellow;width:200px;height:100px"></div>
<div id="resultMA"></div>
</div></div>
<div class="clear"></div>
</div></div><!--end content-->
<div id="footer">
<?php include("footer.htm") ?>
<!--<?php include("disclaimer.htm") ?>-->
</div><!--end footer-->
<div class="clear"></div>
</div><!--end container-->
<div class="clear"></div>
</body>
</html>
Here is my jquery:
$(document).ready(function() {
$('#resultMA').hide();
$('#errorMA').hide();
$("#checkUserMA").submit(function(event){
event.preventDefault();
$("#resultMA").html('');
var values = $(this).serialize();
$.ajax({
url: "checkMA.php",
type: "post",
data: values,
success: function(result){
$("#resultMA").html(result).fadeIn();
$('.error').hide();
},
error:function(){
// alert("failure");
$("#resultMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
$("#fullFormMA").on(submit,(function(e){
e.preventDefault();
$("#errorMA").html('');
var values = $(this).serialize();
$.ajax({
url: "validMA.php",
type: "post",
data: values,
success: function(result){
},
error:function(){
// alert("failure");
$("#errorMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
});//end dom
Here is checkMA.php...
<?php
session_start();
include('functions.php');
connect();
$username = urldecode(protect($_POST['usernameMA']));
$_SESSION['guestUser'] = $username;
$sql2 = mysql_query("SELECT username FROM members WHERE username = '$username'");
$checkNumRows = mysql_num_rows($sql2);
if (!$username){
echo "<p class='red'>Enter an email to be used as your username...</p>";
} else if ($checkNumRows == 1){
echo "<span style='font-weight:bold'>The username: ".$username." is already in use.</span>";
} else if ($checkNumRows == 0){
echo "<hr><p class='green'>This username is available.</p><p>Please continue with the registration process...</p><br>";?>
<form method="post" name="fullFormMA" action="memberAppProcess.php">
<h6>Public Information - this information will be displayed to website visitors</h6>
<label class="clear" style="width:75px">Name</label>
<label class="error" id="name_error">This field is required.</label>
<input type="text" name="firstName" id="firstName" class="left inputCheck" style="width:150px" placeholder="first name"/>
<input type="text" name="lastName" id="lastName" class="inputCheck" style="margin-left:10px" placeholder="last name"/><br><br>
<input type="submit" name="fullFormMA" id="fullFormMA" class='submit right' onClick='submitFullForm();' value="Submit application">
</form>
<?php
}?>
My #checkUserMA works but my #fullFormMA doesn't work. I would love to understand why (DOM already loaded?) and how I might fix my code to allow for a form added "after the fact" via ajax .html(result). Thank you.
The DOM is ready before your ajax success so you can write this JQuery full code
$(document).ready(function() {
$('#resultMA').hide();
$('#errorMA').hide();
$("#checkUserMA").submit(function(event){
event.preventDefault();
$("#resultMA").html('');
var values = $(this).serialize();
$.ajax({
url: "checkMA.php",
type: "post",
data: values,
success: function(result){
$("#resultMA").html(result).fadeIn();
$('.error').hide();
RunAfterAjax();
},
error:function(){
// alert("failure");
$("#resultMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
function RunAfterAjax(){
$("#fullFormMA").on(submit,(function(e){
e.preventDefault();
$("#errorMA").html('');
var values = $(this).serialize();
$.ajax({
url: "validMA.php",
type: "post",
data: values,
success: function(result){
},
error:function(){
// alert("failure");
$("#errorMA").html('There was an error. Please try again.').fadeIn();
}
});//end ajax
});
}
});//end dom
It's executing, you just aren't waiting long enough for it to exist. Move the event binding for the new form to the line right after you add the new form to the document.
$("#resultMA").html(result).fadeIn();
$("#fullFormMA").on(submit,(function(e){...
$("#fullFormMA").on(submit,(function(e){ /* ... */ });
fullFormMA is an <input>, you should bind click instead of submit, and use quotes around the event name.
When you use $('#something').on('event', ...), it only works if the #something element already exists.
You could fix your code by delegating the listener to an upper existing element :
$('#content').on('click', '#fullFormMA', function() { /* ... */ });
This code will detect the click event on #fullFormMA event if it is added after an ajax response.

hide div after inserting data in database

Hi would you like to help me. im a php newbie. I want to insert employment information in my database and hide da div where the form placed.
HTML:
<div class="toggler">
<div id="effect" class="ui-widget-content ui-corner-all">
<form name="empform" method="post" action="profile.php" autofocus>
<input name="employ" type="text" id="employ" pattern="[A-Za-z ]{3,20}"
placeholder="Who is your employer?">
<input name="position" type="text" id="position" pattern="[A-Za-z ]{3,20}"
placeholder="What is your job description?">
<input name="empadd" type="text" id="empadd" pattern="[A-Za-z0-9##$% ]{5,30}"
placeholder="Where is your work address?">
<input name="empcont" type="text" id="empcont" pattern="[0-9]{11}" title="11-digit number"
placeholder="Contact number">
<input name="btncancel" type="button" class="btncancel" value="Cancel"
style="width:60px; border-radius:3px; float:right">
<input name="btndone" type="submit" class="btndone" value="Done" style="width:60px; border-radius:3px; float:right">
</form>
</div>
</div>
PHP:
if (isset($_POST['btndone'])) {
$employ = $_POST['employ'];
$position = $_POST['position'];
$empadd = $_POST['empadd'];
$empcont = $_POST['empcont'];
$empdate = $_POST['empdate'];
$empID = $alumniID;
$obj - > addEmployment($employ, $position, $empadd, $empcont, $empdate, $empID);
}
JS:
<script>
$(function () {
function runEffect() {
var selectedEffect = "highlight";
$(".toggler").show(selectedEffect);
};
function runDisplay() {
var selectedDisplay = "highlight";
$("#empdisplay").show(selectedDisplay);
};
$(".btncancel").click(function () {
$(".toggler").hide();
return false;
});
$(".btndone").click(function () {
runDisplay();
$(".toggler").hide();
return false;
});
}
</script>
Hi this is what I'll do
var request = $.ajax({
url: "profile.php",
type: "POST",
data: $('#form').serialize()
});
request.done(function(msg) {
$('#form').hide();
});
request.fail(function(jqXHR, textStatus) {
alert( "Form failed" );
});
If you have some doubts with Jquery's Ajax visit this link
If you don't understand what jqXHR is, I suggest you visit this link http://www.jquery4u.com/javascript/jqxhr-object/
Execute on click
$('#form').submit(function(){
var request = $.ajax({
url: "profile.php",
type: "POST",
data: $('#form').serialize()
});
request.done(function(msg) {
$('#form').hide();
});
request.fail(function(jqXHR, textStatus) {
alert( "Form failed" );
});
});
Try This
HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<div class="toggler">
<div id="effect" class="ui-widget-content ui-corner-all">
<form id="empform" name="empform" method="post" action="profile.php" autofocus>
<input name="employ" type="text" id="employ" pattern="[A-Za-z ]{3,20}"
placeholder="Who is your employer?">
<input name="position" type="text" id="position" pattern="[A-Za-z ]{3,20}"
placeholder="What is your job description?">
<input name="empadd" type="text" id="empadd" pattern="[A-Za-z0-9##$% ]{5,30}"
placeholder="Where is your work address?">
<input name="empcont" type="text" id="empcont" pattern="[0-9]{11}" title="11-digit number"
placeholder="Contact number">
<input name="btncancel" type="button" class="btncancel" value="Cancel"
style="width:60px; border-radius:3px; float:right">
<input id="submit"name="btndone" type="submit" class="btndone" value="Done" style="width:60px; border-radius:3px; float:right">
</form>
</div>
</div>
<script>
$(document).ready(function() {
//$("#form").prev
$('#submit').click(function(event) {
//alert (dataString);return false;
event.preventDefault();
$.ajax({
type: "POST",
url: 'profile.php',
dataType:"html",
data: $("#empform").serialize(),
success: function(msg) {
alert("Form Submitted: " + msg);
//alert($('#form').serialize());
$('div.toggler').hide();
}
});
});
});
</script>
</html>
PHP
profile.php
<?php
if (isset($_POST)) {
$employ = $_POST['employ'];
$position = $_POST['position'];
$empadd = $_POST['empadd'];
$empcont = $_POST['empcont'];
$empdate = $_POST['empdate'];
$empID = $alumniID;
$obj - > addEmployment($employ, $position, $empadd, $empcont, $empdate, $empID);
}
?>
Iam not sure about your fields
echo $empdate = $_POST['empdate'];
$empID = $alumniID;
they are not in form but works!...
You should do an ajax call to save your data and then hide the div, someting like this :
$('form[name="empform"]').submit(function(e) {
e.preventDefault();
$.post($(this).attr('action'), $(this).serialize(), function(data) {
$('div.toggler').hide();
});
});

Jquery - How to populate form fields in a modal form from a dynamic list in another modal?

Okay, I'll try to be as clear as I can with this.
I have a page with a team's roster that you can add and delete from. When you decide to add a player, you click the "Add Player" button which, using Jquery-UI, loads a dialog modal with a form. You can fill in the form and submit and it works great. I've also added a "Search" button that, when clicked, loads another modal that lets you search a DB of exists players. When it retrieves search results it loads them in an OL. Now this is where it gets tricky:
I would like to have a button called "Use player info" that, when clicked, closes the search modal and auto-fills the the form fields with the selected player's information.
Here is the code for the search modal:
Script (in the head):
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word==''){
} else {
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
HTML
<div id="search" align="center">
<div style="width:500px">
<div style="text-align:center; padding-top:10px" class="title">Player Search</div>
<div style="margin-top:20px; text-align:left">
<form method="get" action="">
<div style="margin:0; padding:0; float:left">
<input type="text" name="search" id="search_box" class='search_box'/>
</div>
<div style="margin:0; padding:0; float:left; padding-left:8px; font-size:16px">
<input type="submit" value="Search" class="search_button" />
</div>
</form>
</div>
<div style="width:480px; padding-left:10px; padding-right:10px;">
<div id="flash"></div>
<ol id="insert_search" class="update"> </ol>
</div>
</div>
</div>
Here is the php code for the actual search function:
<li><div id="all">
<div id="result"><div id="names"><div id="lnames"><?php echo $final_msg; ?></div><div id="fnames"> <?php echo $firstName ?></div></div><div id="dobs"><?php echo $DOB ?></div><div id="ids"><?php echo $ID ?></div>
<div id="add"><button type="button" id="add_player2" > Add Player </button></div></div>
</div></li>
And here is the code for the form modal I want he information to be put in:
<script>
$(function() {
$( "#search" ).dialog({
autoOpen: false,
width: 550,
modal: true,
resizable: false,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word=='')
{
}
else
{
$.ajax({
type: "GET",
url: "../../Search/searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
<script>
$(function() {
$("#dialog-form").dialog({autoOpen:!1, height:380, width:350, modal:!0, buttons:{
"Search for Player":function() {
$( "#search" ).dialog( "open" );
},
"Add Player":function() {
$("#myForm").ajaxSubmit({success:function() {
window.location = ""
}});
$(this).dialog("close")
},
Cancel:function() {
$(this).dialog("close")
}
},
create:function () {
$(this).closest(".ui-dialog")
.find(".ui-button:contains(Search for Player)") // the first button
.addClass("green");
}});
$("#add-player").button().click(function() {
$("#dialog-form").dialog("open")
})
});
</script>
<div id="dialog-form" title="Add Player">
<form name="myForm" id="myForm" action="../../php/add_player_comp_script_test.php?id=<? echo $table ?>" method="post" enctype="multipart/form-data">
<fieldset>
<label for="last_name_add">Last Name</label>
<input type="text" name="last_name_add" id="last_name_add" class="text ui-widget-content ui-corner-all" />
<label for="first_name_add">First Name</label>
<input type="text" name="first_name_add" id="first_name_add" class="text ui-widget-content ui-corner-all" />
<label for="id_add">ID Number</label>
<input type="text" name="id_add" id="id_add" value="" class="text ui-widget-content ui-corner-all" />
<label for="jersey_add">Jersey Number</label>
<input type="text" name="jersey_add" id="jersey_add" value="" class="text ui-widget-content ui-corner-all" />
<label for="dob_add">DOB (YYYY-MM-DD)</label>
<input type="text" name="dob_add" id="dob_add" value="" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
Thanks for any and all help!
I am assuming that this-
<li><div id="all">
<div id="result"><div id="names"><div id="lnames"><?php echo $final_msg; ?></div><div id="fnames"> <?php echo $firstName ?></div></div><div id="dobs"><?php echo $DOB ?></div><div id="ids"><?php echo $ID ?></div>
<div id="add"><button type="button" id="add_player2" > Add Player </button></div></div>
</div></li>
is the html in this success function-
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
If so, it would be better if you returned a json encoded array json_encode(), instead of html - eg.
[{"lname":"Jones","fname":"Joe","dob":"2000-01-13","id":"6"},
{"lname":"Jones","fname":"Jim","dob":"2001-04-04","id":"19"},
{"lname":"Jones","fname":"Bob","dob":"1999-10-23","id":"32"}]
php code on ../../Search/searchdata.php would be something like -
while($row = _fetched_array_) {
$players[] = array(
'lname' => $row['lname'],
'fname' => $row['fname'],
'dob' => $row['dob'],
'id' => $row['id']
);
}
// Return JSON Encoded Array
echo json_encode($players);
Then you can create links for each one, and on selecting the player it will add it to your form fields
success: function(html){
players = $.parseJSON(html); //create json array in format above
player_links = ''; // create blank variable
for (var i = 0; i < players.length; i++){ // loop through each of the returned players
// Echo Player First & Last Name and a link to add
player_links += '<li>' + players[i].lname + ' ' + players[i].fname + ' Add Player</li>';
}
$("#insert_search").show();
$("#insert_search").append(player_links);
$("#flash").hide();
// Bind .player_details click
$('.player_details').click(function () {
var pid = $(this).data('player');
$('#last_name_add').val(players[pid].lname);
$('#first_name_add').val(players[pid].fname);
$('#id_add').val(players[pid].id);
$('#dob_add').val(players[pid].dob);
$("#search").dialog("close");
});
}
I have created a simple example of this as a jsFiddle - http://jsfiddle.net/8jcLQ/

Categories