AJAX Submit Button Got Disabled - php

i want to create a dynamic search using php and ajax, and then choose the results that will be inserted in another tabke in database by using checkboxes..
here's the code to query the search in table
<?php
//include('../koneksi/koneksi.php');
mysql_connect('localhost','root',''); //ini untuk koneksi databasenya
mysql_select_db('aam'); // nama tabel
$key=$_GET['q'];
$query = mysql_query("select * from dokter where nama LIKE '%$key%'");
echo "
<table border='1'>
<tr>
<th>Kode Dokter</th>
<th>Nama</th>
<th>Spesialis</th>
<th>Alamat</th>
<th>Kota</th>
<th>Pilih</th>
</tr>
";
while($row = mysql_fetch_array($query))
{
//$array[] = $row['title'];
echo "<tr>";
echo "<th>" . $row['id_dokter'] . "</th>";
echo "<th>" . $row['nama'] . "</th>";
echo "<th>" . $row['spesialis'] . "</th>";
echo "<th>" . $row['alamat'] . "</th>";
echo "<th>" . $row['kota'] . "</th>";
echo"<th> <input name='chkbox[]' type='checkbox' value='". $row['id_dokter'] ."'> </th>";
echo "</tr>";
}
echo "</table>";
?>
the code above will generate a table in my page. after the results populated, i use this code to submit my choices to the database
function kirimJadwal(){
$(document).ready(function(e) {
var checkboxdokter = new Array();
$("form#formulir").on('submit', function(e){
e.preventDefault();
/*$("input:checked").each(function() {
checkboxdokter.push($(this).val());
});*/
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
//data: {checkboxdokter:checkboxdokter},
data: $("form#formulir").serialize(),
success: function(data){
alert(checkboxdokter);
}
});
});
});
}
and this is the form that i use to put the results
<form method='post' action='Planning-kirim.php' name="formulir" id="formulir">
</div>
<label> Atur Jadwal</label>
<a id="dt1" href="#" <span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></a>
<input type="date" name="date">
<input type="submit" id="kirim" value="Submit" />
</form>
the problem is, when the results populated, the submit button will do nothing everytime i click it? is there any of my functions here that freezes the button???

