hide div after inserting data in database - php

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

Related

how can I get the result from second code?

I have modified my question. How can I get the result from second form? because I have create two form with similar code, however I can only get the result from the first form and when I press the second one, it still get the result from first form. Can someone help me out?
Code
<div>
<form id="fupForm" name="form1" method="post">
<div class="form-group">
<input type="hidden" class="form-control" id="gp_name" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control" id="date" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control" id="type" name="type"
value="Hotel">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Hotel" id="butsave">
</form></div>
<div>
<form id="fupForm2" name="form2" method="post">
<div class="form-group">
<input type="hidden" class="form-control" id="gp_name" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control" id="date" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control" id="type" name="type"
value="Coach">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Coach" id="butsave2">
</form></div>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
$("#butsave").attr("disabled", "disabled");
var gp_name = $('#gp_name').val();
var date = $('#date').val();
var type = $('#type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
<script>
$(document).ready(function() {
$('#butsave2').on('click', function() {
$("#butsave2").attr("disabled", "disabled");
var gp_name = $('#gp_name').val();
var date = $('#date').val();
var type = $('#type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave2").removeAttr("disabled");
$('#fupForm2').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
I have try to find on the Google, but can't find the solution for my case.
Add form id before the input element.
Remember ids are always unique and can not be duplicate. So here I change id to class. Please check below code.
<div>
<form id="fupForm" name="form1" method="post">
<div class="form-group">
<input type="hidden" class="form-control gp_name" id="" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control date" id="" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control type" id="" name="type"
value="Hotel">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Hotel" id="butsave">
</form></div>
<div>
<form id="fupForm2" name="form2" method="post">
<div class="form-group">
<input type="hidden" class="form-control gp_name" id="" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control date" id="" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control type" id="" name="type"
value="Coach">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Coach" id="butsave2">
</form></div>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
$("#butsave").attr("disabled", "disabled");
var gp_name = $('#fupForm .gp_name').val();
var date = $('#fupForm .date').val();
var type = $('#fupForm .type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
<script>
$(document).ready(function() {
$('#butsave2').on('click', function() {
$("#butsave2").attr("disabled", "disabled");
var gp_name = $('#fupForm2 .gp_name').val();
var date = $('#fupForm2 .date').val();
var type = $('#fupForm2 .type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave2").removeAttr("disabled");
$('#fupForm2').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
An id must be unique in a document. Use a validator.
You get the same data each time, because you are searching using an id selector and error recovery means that you will always get the first one.
Don't use IDs
Do use selectors relative to the form you are dealing with
For example:
$("form").on("submit", function(event) {
event.preventDefault();
const $form = $(this);
const $input = $form.find("[name=type]");
console.log($input.val());
});
form {
padding: 1em
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type=hidden name=type value=foo>
<button>Submit</button>
</form>
<form>
<input type=hidden name=type value=bar>
<button>Submit</button>
</form>
The function $( document ).ready( function() {} ) and $( function() {} ) are equal. This will overwrite the previous variant. If you merge the code, it should work.

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 :)

How to send data with ajax when pressing enter [duplicate]

This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 7 years ago.
form.php
<form action="#" method="POST" enctype="multipart/form-data" style="textalign: center;">
<label class="label" for="Fromdate">From Date</label>
<input type="text" id="datepicker" class="textBox" name="fromDate" />
<label class="label" for="Todate">To Date</label>
<input type="text" id="datepicker1" class="textBox" name="toDate" />
<input type="submit" name="searchby" id="searchby" value="Search" class="buttonLarge" />
<input type="submit" name="excel" value="Export To Excel" class="buttonLarge" />
</form>
datediff.php
<?php
if(($_POST['searchby'] == 'Search')){
?>
<script type="text/javascript">
var fromDate = $("#datepicker").val();
var toDate = $("#datepicker1").val();
$.ajax({
type: "POST",
url: "datediff.php",
data: { fromDate,toDate },
cache: false,
success: function (html) {
}
});
</script>
<?php
}
?>
Wrong json { fromDate,toDate }.
And yes it will submit if we press enter. For submitting it through ajax we have to prevent default functionality through event.preventDefault().
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
search();
}
});
$('#searchby').click(function(e){
e.preventDefault();
search();
});
function search()
{
$.ajax({
type: "POST",
url: "datediff.php",
data: { 'fromDate':$('#datepicker').val(), 'toDate':$('#datepicker1').val() },
cache: false,
success: function (html) {
}
});
}

How to send textfield with jquery.post, php+mysql without form?

How to send textfield with jquery.post (ajax) from php without form?
I need send text field using jquery.post . I have this code:
HTML:
<div id="form1" class="enviar"> <p>
URL:
<input type="text" name="url" id="url" />
<p> JSON:
<textarea name="json" id="json" cols="45" rows="5"></textarea>
</p>
<p>
<input type="submit" name="send" value="send" />
</p>
</div>
JQUERY:
$(function(){
$("#send") .submit(function(){
var json = $("#json") .val();
var url = $("#url") .val();
var s = {
"json":json
}
var u = {
"url":url
}
$.ajax({
url:u,
type:'post',
data:s,
beforeSend: function (){
$(".status") .html(" alt=\"Loading ....\" />");
},
success:function(data){
$(".status").html(data);
}
});
});
})
PHP:
include ('conection.php');
$arr = json_decode($_POST['json'],true);
if ($_POST['json']>NULL){
mysql_query("INSERT INTO liciteiro.clientes(client_id,client_descricao,client_razaosocial,client_endereco,client_cidade,client_estado,client_telefone) VALUES ('".$arr[0]['client_id']."','".$arr[0]['client_descricao']."','".$arr[0]['client_razaosocial']."','".$arr[0]['client_endereco']."','".$arr[0]['client_cidade']."','".$arr[0]['client_estado']."','".$arr[0]['client_telefone']."')")or die(mysql_error());
}
else {
die(mysql_error());
}
But this code doesn't send anything.
Try this it will send data after click on send button
Html
<div id="form1" class="enviar">
<p>URL:<input type="text" name="url" id="url" /></p>
<p> JSON:<textarea name="json" id="json" cols="45" rows="5"></textarea></p>
<p><input type="submit" name="send" value="send" id="send" /></p>
</div>
Jquery
$(function(){
$("#send").click(function(){
var json = $("#json") .val();
var url = $("#url") .val();
$.ajax({
url:url,
type:'post',
data:{json: json},
beforeSend: function (){
$(".status") .html(" alt=\"Loading ....\" />");
},
success:function(data){
$(".status").html(data);
}
});
});
});
jQuery:
$('#mybutton').on("click",function(){
var url = $('#url').val()
$.post(url,
{text:$('#json').val(), url:url },
function(data){
alert("it works");
})
})
HTML:
<textarea name="json" id="json" cols="45" rows="5"> </textarea>
<input type="button" id="mybutton" />
You could add id to you button and use
$("#my-button-id").click
Or you can try this
$(function(){
$('#form1 input[type="submit"]').click(function(e){
e.preventDefault();
var json = $("#json") .val();
var url = $("#url") .val();
$.ajax({
url:url,
type:'post',
data:{json: json},
beforeSend: function (){
$(".status") .html(" alt=\"Loading ....\" />");
},
success:function(data){
$(".status").html(data);
}
});
});
});
But you must notice that you can't make ajax queries to other domains, without allow-origin headers.

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