I would like to create a dynamic form with add and remove field using jquery and ajax. but unfortunately,my insert button supposedly go to insert.php wont work.When I click insert button,nothing is happened. When the insert button clicked,it will be redirect to insert.php store data inside the database.Here is my coding
repeater.js
jQuery.fn.extend({
createRepeater: function (options = {}) {
var hasOption = function (optionKey) {
return options.hasOwnProperty(optionKey);
};
var option = function (optionKey) {
return options[optionKey];
};
var generateId = function (string) {
return string
.replace(/[/g, '_')
.replace(/]/g, '')
.toLowerCase();
};
var addItem = function (items, key, fresh = true) {
var itemContent = items;
var group = itemContent.data("group");
var item = itemContent;
var input = item.find('input,select');
input.each(function (index, el) {
var attrName = $(el).data('name');
var skipName = $(el).data('skip-name');
if (skipName != true) {
$(el).attr("name", group + "[" + key + "]" + "[" + attrName + "]");
} else {
if (attrName != 'undefined') {
$(el).attr("name", attrName);
}
}
if (fresh == true) {
$(el).attr('value', '');
}
$(el).attr('id', generateId($(el).attr('name')));
$(el).parent().find('label').attr('for', generateId($(el).attr('name')));
})
var itemClone = items;
/* Handling remove btn */
var removeButton = itemClone.find('.remove-btn');
if (key == 0) {
removeButton.attr('disabled', true);
} else {
removeButton.attr('disabled', false);
}
removeButton.attr('onclick', '$(this).parents('.items').remove()');
var newItem = $("<div class='items'>" + itemClone.html() + "<div/>");
newItem.attr('data-index', key)
newItem.appendTo(repeater);
};
/* find elements */
var repeater = this;
var items = repeater.find(".items");
var key = 0;
var addButton = repeater.find('.repeater-add-btn');
items.each(function (index, item) {
items.remove();
if (hasOption('showFirstItemToDefault') && option('showFirstItemToDefault') == true) {
addItem($(item), key);
key++;
} else {
if (items.length > 1) {
addItem($(item), key);
key++;
}
}
});
/* handle click and add items */
addButton.on("click", function () {
addItem($(items[0]), key);
key++;
});
}
});
index.php
<?php
//session_start();
$servername = "localhost";
$username = "root";
$password = "bptm2012";
$dbname = "icompex";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select panel_id,panel_kp,panel_nm from mem_panel";
$result = mysqli_query($conn, $sql);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Add Remove Panel Group and Category</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="repeater.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<br/>
<h3 align="center">Kemaskini Ahli dan Kumpulan Panel Penilai</h3>
<br/>
<div style="width:100%; max-width: 600px; margin:0 auto;">
<div class="panel panel-default">
<div class="panel-heading">Menu Kumpulan dan Ahli Panel</div>
<div class="panel-body">
<span id="success_result"></span>
<div id="div1"><h2></h2></div>
<form method="post" id="repeater_form">
<div class="form-group">
<label>Pilih Group</label><br>
<select class="form-control" name="cat">
<option value="" disabled selected>Sila Pilih Kategori</option>
<option value="A">A - Rekabentuk Alam Bina & Rekabentuk Dalaman</option>
<option value="B">B - Pembinaan dan Bahan</option>
<option value="C">C - Mesin, Peralatan dan Proses Pergilangan</option>
<option value="D">D - ICT & Multimedia</option>
<option value="E">E - Elektrik, Elektronik dan Telekomunikasi</option>
<option value="F">F - Pengangkutan, Automatif & Penerbangan</option>
<option value="G">G - Pertanian, Alam Sekitar dan Tenaga Boleh Diperbaharui</option>
<option value="H">H - Pengajaran dan Pembelajaran</option>
<option value="I">I - Perkhidmatan dan Pemasaran Produk</option>
</select>
<label>Sila Pilih Kumpulan Panel</label><br>
<select name="group" class="form-control">
<option value="" disabled selected>Sila Pilih Kumpulan Panel</option>
<option value="1">Panel 1</option>
<option value="2">Panel 2</option>
<option value="3">Panel 3</option>
<option value="4">Panel 4</option>
<option value="5">Panel 5</option>
<option value="6">Panel 6</option>
<option value="7">Panel 7</option>
<option value="8">Panel 8</option>
<option value="9">Panel 9</option>
<option value="10">Panel 10</option>
<option value="11">Panel 11</option>
<option value="12">Panel 12</option>
<option value="13">Panel 13</option>
<option value="14">Panel 14</option>
<option value="15">Panel 15</option>
</select>
</div>
<div id="repeater">
<div class="repeater-heading" align="right">
<button type="button" class="btn btn-primary repeater-add-btn">Tambah Ahli</button>
</div>
<div class="clearfix"></div>
<div class="items" data-group="programming_languages">
<div class="item-content">
<div class="form-group">
<div class="row">
<div class="col-md-9">
<label>Pilih Nama Ahli Panel</label>
<select class="form-control" data-skip-name="true" data-name="skill[]"
required>
<?php
echo "<option>Sila Pilih Ahli Panel</option>";
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo '<option value="' . $row['panel_id'] . '">' . $row['panel_nm'] . '</option>';
}
} else {
echo "<option>Maaf Belum ada pendaftaran ahli panel dibuat</option>";
}
mysqli_close($conn);
?>
</select>
</div>
<div class="col-md-3" style="margin-top:24px;" align="center">
<button id="remove-btn" class="btn btn-danger"
onclick="$(this).parents('.items').remove()">Remove
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="form-group" align="center">
<br/><br/>
<input type="submit" name="insert" class="btn btn-success" value="insert"/>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$("#repeater").createRepeater();
$('#repeater_form').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: "insert.php",
method: "POST",
data: $(this).serialize(),
success: function (data) {
$('#repeater_form')[0].reset();
$("#repeater").createRepeater();
$('#success_result').html(data);
/*setInterval(function(){
location.reload();
}, 3000);*/
}
});
});
});
</script>
</body>
</html>
insert.php
<?php
connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
if (isset($_POST["name"])) {
$skill = implode(", ", $_POST["skill"]);
$data = array(
':panel_cat' => $_POST["cat"],
':panel_group' => $_POST["group"],
':panel_mem' => $skill
);
$query = "
INSERT INTO panel_penilai
(panel_cat, panel_group,panel_mem)
VALUES (:panel_cat, :panel_group, :panel_mem)
";
$statement = $connect->prepare($query);
if ($statement->execute($data)) {
echo '
<div class="alert alert-success">
Data Successfully Inserted
</div>
';
}
}
//?>
4
Answers
first in insert.php your code will run if there is a “name” parameter that is posted, whereas in the index.php form there is no field with the name “name”.
so the insert.php file doesn’t display any results when you post with the current form
And as reminder you forget about $ and there is a database difference between insert.php and index.php
should be
and in ajax you better add error handling so that you can see the error information in the console browser
You can use XMLHTTP request to send the request. It is easier than your function and fully working. Check a sample request here XMLHTTP REQUEST
Let me know if you were successfull
Remove
event.preventDefault();
.preventDefault() method is used to stop submitting the form. Removing it will allow the form to submit the data to
insert.php
You just change the submit button type to button
And event must be click not submit
so page will not redirect, data post throw ajax.