Try to replace your javascript with this:
$(document).ready(function() {
$("#formulir").on('submit', function(){
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
data: $("#formulir").serialize(),
success: function(data){
alert("123");
}
});
return false;
});
});
And html with this:
$(document).ready(function() {
$("#formulir").on('submit', function(){
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
data: $("#formulir").serialize(),
success: function(data){
alert("123");
}
}).done(function(){
alert();
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method='post' action='Planning-kirim.php' name="formulir" id="formulir">
<label> Atur Jadwal</label>
<a id="dt1" href="#" ><span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></a>
<input type="date" name="date">
<input type="submit" id="kirim" value="Submit" />
</form>
Click on the submit button and look to the firebug. You'll find sent requests there. So the javascript works.

Document need to load before function.
$(document).ready(function(e) {
kirimJadwal();
function kirimJadwal(){
var checkboxdokter = new Array();
$("form#formulir").on('submit', function(e){
e.preventDefault();
/*$("input:checked").each(function() {
checkboxdokter.push($(this).val());
});*/
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
//data: {checkboxdokter:checkboxdokter},
data: $("form#formulir").serialize(),
success: function(data){
alert(checkboxdokter);
}
});
});
});
}

Related

Post element value to database with ajax

i'm a beginner with databases, ajax and php. I want a user to make a choice from a list with checkboxes and when a choice is made, the choice is sent to the database. I have this code:
<form method="post" action="post" class="registry-form">
<div class="list">
<div>
<input id='label-1' type='checkbox' />
<label for='label-1'>
<h3>
<span>Studio Noos Mom Bag | Urban Woollish</span>
<span>
<br />
Bekijk product
</span>
</h3>
</label>
</div>
...
</div>
</form>
<input type="submit" class="gift-btn" value="submit choice" />
<script>
$(document).ready(function() {
$(".list div input[type=checkbox]").change(function() {
$(this).parent().toggleClass('checked');
});
$('.registry-form').submit( function(e) {
e.preventDefault();
var geboortelijst_beschrijving = $(".list .checked h3 span:first-child").html();
console.log(geboortelijst_beschrijving);
$.ajax({
type: "POST",
url: "post.php",
dataType:'json',
data: geboortelijst_beschrijving,
success: function(data){
$(".list .checked").addClass('taken');
}
});
return false;
});
});
</script>
post.php:
<?php
header("Content-Type: application/json", true);
$conn = mysqli_connect("localhost","root","root","geboortelijst");
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$geboortelijst_beschrijving = $_POST['geboortelijst_beschrijving'];
//$geboortelijst_beschrijving = mysqli_real_escape_string($conn, $_POST['geboortelijst_beschrijving']);
if(mysqli_query($conn, "INSERT INTO geboortelijst(geboortelijst_beschrijving, geboortelijst_status)
VALUES('" . $geboortelijst_beschrijving . "', '1')")) {
echo '1';
} else {
echo "Error: " . $sql . "" . mysqli_error($conn);
}
mysqli_close($conn);
?>
The response i get from post.php is always 200 0K, but i have no idea why the "geboortelijst_beschrijving" is not being sent to my database. This value is empty and i always and only get "1" (which of course comes from geboortelijst_status).
Anybody have some insights?
$(".list .checked h3 span:first-child") is not the correct selector. This is looking for an h3 that's contained in the checkbox element, but checkboxes aren't containers.
You want the h3 that's a sibling of the checkbox, not a descendant, and then find the first span in that.
var geboortelijst_beschrijving = $(".list .checked").siblings("h3").find("span:first-child").html();
Something like this
$(document).ready(function() {
$('.registry-form').submit( function(e) {
e.preventDefault();
let checkboxes=$.find("input[type='checkbox']");
for(let i=0; i<checkboxes.length; i++)
{
let checkbox=checkboxes[i];
let id=checkbox.getAttribute("id");
if (id!=null && id.contains("label-") && checkbox.checked)
{
let label=$.find("label[for='"+id+"']")[0];
if (label!=null)
{
var geboortelijst_beschrijving = $(label).html();
console.log(geboortelijst_beschrijving);
$.ajax({
type: "POST",
url: "post.php",
dataType:'json',
data: "geboortelijst_beschrijving="+geboortelijst_beschrijving,
success: function(data){
$(checkbox.parentElement).addClass('taken');
}
});
}
}
}
})
});

post input name array of while loop

there is array in while loop please check with code below
<?php
$addItemSql = "SELECT * from tbl_invoice_services where col_cust_id='$getID' ORDER BY col_service_id";
$addItemResult = mysqli_query($db, $addItemSql);
while ($addItemRow = mysqli_fetch_assoc($addItemResult)) {
?>
<tr>
<td>
<input type="hidden" id="col_service_product1" name="col_service_product1[]" value="<?php echo $addItemRow['col_service_product']; ?>">
</td>
</tr>
<?php} ?>
and want to post those array value to php
ajax code
$('.saveInvoice').on('click', function (ev) {
$.ajax({
url: "saveInvoce.php",
type: "POST",
data: {
col_service_product1:$('#col_service_product1').val()
},
success: function (data) { }
});
});
try this demo code
file1
<?php
$i=0;
while ($i<5) {
?>
<tr>
<td>
<input type="hidden" id="col_service_product1" name="col_service_product1" value="<?php echo $i; ?>">
</td>
</tr>
<?php $i++; } ?>
<button value="Save Invoice" class="saveInvoice">Save Invoice</button>
<script type="text/javascript" src="../library/q.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.saveInvoice').click(function () {
var arr=[];
var data=document.getElementsByName("col_service_product1");
for(var i=0;i<data.length;i++){
arr[i]=data[i].value;
}
$.ajax({
url: "saveInvoce.php",
type: "post",
data: {col_service_product1:arr},
success: function (data) {
alert(data);
}
});
});
});
</script>
file2
<?php
$data=$_POST['col_service_product1'];
//code for save data in table
foreach($data as $value){
echo $value; //query here
}

