I have a php generated form with multiple input fields the number of which is determined by user select. I would like to use an ajax function to enter all the data to database. The problem is that I am new to ajax and not sure ho to go about it. The ajax javascript function below is a sample of what I would like to achieve and I know it is not correct. Can someone point me in the right direction. I have looked around and from what I see, Json may be a solution but I know nothing about it and reading up on it I still don't get it.
sample ajax:
function MyFunction(){
var i = 1;
var x = $('#num_to_enter').val();
while (i <= x){
var name = $('#fname[i]').val();
var lname = $('#lname[i]').val();
var email = $('#Email[i]').val();
i++;
}
$('#SuccessDiv').html('Entering Info.<img src="images/processing.gif" />');
$.ajax({url : 'process.php',
type:"POST",
while (i <= x){
data: "fname[i]=" + name[i] + "&lname[i]=" + lname[i] + "&email[i]=" + email[i],
i++;
}
success : function(data){
window.setTimeout(function()
{
$('#SuccessDiv').html('Info Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
return false;
}
A sample of form :
<?php
echo "<form method='post'>";
$i=1;
while($i <= $num_to_enter){
$form_output .= "First Name:
<input id='fname' type='text' name='fname[$i]'><br />
Last Name:
<input id='lname' type='text' name='lname[$i]'><br />
Email:
<input id='Email' type='text' name='Email[$i]'><br />
$i++;
}
echo"<input type='button' value='SUBMIT' onClick='MyFunction()'></form>";
?>
Then DB MySQL Sample
<?php
while ($i <= $x){
$x = $_POST['num_to_enter'];
$fname = $_POST['fname[$i]'];
$fname = $_POST['fname[$i]'];
$fname = $_POST['email[$i]'];
$sql = "INSERT INTO `mytable`
(`firstname`, `lastname`, `email`) VALUES ('$fname[$i]', '$lname[$i]', '$email[$i]');";
$i++;
}
?>
Here is a simple demo of AJAX:
HTML
<form method="POST" action="process.php" id="my_form">
<input type="text" name="firstname[]">
<input type="text" name="firstname[]">
<input type="text" name="firstname[]">
<input type="text" name="firstname[custom1]">
<input type="text" name="firstname[custom2]">
<br><br>
<input type="submit" value="Submit">
</form>
jQuery
// listen for user to SUBMIT the form
$(document).on('submit', '#my_form', function(e){
// do not allow native browser submit process to proceed
e.preventDefault();
// AJAX yay!
$.ajax({
url: $(this).attr('action') // <- find process.php from action attribute
,async: true // <- don't hold things up
,cache: false // <- don't let cache issues haunt you
,type: $(this).attr('method') // <- find POST from method attribute
,data: $(this).serialize() // <- create the object to be POSTed to process.php
,dataType: 'json' // <- we expect JSON from the PHP file
,success: function(data){
// Server responded with a 200 code
// data is a JSON object so treat it as such
// un-comment below for debuggin goodness
// console.log(data);
if(data.success == 'yes'){
alert('yay!');
}
else{
alert('insert failed!');
}
}
,error: function(){
// There was an error such as the server returning a 404 or 500
// or maybe the URL is not reachable
}
,complete: function(){
// Always perform this action after success() and error()
// have been called
}
});
});
PHP process.php
<?php
/**************************************************/
/* Uncommenting in here will break the AJAX call */
/* Don't use AJAX and just submit the form normally to see this in action */
// see all your POST data
// echo '<pre>'.print_r($_POST, true).'</pre>';
// see the first names only
// echo $_POST['firstname'][0];
// echo $_POST['firstname'][1];
// echo $_POST['firstname'][2];
// echo $_POST['firstname']['custom1'];
// echo $_POST['firstname']['custom2'];
/**************************************************/
// some logic for sql insert, you can do this part
if($sql_logic == 'success'){
// give JSON back to AJAX call
echo json_encode(array('success'=>'yes'));
}
else{
// give JSON back to AJAX call
echo json_encode(array('success'=>'no'));
}
?>
var postdata={};
postdata['num']=x;
while (i <= x){
postdata['fname'+i]= name[i];
postdata['lname'+i]= lname[i];
postdata['email'+i]= email[i];
i++;
}
$.ajax({url : 'process.php',
type:"POST",
data:postdata,
success : function(data){
window.setTimeout(function()
{
$('#SuccessDiv').html('Info Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
PHP
$num=$_POST['num'];
for($i=1;i<=$num;i++)
{
echo $_POST['fname'.$i];
echo $_POST['lname'.$i];
echo $_POST['email'.$i];
}
Related
I am new to JQUERY and I am trying to search for the something and based on the searched text I am doing an ajax call which will call php function and the PHP is returning me with JSON data.
I want to display the returned data in the Datatable form.
I have my PHP file table.php and JavaScript file jss.js and my main.php.
The PHP file is returning the JSON data and I able to use alert to display it.
I want to know how can I display it in datatable.
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off"/>
<button id="search" name="submit">Search</button>
</div>
my ajax/jss.js file
$(document).ready(function(){
$('#search').click(function(){
var search_query = $('#search_query').val();
if(search_query !='')
{
$.ajax({
url:"table.php",
method:"POST",
data:{search_query:search_query},
success: function(data)
{
alert("HEKKI "+data);
}
});
}
else
{
alert("Please Search again");
}
});
});
my table.php file
<?php
$data=array();
$dbc = mysqli_connect('localhost','root','','acdc') OR die('Could not connect because: '.mysqli_connect_error());
if (isset($_REQUEST['search_query']))
{
$name = $_REQUEST['search_query'];
}
if($dbc)
{
if (!empty($name))
{
$sql = "select c.res1 res1,
cc.res2 res2,
cc.res3 res3,
cc.res4 res4,
cc.res5 res5
from table1 c
inner join table2 cc
on c.id = cc.id
where c.name like '".$name."%'
and cc.ENABLED = 1";
$res = mysqli_query($dbc,$sql);
if(!(mysqli_num_rows($res)==0))
{
while($row=mysqli_fetch_array($res))
{
$data['RES1'] = $row['res1'];
$data['RES2'] = $row['res2'];
$data['RES3'] = $row['res3'];
$data['RES4'] = $row['res4'];
$data['RES5'] = $row['res5'];
}
}
else
{
echo "<div style='display: block; color:red; text-align:center'><br/> Not Found,Please try again!!!</div>";
}
}
}
echo json_encode($data);
/*
*/
?>
Can you please guide me how to display the result in main page.
Setting utf8 as charset is probably a good idea. If you have different charset in your table you will get a JSON error :
mysqli_set_charset($dbc, 'utf8');
Then use mysqli_fetch_assoc instead of mysqli_fetch_array. You want field: value records turned into JSON :
$data = array();
while($row=mysqli_fetch_assoc($res)) {
$data[] = $row;
}
Output the JSON :
echo json_encode( array('data' => $data) );
Now you can use it directly along with dataTables :
<table id="example"></table>
$('#example').DataTable({
ajax: {
url: 'table.php'
},
columns: [
{ data: 'res1', title: 'res1'},
{ data: 'res2', title: 'res2'},
//etc..
]
})
one approach is to create the form fulfiled with data just in table.php file and with support of jQuery you will need to populate the <form id="form_id"> with ajax result $('#form_id').html(ajax_response);
other aproach:
to use jQuery json data to populate every field separately.
var jsonData = JSON.parse( ajax_response ); // decode json
than
$('#id_input_1').val(jsonData.RES1);
$('#id_input_2').val(jsonData.RES2);
$('#id_input_3').val(jsonData.RES3);
Place a placeholder in this case I used #results, and dynamically create a table and append it to the placeholder. I commented out your ajax for this example, but just call the function I created to process the results from within the success callback and pass the new function a javascript object.
$(document).ready(function() {
$('#search').click(function() {
var search_query = $('#search_query').val();
if (search_query != '') {
//$.ajax({
// url: "table.php",
// method: "POST",
// data: {
// search_query: search_query
// },
// success: function(data) {
// alert("HEKKI " + data);
// }
//});
processResults({RES1: "result1", RES2: "result2"});
} else {
alert("Please Search again");
}
});
});
function processResults(obj){
var $tbl = $("<table>");
var $row = $("<tr>");
var trow;
$.each(obj, function(idx, elem){
trow = $row.clone();
trow.append($("<td>" + obj[idx] + "</td>"));
$tbl.append(trow);
});
$("#results").append($tbl);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" name="search_query" id="search_query" placeholder="Search Client" size="50" autocomplete="off" />
<button id="search" name="submit">Search</button>
<div id='results'></div>
</div>
I would like some help with ajax. I would like to update a php file which will update a database. I have a form which send the selected check box to a php file which then updates the data base. I would like to do this with ajax but I am struggling with this. I know how to update <div> Html elements by ajax but cannot work this out.
HTML script
<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<form name="form">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
var boiler = document.getElementByName("boiler").value;
var niamh = document.getElementByName("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'boiler=' + boiler + 'niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: dataString,
cache: false,
success: function() {
alert("ok");
}
});
}
</script>
</body>
</html>
PHP updateDB.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="14Odiham"; // Mysql password
$db_name="heating"; // Database name
$tbl_name = "test";
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;
// Insert data into mysql
$sql = "UPDATE $tbl_name SET boiler=$boiler WHERE id=1";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
?>
<?php
//close connection
mysql_close();
header ('location: /ajax.php');
?>
I would like this to update with out refreshing the page.
I just want some suggestion and first your html page code should like-
<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<form name="form" id="form_id">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
// it's like cumbersome while form becoming larger so comment following three lines
// var boiler = document.getElementByName("boiler").value;
// var niamh = document.getElementByName("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
//var dataString = 'boiler=' + boiler + 'niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
// instead of type use method
method: "POST",
url: "updateDB.php",
// instead dataString i just serialize the form like below this serialize function bind all data into a string so no need to worry about url endcoding
data: $('#form_id').serialize(),
cache: false,
success: function(responseText) {
// you can see the result here
console.log(responseText)
alert("ok");
}
});
}
</script>
</body>
</html>
Now i am turning to php code:
You used two line of code right in php
$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;
$_GET is used in get method and $_POST for post method, thus you are using post method in ajax and above line of code should be like
$boiler = (isset($_POST['boiler'])) ? 1 : 0;
$niamh = (isset($_POST['niamh'])) ? 1 : 0;
Update:
As well as fixing the dataString, stop the form from being submitted so that your function is used:
<form name="form" onsubmit="return false;">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
The ajax call should handle returned data from updateDb.php.
Update the php file to send data back to the server, revert to $_POST instead of $_GET and remove the header call at the bottom:
if($result){
$data['success'=>true, 'result'=>$result];
} else {
$data['success'=>false];
}
echo json_encode($data);
// die(); // nothing needed after that
Update the ajax call to handle the response and fix your dataString with '&' between params (This is why you are not getting your params properly).
var dataString = 'boiler=' + boiler + '&niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: dataString,
cache: false,
success: function(data) {
var json = $.parseJSON(data);
if(json.success){
// update the page elements and do something with data.results
var results = data.results;
} else {
// alert("some error message")'
}
}
});
}
document.getElementByName not a javascript function, try document.getElementById() instead
You can do this
<form name="form" onsubmit="myfunction()">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<input type="submit" value="Update"/>
</form>
Javascript:
function myFunction() {
var boiler = document.getElementById("boiler").value;
var niamh = document.getElementById("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
// i dont practice using url string in ajax data as it can be compromised with a quote (') string, instead i am using json
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: {
boiler: boiler,
niamh: niamh
},
cache: false,
}).done(function() {
alert('success');
}); // i do this because some jquery versions will deprecate the use of success callback
}
And you are getting to a post so change the $_GET in you php file to $_POST
I am trying to send form variables to PHP via AJAX and show the result in console.log. But the console shows always no value for data. I donĀ“t know what's wrong. What I have so far:
Part of jQuery Code:
...
init: function() {
this.on('success', function(csvFile, json) {
// AJAX
$.ajax({
url : "tests.php",
type : "POST",
data : this.csvFile
}).done(function (data) {
// Bei Erfolg
console.log("Erfolgreich:" + data);
}).fail(function() {
// Bei Fehler
console.log("Fehler!");
}).always(function() {
// Immer
console.log("Beendet!");
});
});
Part of HTML Code:
<form action="tests.php" class="dropzone" id="myAwesomeDropzone">
<input type="text" name="testname" value="das bin ich"/>
</form>
PHP Code:
if(!empty($_FILES)){
$test = $_FILES['file']['tmp_name'];
echo test;
}
if(!empty($_POST)){
$test2 = $_POST['testname'];
echo $test2;
}
Your HTML code and PHP works fine (just need to fix "echo test" to "echo $test" in your tests.php). Dropzone automatically attach itself to anything with class "dropzone" and it will do ajax requests to your server after you select a file.
If you want to programmatically:
HTML
<div id="myDZ">
Drop your file
<input type="text" id="testname" name="testname" value="hello_world"/>
<button id="upload">upload</button>
</div>
jQuery:
<script type="text/javascript">
$("#upload").click(function(e){
myDZ.processQueue();
})
var myDZ = new Dropzone("#myDZ", {
url: "tests.php",
autoProcessQueue: false,
init: function(){
this.on('sending', function(xhr, fd1, fd2){
//append extra data here
fd2.append("testname", $("#testname").val());
});
this.on('success', function(file, responseText){
//do after successful upload
console.log(responseText);
})
}
});
</script>
you can remove "autoProcessQueue: false" and remove the button stuff if you want it to auto upload once a file is selected.
more events can be found here: http://www.dropzonejs.com/#event-list
I don't know what i did wrong in the ajax call. I want to return the data back to my script and work with it but its not returning result. Here are some things i will like to clarify as well as i am new to ajax programming. if the ajax call is successful and it returns result to the script. Where in the script will the result be. Will i have to create an array that holds the result or ...
Here is the html
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="reserveform">
<div id="response"></div>
<div>
<label>Name</label><input type="text" name="name" id="nameid">
</div>
<div>
<label>Phone Number</label><input type="text" name="phone" id="phoneid">
</div>
<div>
<button type="submit" class="btn" id="btnsubmit">Submit</button>
</div>
</form>
<div id="success"></div>
//my script
$('#btnsubmit').click(function(e){
e.preventDefault();
var nameid = $('#nameid').val();
var phoneid = $('#phoneid').val();
var validate_msg = '';
if (nameid == ''){
validate_msg = '<p> Name is Required. </p>';
}
if (phoneid == '' || ($.isNumeric(phoneid) == false)){
validate_msg += '<p> Phone field is either empty or non numeric. </p>';
}
if (validate_msg != ''){
$('#response').addClass('error').html('<strong>Please correct the errors below </strong>' + validate_msg);
} else {
var formData = $('form #reserveForm').serialize();
submitForm(formData);
}
});
function submitForm(formData){
$.ajax({
type: 'POST',
url: 'reservation.php',
data:formData,
dataType:'json',
success: function(data){
$("#success").html(data);
},
error: function(XMLHttpResponse, textStatus, errorThrown){
$('#success').removeClass().addClass('error').html('<p>There was an ' + errorThrown + ' due to ' + textStatus + 'condition');
}
});
}
If you are trying ajax form submission and need to populate the result in the success div without refresh, you need return false
Don't use
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="reserveform">
Here don't need the action in form, try like
<form id="reserveform" onsubmit="return submitForm();">
In function use form serialize so all input elements value in form will available
function submitForm(){
var formData = $("#reserveform").serialize();
$.ajax({
type: 'POST',
url: 'reservation.php',
data:formData,
dataType:'json',
success: function(data){
$("#success").html(data);
},
error: function(XMLHttpResponse, textStatus, errorThrown){
$('#success').removeClass().addClass('error').html('<p>There was an ' + errorThrown + ' due to ' + textStatus + 'condition');
}
});
return false; // use this otherwise the form will be submitted and results an entire page refresh
}
please try this
you have to put the btnsubmit click event inside onload or document ready
$(document).ready(function()
{
$('#btnsubmit').click(function(e){
e.preventDefault();
var nameid = $('#nameid').val();
var phoneid = $('#phoneid').val();
var validate_msg = '';
if (nameid == ''){
validate_msg = '<p> Name is Required. </p>';
}
if (phoneid == '' || ($.isNumeric(phoneid) == false)){
validate_msg += '<p> Phone field is either empty or non numeric. </p>';
}
if (validate_msg != ''){
$('#response').addClass('error').html('<strong>Please correct the errors below </strong>' + validate_msg);
} else {
var formData = $('form #reserveForm').serialize();
submitForm(formData);
}
});
}
);
You cant use like this $("#success").html(data); because data is in json format. here, the data is an object. You need to parse it and assign to tags.
I see you configured the form to submit to the same document that you are in already. This is fine, we do this all the time.
However, you are also stopping the form from submitting and then using AJAX to submit the values. You specify reservation.php as your ajax processor. Is this the same PHP page you are on already? If so, then I know what the problem is: you can't do that.
By design, AJAX must use an external PHP file to process the AJAX. If you try to do this inside the same document, the AJAX will only echo back the full HTML of the document itself.
Short answer: use an external PHP file. This is by design.
See this other answer for more information about exactly this issue.
See these other posts for further info about AJAX and getting info into the PHP processing script, and returning info back from the PHP processing script:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
I have a couple of scripts i have written below that work great seperately, but together they don't work as they should. Let me post the code and then explain the issue:
Autosave function:
<script>
function autosave() {
$('form').each(function() {
var string = $(this).closest('form').serialize();
var $this = $(this);
$.ajax({
type: "POST",
url: "add_room.php",
data: string,
cache: false,
success: function(data){
var saveIcon = $this.siblings('.saveIcon');
$this.siblings('[type=hidden]').val(data);
saveIcon.fadeIn(750);
saveIcon.delay(500).fadeOut(750);
$('#message').text('The id of the inserted information is ' + data);
}
});
});
}
setInterval(autosave, 10 * 1000);
</script>
AJAX post and return script:
<script>
$(document).ready(function() {
$('body').on('click', '.save', function(e) {
var string = $(this).closest('form').serialize();
var $this = $(this);
$.ajax({
type: "POST",
url: "add_room.php",
data: string,
cache: false,
success: function(data){
var saveIcon = $this.siblings('.saveIcon');
$this.siblings('[type=hidden]').val(data);
saveIcon.fadeIn(750);
saveIcon.delay(500).fadeOut(750);
$('#message').text('The id of the inserted information is ' + data);
}
});
});
});
$(document).ready(function(){
$('#addForm').on('click', function(){
$('<form method="post" action="add_room.php"><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="itemId[]" value=""><input type="hidden" name="itemParent[]" value="<?=$_GET["room"]?>"><div class="saveIcon" style="display: none; color: green;">SAVED!</div><div class="save">Save Item</div></form>').fadeIn(500).appendTo('.addItem');
});
});
</script>
Form:
<form method="post" action="add_room.php">
<label for="itemName[]">Item</label>
<input type="text" name="itemName[]">
<label for="itemPhoto[]">Item</label>
<input type="text" name="itemPhoto[]">
<input type="hidden" name="itemId[]" value="">
<input type="hidden" name="itemParent[]" value="<?=$_GET['room']?>">
<div class="saveIcon" style="display: none; color: green;">SAVED!</div>
<div class="save">Save Item</div>
</form>
PHP:
<?PHP
require_once('dbConfig.php');
$item = $_POST['itemName'];
$photo = $_POST['itemPhoto'];
$id = $_POST['itemId'];
$parentId = $_POST['itemParent'];
foreach($item as $key => $val) {
if(!$id[$key]) {
if ($stmt = $db->prepare("INSERT test (test_title, test_desc, test_parent) VALUES (?, ?, ?)"))
{
// Use an s per variable passed to the string, example - "ss", $firstname, $lastname
$stmt->bind_param("ssi", $val, $photo[$key], $parentId[$key]);
$stmt->execute();
$stmt->close();
echo $db->insert_id;
//echo "success";
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare Insert SQL statement.";
}
}
else
{
if ($stmt = $db->prepare("UPDATE test SET test_title = ?, test_desc = ? WHERE test_id = ?"))
{
// Use an s per variable passed to the string, example - "ss", $firstname, $lastname
$stmt->bind_param("ssi", $val, $photo[$key], $id[$key]);
$stmt->execute();
$stmt->close();
echo $id[$key];
//echo "success";
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare Update SQL statement.";
}
}
}
?>
Now, what happens with the second script is, when used on its own without the autosave, when you fill out the form and click save it takes that forms data and saves it to the necessary rows in a database, and then returns the id of what was just saved and puts that data in a hidden field so that the php script can work out if an insert query is needed or an update query is needed(when the returned id is present). There is also a clickable div called addForm which then appends another form set below the one(s) present and again, when it's save button is clicked ONLY this form is saved/updated in the database. When i trigger the autosave like i have in my code, the autosave literally takes ALL the forms and saves them as new entries but doesn't return the id/update the hidden field to trigger the update sequence. Can you shed ANY light on this at all? It's really bugging me. Have tried explaining this as best i can, sorry it's so long. It's a bit of a complicated one! haha
I'd suggest a few changes to the organization of the code, which then leads to making it easier to identify the errors.
http://pastebin.com/0QTZzX6X
function postForm(form) {
var $this = $(form);
var string = $this.serialize();
$.ajax({
type: "POST",
url: "add_room.php",
data: string,
cache: false,
success: function(data){
var saveIcon = $this.find('.saveIcon');
$this.find('[type=hidden]').val(data);
saveIcon.fadeIn(750);
saveIcon.delay(500).fadeOut(750);
$('#message').text('The id of the inserted information is ' + data);
}
});
}
function autosave() {
$('form').each(function() {
postForm(this);
});
}
setInterval(autosave, 10 * 1000);
$(document).ready(function() {
$('body').on('click', '.save', function(e) {
postForm($(this).closest('form').get(0));
});
$('#addForm').on('click', function(){
$('<form method="post" action="add_room.php"><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="itemId[]" value=""><input type="hidden" name="itemParent[]" value="<?=$_GET["room"]?>"><div class="saveIcon" style="display: none; color: green;">SAVED!</div><div class="save">Save Item</div></form>').fadeIn(500).appendTo('.addItem');
});
});
Basically i took logic that was duplicated and placed it into a more generic function.