ajax call returns only last id

I am trying to develop an add to cart function via ajax, the problem is that no matter which product I add to cart, it adds the last item on the list and then increments the same product upon clicking on any other product. Here is my code:-
<?php
$i = 1;
while($row = mysqli_fetch_array($run_products)){
$op_id = $row['option_id'];
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row['option_desc'] . "</td>";
echo "<td>
<form action='' method='post' class='p_form'>
<input type='text' name='product_id' value='$op_id' pid='$op_id'>
<input type='text' name='quantity' value='1' pid='$op_id'>
<input class='btn btn-primary add' type='submit' name='add_to_cart' value='Add to Cart' id='product' pid='$op_id'>
</form>
</td>";
echo "</tr>";
$i++;
}
?>
Here is jquery:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.p_form',function (event) {
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
//data: {id:id},
data:$('.p_form').serialize(),
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
Here is action.php, the $product_id always returns as 4 (for example) if the last id in the last is 4
if (!empty($_POST)){
$product_id = $_POST['product_id'];
echo $product_id;
}
Need to do it like below:-
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.add',function (event) {//instead of form click add event on form button click
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
data:element.parent('.p_form').serialize(), //serialize clicked button parent form
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
Trigger click event on button click not on the form click:
This will work for you for each product.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.add',function (event) {
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
data: {id:id}, //send id of product you wish to add
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
And on server side:
if (!empty($_POST)){
$product_id = $_POST['id'];//get only that id posted in ajax call
echo $product_id;
}

How to delete all entry from table using checkBox clickall after confirmation is true? jQuery Ajax PHP

I am trying to delete all records from the table using the checkbox. When the user checked the topmost checkbox, it will check all other checkboxes inside the loop then a confirmation box will appear about deleting the records. if the user click OK, the the all the records will be deleted using $.ajax, if he clicked Cancel, then, the page will return to the same state, and the checkboxes are not checked anymore.
<?php
include 'dbconn.php';
?>
<table border="1" >
<tr><td align="center" width="20"><input type="checkbox" name='checkALL' id='checkALL'></td><td>Name</td>
</tr>
<?php
$sql=mysql_query("SELECT * FROM names ORDER BY names ASC") or die(mysql_error());
while($rows=mysql_fetch_assoc($sql)){
?>
<tr>
<td><input type="checkbox" name="id[]" id="id[]" value="<?php print $rows['id'];?>">
</td><td>Name</td>
</tr>
<?php
}
?>
</table>
JQUERY
<script>
$(function(){
//click all
$('#checkALL').click(function(){
$(':checkbox').attr({checked: 'true'});
var del=confirm("You checked all the box. Delete All?");
if(del==true){
//delete here using $.ajax
}
else{
window.location.reload(false);
$('#checkAll').attr({checked: 'false'});
}
});
});
</script>
Place this in your if block.
$.ajax({
type: "GET",
url: '<php file which truncates table>',
success: function (data) {
if (data == 'truncated') {
alert('success');
} else {
alert('not truncated');
}
}
});
Return the string truncated from your php file on success.
Here U- PageUrl, A- Action on page, P- Parameter
if (confirm('Are you sure to delete this record?')) {
Operation(U, A, P);
}
function Operation(U, A, P) {
$.ajax({
type: "POST",
url: U + '/' + A,
data: P,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (r) {
var str = r.d;
}
});
}
You can use something like this in your HTML check all page
<html>
<head><title>Select/Delete ALL with jQuery/PHP</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<table border="1" cellpadding="5">
<tr>
<th>
<input type="checkbox" id="checkAll" />
</th>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="100" /></td>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="200" /></td>
</tr>
<tr>
<td><input type="checkbox" class="check" name="posts[]" value="300" /></td>
</tr>
</table>
<script>
$(document).ready(function(){
var checked = false;
$('#checkAll').click(function(){
if (checked == false){
checked = true
} else {
checked = false
}
$('input.check').attr("checked",checked);
var confirmDelete=confirm("You checked all the box. Delete All?");
if (confirmDelete==true){
var csv = '';
$('.check').each(function() {
csv += $(this).attr("value") + ",";
});
$.ajax({
type: "POST",
url: "delete.php",
data: { tobeDeleted: csv }
}).done(function( msg ) {
console.log( "Data has been deleted: " + msg );
});
} else {
$('#checkAll').attr("checked", false);
$('input.check').attr("checked", false);
}
});
});
</script>
</body>
</html>
and use something like this in your PHP script
<?php
$postDeleted = substr($_POST['tobeDeleted'], 0, strlen($_POST['tobeDeleted'])-1);
$arrDeleted = explode(",", $postDeleted);
$sql = "DELETE FROM employee WHERE 1=1 ";
foreach($arrDeleted as $key=>$value){
$sql .= "OR employee_id = $value ";
}
echo $sql;
?>
if(del==true){
$.ajax({
type: "POST",
url: 'your_file_url',
async:false,
cache: false,
success: function(data){
if (data == 1) {
alert('success');
} else {
alert('Error');
}
}
});
}
In your php file, echo 1 for successful delete and 0 for some error

Delete record using jquery ajax but table is loaded again

I am deleting records using jQuery and Ajax. The code I wrote deletes a record but the HTML table is loaded again, which means the page refreshes which I want to avoid.
Here is my code:
comment.php
<script type="text/javascript">
$(document).ready(function(){
function loadList(){
$.ajax({
url: "load_list.php",
cache: false,
success : function(html){
$(".name_list").html(html);
}
});
}
loadList();
$("#Submit").click(function() {
if($(":text").val().length==0)
{
// $(this).next().html("Field needs filling");
$(":text").after('<span class="errorkeyup">Field cannot be empty</span>');
//return false;
success = false;
}
else
{
var name=$("#name").val();
var message=$("#message").val();
$.ajax({
type:"post",
url:"save_list.php",
data:"name="+name+"&message="+message,
success:function(data){
loadList();
}
});
return false;
}
});
$(".delete_button").on("click", function(){
//this deletes the row clicked on with an alert and then reloads the list
var id = $(this).attr("id");
/*var x=window.confirm("Are you sure you want to delete this item?")
if (x==true){*/
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function(){
loadList();
}
});
// }
return false;
});
});
</script>
</head>
<body>
<div id="form">
<form method="post" name="form" action="">
<div id="content">
Name : <input type="text" name="name" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
</div>
<input type="button" value="Submit" id="Submit">
</form>
</div>
<div class="name_list"></div>
</body>
loadlist.php
<?php
include('connection.php');
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<table border="1">';
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td>
<a id='".$row['id']."' href=delete.php?id=".$row['id']."&type=Delete class=delete_button>Delete</a></td>";
echo"<td>
<a id='".$row['id']."' href=comment.php?id=".$row['id']."&type=edit class=edit_button>Edit</a></td>";
echo '</tr>';
$i++;
}
echo'</table>';
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: comment.php");
}
?>
When you do the $.ajax() call for $('.delete_button'), you shouldn't call your loadList() function there because that is what reloads the table, instead you should just remove the one entry that's deleted from the table.
Perhaps you can remove it with something similar to this, placed inside the delete button success callback:
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function()
{
$(this).parent().parent().remove();
}
});
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: comment.php");
}
?>
in this code remove line
header("location: comment.php");
Final code would be,
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
echo '1';
} else {
echo '0';
}
exit;
?>
In delete function, after executing delete query, you need to echo '1' or '0'. Lets say echo '1'; when deleted successfully and echo '0' when delete not succeed. So based on 1 or 0 you can remove those deleted row from table by ,
$(".delete_button").on("click", function(){
//this deletes the row clicked on with an alert and then reloads the list
var obj = $(this);
var id = obj.attr("id");
/*var x=window.confirm("Are you sure you want to delete this item?")
if (x==true){*/
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function(response){
if(response == '1') {
obj.parent.remove();
}
}
});
// }
return false;
});

Categories