How do i pass the ID of row to Modal? - javascript

I have Edit button on each row. If I press Edit button on selected row I need pass ID of this row to Modal and use it in sql query to call rest of data. P.S. I tried many ways, no one of them helped and based on bootstrap.
Here is my code with Modal
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<div class="table-responsive">
<table class="table" id="myTable">
<thead>
<tr class="header">
<th>#</th>
<th>Müştərinin Nömrəsi</th>
<th>Götürülən Ünvan</th>
<th>Gədilən Ünvan</th>
<th>Zəng Vaxtı</th>
<th>Sürücünün Tabel Kod</th>
<th>Təhfil aldı</th>
<th>Təhfil verdi</th>
<th>Maşın Nömrəsi</th>
<th>Qiymət</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
while($data=mysql_fetch_array($result)) // цикл вывода
{
$id = $data['id'];
echo "<tr>
<td></td>
<td>".$data['MUSHTERINOMRE']."</td>
<td>".$data['MUSHTERIHARDAN']."</td>
<td>".$data['MUSHTERIHARA']."</td>
<td>".$data['ZENGVAXTI']."</td>
<td>".$data['TABELKOD']."</td>
<td>".$data['TEHFILALDI']."</td>
<td>".$data['TEHFILVERDI']."</td>
<td>".$data['MASHINNOMRE']."</td>
<td>".$data['QIYMET']."</td>
<td><button class=\"btn btn-success\" onclick='getValue(".$id.");' data-toggle=\"modal\" data-target=\"#myModal\" contenteditable=\false\" value=".$id.">EDIT </button></td>
"; ?>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content"></div>
</div>
<div class="modal-dialog">
<div class="modal-content"></div>
</div>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true" class="">? </span><span class="sr-only">Close</span>
</button>
<!--Here I am trying to echo ID
<h4 class="modal-title" id="myModalLabel"><?php //echo $id."ID OFaa"; ?></h4>-->
</div>
<div class="modal-body">
<?php echo $id."I NEED TO GET ID HERE "; ?>
<?php
$link = mysql_connect('localhost', 'user', 'psw');
$db_selected = mysql_select_db('my_db', $link);
$query = mysql_query("Select * from my_table where id = $id");
//var_dump($pt);
$row = mysql_fetch_array($query);
$number = $row['num'];
?>
<div class="form-group">
<label for="name" class="control-label">Müştəri Nömrə:</label>
<input type="text" class="form-control" id="num" name="num" value="<?php echo $number; ?>" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>

The most important thing to remember is that PHP won't execute client-side, so populating the dialog with id and editable values must be performed by the client-side language - javascript. Your only option for further server-side involvement during the editing process is to make AJAX call(s).
You will find the process a lot simpler with a "promisified" modal dialog. Rather than write something yourself, you can install install, bootStrapModal, giving you a modal that is much like the standard Bootstrap modal but behaves as an asynchronous resource.
HTML:
<script src="js/bsBetterModal.js"></script>
Build the table rows as follows :
while($data=mysql_fetch_array($result)) { // цикл вывода
$id = $data['id'];
echo "<tr data-id=\".$id.\">
<td></td>
<td class=\"mushterinomre\">".$data['MUSHTERINOMRE']."</td>
<td class=\"mushterihardan\">".$data['MUSHTERIHARDAN']."</td>
<td class=\"mushterihara\">".$data['MUSHTERIHARA']."</td>
<td class=\"zengvaxti\">".$data['ZENGVAXTI']."</td>
<td class=\"tabelkod\">".$data['TABELKOD']."</td>
<td class=\"tehfilaldi\">".$data['TEHFILALDI']."</td>
<td class=\"tehfilverdi\">".$data['TEHFILVERDI']."</td>
<td class=\"mashinnomre\">".$data['MASHINNOMRE']."</td>
<td class=\"qiymet\">".$data['QIYMET']."</td>
<td><button class=\"btn btn-success edit\">EDIT</button></td>
</tr>";
} ?>
...
Write the dialog's header as follows :
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true" class="">? </span><span class="sr-only">Close</span></button>
<h4 class="modal-title dlg-element" data-element="id"></h4>
</div>
Write each of the dialog's inputs (x8) as follows :
<label class="control-label">Müştəri Nömrə:</label>
<input type="text" class="dlg-element" data-element="mushterinomre" value="" />
Write the dialog footer as follows :
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary ok">Save changes</button>
</div>
The EDIT buttons' click handler is a little complicated. It comprises some preamble followed by a promise chain. I've made it as simple as I can by unloading the fiddly bits into a bunch of helper utilities.
jQuery(function($) {
// *** start: click handler ***
$('#myTable').on('click', '.edit', function(e) {
e.preventDefault(); // in case button attempts form submission
var $button = $(this).prop('disabled', true);
var $row = $(this).closest('tr');
var idHash = { 'id': $row.data('id') }; // <<<<<< HERE'S THE ID - expressed as a js plain object.
// From here on, everything is asynchronous, therefore performed within a promise chain.
fetchValues(idHash) // Fetch current values (onscreen values may be stale)
.then(function(valuesHash) {
return betterModal.run($('#myModal'), $.extend(valuesHash, idHash))// Open modal window, populated with current field values.
.then(function($dialog) {
// The dialog was accepted.
// `$dialog` holds a jQuery object of the dialog.
return saveValues($.extend(dialogToHash($dialog), idHash)); // Pass hash of editable field values, plus idHash, to saveValues()
})
.then(function() {
// New values were successfully saved.
// valuesHash is still in scope
updateHtmlTableRow($row, valuesHash); // Update the HTML table row with the edited values.
}, function(err) {
// Save failed
// Provide warning to user ...
return err;
})
})
.then(null, function(err) {
console.log(err);
$button.prop('disabled', false);
})
.always(function() {
$button.prop('disabled', false);
});
});
// *** end: click handler ***
var fields = ['mushterinomre', 'mushterihardan', 'mushterihara', 'tabelkod', 'tehfilaldi', 'tehfilverdi', 'mashinnomre', 'qiymet']; // 'zengvaxti' omitted
// *** start: helper utility functions ***
function fetchValues(idHash) {
return $.getJSON({
'url': 'api.php', // replace with actual url
'method': 'get',
'data': idHash
});
}
function saveValues(values) {
return $.ajax({
'url': 'api.php', // replace with actual url
'method': 'put',
'data': values
});
}
function dialogToHash($dialog) {
var hash = {};
fields.forEach(function(f) {
hash[f] = $('.'+f, $dialog).val();
});
return hash;
}
function updateHtmlTableRow($row, valuesHash) {
fields.forEach(function(f) {
$('.'+f, $row).text(valuesHash[f]),
});
}
// *** end: utility functions ***
});
Untested and sketchy in places so will need debugging. Some server-side stuff also needs to be addressed.

Hope this gives you some direction
function getValue(id)
{
$.ajax({
url:'filename.php',
method:'get',
data:'id='+id,
success: function(ret)
{
// add the returned value into the modal body
$('#modalBody').html(ret);
// show the modal
$('#myModal').show();
}
});
}

Related

How to get $_SESSION value updated when jscript confirm and call PHP by AJAX

After lots of trying, I need help. After a click event, i perform checking on data exist in my database and use jscript to pop a confirmation box.
How to get it works as I click cancel, its not showing any value I set on confirm.php?
Confirm with OK and Cancel
jscript code:
if($row_count2 > 0)
{
if ($row2["Status"] == "REJECTED")
{
<script type="text/javascript">
if (!confirm('Lot No has been REJECTED before.. Double confirm to add the Lot No!!')) {
var option = "NO";
$.ajax({
type: "POST",
url: "confirm.php",
data: "value="+option,
success: function (data) {
alert(data);
}
});
}
</script>
}
}
$ll = $_SESSION['Confirm'];
echo "<script type='text/javascript'>alert('$ll');</script>";
if ($row_count2 < 1 || ($_SESSION['Confirm'] = "YES"))
{
//my insert query is here...
}
And this is inside confirm.php:
<?php
session_start();
$xx = $_REQUEST["value"];
$_SESSION['Confirm'] = $xx;
echo "<script type='text/javascript'>alert('$xx');</script>";
?>
I'm expecting to get $_SESSION['Confirm'] value as NO
By default $_SESSION['Confirm'] value is YES
alert(data) shows that $xx is NO but when I put alert for $_SESSION['Confirm'] value on if condition
before my insert query $_SESSION['Confirm'] value still remain YES
Instead of using JScript alert which is really troublesome.. I end up using modal popup alert..
<div class="modal-content">
<div class="modal-header bg-secondary">
<button type="button" class="close" data-dismiss="modal"></button>
<h4 class="modal-title text-white ">Confirmation</h4>
</div>
<div class="modal-body">
<div class="box-body">
<form class="form-signin">
<label for="txtLotNo" class="mr-sm-2 ml-sm-4">Lot No : '.$lotNo.' has been REJECTED before.. Double confirm to add the Lot No!!</label>
<br>
<div class="text-center">
<button type="button" id="getAdd" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#myAdd" data-id="YES'.$lotNo.$newLotNo.'" >YES</button>
<button type="button" id="getAdd" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#myAdd" data-id="NO" >NO</button>
</div>
</form>
</div>
</div>
</div>
Then I call a php file using JScript which can handle the data-id perfectly..
<script>
$(document).on('click','#getAdd',function(e){
e.preventDefault();
var per_id=$(this).data('id');
//alert(per_id);
$('#add-data').html('');
$.ajax({
url:'addLot_func.php',
type:'POST',
data:'id='+per_id,
dataType:'html'
}).done(function(data){
$('#add-data').html('');
$('#add-data').html(data);
}).fail(function(){
$('#add-data').html('<p>Error</p>');
});
});
</script>
In addLot_func.php:
if(isset($_REQUEST['id'])){
$id=intval($_REQUEST['id']);
$reject = $_REQUEST['id'];
}
else $reject = "";
if(substr($reject,0,3) == "YES")
{
...
}
else
{
...
}

Trying to pass data from a database into a bootstrap modal when opened. How do I go about doing this?

I'm trying to pass data from my database into a modal form. The purpose of this modal is so users can edit their data within the database and then save the changes to said data.
I've tried many tutorials on YouTube, as well as reading previous responses on this site using methods such as doing it through Ajax and Bootstrap Modal Event Listener & Ajax and jQuery Click function but due to my inexperience with these programming languages I've yet to understand as the examples are vastly different to my project. Below is my code for form as well as the tables in my database
Button used to open the modal:
<a class="badge badge-success p-2" role="button" data-toggle="modal" data-target="#editPostModal">Edit</a>
Modal:
<div class="modal fade" id="editPostModal" tabindex="-1" role="dialog"aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Update Post</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form action="editdata.inc.php" method="POST" enctype="multipart/form-data"> // PHP File I would like to use to run a possible "update" query
<div class="modal-body">
<div class="form-group">
<input type="text" name="themeContent" class="form-control" placeholder = "Enter theme"/>
</div>
<div class="form-group">
<input type="text" name="visualIdeaContent" class="form-control" placeholder = "Enter idea"/>
</div>
<div class="form-group">
<input type="text" name="captionContent" class="form-control" value="<?= $captionContent; ?>" placeholder = "Insert caption"/>
</div>
<div class="form-group">
<input type="date" name="dateContent" class="form-control" placeholder = "Select date"/>
</div>
<div class="form-group">
<input type="text" name="linkContent" class="form-control" placeholder = "Insert URL"/>
</div>
<div class="form-group">
<input type="file" name="visualContent" class="custom-file" placeholder = "Upload picture"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="submit" name="editdata" class="btn btn-primary">Save Changes</button>
</div>
</form>
</div>
</div>
Database
Name: annexcms
Table: content
uidContent // Unique ID
themeContent
visualIdeaContent
captionContent
dateContent
linkContent
visualContent
All in all, I expect the modal to:
1) Open and display data from the database tied to a specific User ID
2) Have the ability to save any changes made to that data when clicking the "Save Changes" button.
3) Have the saved data updated in the database.
This is the last part of my CRUD application as I've mastered the other three features. Appreciate any help I can receive.
You need 2 controller methods:
public function respondData($id)
{
//you can ever check if id exist here or if exist at all and
//throw any exeptions if not exist, this is just example
if($checkUser->exist($id))
{
$userData = array('id' => '1, 'name' => 'Name');
return json_encode($data);
}
throw new \Exeption('User does not exist');
}
public function saveData()
{
if($_POST)
{
if(($checkUser->exist($_POST['id'])))
{
//get value from POST and check and update
return true; // or message and parse it if it was ajax request
}
}
throw new \Exeption('Method not allowed');
}
JQUERY:
You need to get data from your user and bind it to modal
You can do this this way:
add data-user to you button or a link and other method to trigger modal opening:
$(document).on('click', '#your-link', function () {
var data = $(this).data('user');
$.post({
url: 'url_to_first_action' + '?id=' + data,
data: data,
success: function(data){
//here you parse JSON ARRAY to your fields
},
});
});
Now after user submit you data to second action you can do this with straight POST request or use the ajax to serialize() post.
So after tinkering with previous code, I got this to work.
My table:
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>Theme</th>
<th>Visual Idea</th>
<th>Caption</th>
<th>Date</th>
<th>Visual</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$table = mysqli_query($conn ,'SELECT * FROM content');
while($row = mysqli_fetch_array($table)){ ?>
<tr id="<?php echo $row['uidContent']; ?>">
<td width="200" data-target="themeContent"><?php echo $row['themeContent']; ?></td>
<td width="300" data-target="visualIdeaContent"><?php echo $row['visualIdeaContent']; ?></td>
<td width="600" data-target="captionContent"><?php echo $row['captionContent']; ?></td>
<td width="100" data-target="dateContent"><?php echo $row['dateContent']; ?></td>
<td width="200" data-target="visualContent"><img id="imgsrc" src="<?php echo $row['visualContent']; ?>"width="200"/></td>
<td style = "display:none" width="100" data-target="linkContent"><?php echo $row['linkContent']; ?></td>
<td width="170">
<a class="badge badge-primary p-2" role="button" href="<?php echo $row['linkContent']; ?>" target="_blank">Link</a>
<a class="badge badge-success p-2" href="#" data-role="update" data-id="<?php echo $row['uidContent'] ;?>">Edit</a>
<a class="badge badge-danger p-2" role="button" href="action.inc.php?delete=<?php echo $row['uidContent'] ;?>" onclick="return confirm('Are you sure you want to delete this post? This process cannot be undone.');">Delete</a>
</td>
</tr>
<?php }
?>
</tbody>
</table>
The script:
<script>
$(document).ready(function(){
// Gets values in input fields
$(document).on('click','a[data-role=update]',function(){
var id = $(this).data('id');
var themeContent = $('#'+id).children('td[data-target=themeContent]').text();
var visualIdeaContent = $('#'+id).children('td[data-target=visualIdeaContent]').text();
var captionContent = $('#'+id).children('td[data-target=captionContent]').text();
var linkContent = $('#'+id).children('td[data-target=linkContent]').text();
var dateContent = $('#'+id).children('td[data-target=dateContent]').text();
var visualContent = $('#'+id).children('td[data-target=visualContent]').text();
$('#themeContent').val(themeContent);
$('#visualIdeaContent').val(visualIdeaContent);
$('#captionContent').val(captionContent);
$('#dateContent').val(dateContent);
$('#linkContent').val(linkContent);
$('#visualContent').val(visualContent);
$('#uidContent').val(id);
$('#updatePostModal').modal('toggle');
});
});
</script>
The only issue is that I'm not getting the image path to display as a thumbnail in the form, but I'll figure it out on my own through research.
My code is ugly, but at this point, I'm more concerned about the functionality. Thanks everyone.

Why can't the edit-modal fetch the data(of the selected row) from my database?

So this is my brand.php file
And it portrays the edit part of the brand
so in this part we can probably see how the thing will look like
<!-- edit brand -->
<div class="modal fade" id="editBrandModel" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" id="editBrandForm" action="php_action/editBrand.php" method="POST">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title"><i class="fa fa-edit"></i> Edit Brand</h4>
</div>
<div class="modal-body">
<div id="edit-brand-messages"></div>
<div class="modal-loading div-hide" style="width:50px; margin:auto;padding-top:50px; padding-bottom:50px;">
<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>
<span class="sr-only">Loading...</span>
</div>
<div class="edit-brand-result">
<div class="form-group">
<label for="editBrandName" class="col-sm-3 control-label">Brand Name: </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<input type="text" class="form-control" id="editBrandName" placeholder="Brand Name" name="editBrandName" autocomplete="off">
</div>
</div> <!-- /form-group-->
<div class="form-group">
<label for="editBrandStatus" class="col-sm-3 control-label">Status: </label>
<label class="col-sm-1 control-label">: </label>
<div class="col-sm-8">
<select class="form-control" id="editBrandStatus" name="editBrandStatus">
<option value="">~~SELECT~~</option>
<option value="1">Available</option>
<option value="2">Not Available</option>
</select>
</div>
</div> <!-- /form-group-->
</div>
<!-- /edit brand result -->
</div> <!-- /modal-body -->
<div class="modal-footer editBrandFooter">
<button type="button" class="btn btn-default" data-dismiss="modal"> <i class="glyphicon glyphicon-remove-sign"></i> Close</button>
<button type="submit" class="btn btn-success" id="editBrandBtn" data-loading-text="Loading..." autocomplete="off"> <i class="glyphicon glyphicon-ok-sign"></i> Save Changes</button>
</div>
<!-- /modal-footer -->
</form>
<!-- /.form -->
</div>
<!-- /modal-content -->
</div>
<!-- /modal-dailog -->
</div>
<!-- / add modal -->
<!-- /edit brand -->
> --this one is the end part
And this is the fetching part, wherein once you click the button from the row(example row 1), a modal(Edit Modal will likely appear), but the thing is, once the modal appear, the data that is supposed to be fetched from the row is not on that modal ;-;
<?php
require_once '../../includes/connection.php';
$brandId = $_POST['brandId'];
$sql = "SELECT brand_id, brand_name, brand_active, brand_status FROM brands WHERE brand_id = $brandId";
$result = $connect->query($sql);
if($result->num_rows > 0) {
$row = $result->fetch_array();
} // if num_rows
$connect->close();
echo json_encode($row);
?>
Now the JScript part
This part is the filler part(like getting the data and now portraying the data and filling the input boxes etc..)
function editBrands(brandId = null) {
if(brandId) {
// remove hidden brand id text
$('#brandId').remove();
// remove the error
$('.text-danger').remove();
// remove the form-error
$('.form-group').removeClass('has-error').removeClass('has-success');
// modal loading
$('.modal-loading').removeClass('div-hide');
// modal result
$('.edit-brand-result').addClass('div-hide');
// modal footer
$('.editBrandFooter').addClass('div-hide');
$.ajax({
url: 'fetchSelectedBrand.php',
type: 'post',
data: {brandId : brandId},
dataType: 'json',
success:function(response) {
// modal loading
$('.modal-loading').addClass('div-hide');
// modal result
$('.edit-brand-result').removeClass('div-hide');
// modal footer
$('.editBrandFooter').removeClass('div-hide');
// setting the brand name value
$('#editBrandName').val(response.brand_name);
// setting the brand status value
$('#editBrandStatus').val(response.brand_active);
// brand id
$(".editBrandFooter").after('<input type="hidden" name="brandId" id="brandId" value="'+response.brand_id+'" />');
// update brand form
$('#editBrandForm').unbind('submit').bind('submit', function() {
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
var brandName = $('#editBrandName').val();
var brandStatus = $('#editBrandStatus').val();
if(brandName == "") {
$("#editBrandName").after('<p class="text-danger">Brand Name field is required</p>');
$('#editBrandName').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#editBrandName").find('.text-danger').remove();
// success out for form
$("#editBrandName").closest('.form-group').addClass('has-success');
}
if(brandStatus == "") {
$("#editBrandStatus").after('<p class="text-danger">Brand Name field is required</p>');
$('#editBrandStatus').closest('.form-group').addClass('has-error');
} else {
// remove error text field
$("#editBrandStatus").find('.text-danger').remove();
// success out for form
$("#editBrandStatus").closest('.form-group').addClass('has-success');
}
if(brandName && brandStatus) {
var form = $(this);
// submit btn
$('#editBrandBtn').button('loading');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success:function(response) {
if(response.success == true) {
console.log(response);
// submit btn
$('#editBrandBtn').button('reset');
// reload the manage member table
manageBrandTable.ajax.reload(null, false);
// remove the error text
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
$('#edit-brand-messages').html('<div class="alert alert-success">'+
'<button type="button" class="close" data-dismiss="alert">×</button>'+
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> '+ response.messages +
'</div>');
$(".alert-success").delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
}); // /.alert
} // /if
}// /success
}); // /ajax
} // /if
return false;
}); // /update brand form
} // /success
}); // ajax function
} else {
alert('error!! Refresh the page again');
}
} // /edit brands function
Can you check the Network tab to see the result from server? You can debug your app by seeing that result.
By the way, there're two things that you may need to edit:
1/ If brandId is interger, you need to get it from $_GET by intval($_POST['brandId']) to prevent SQL Injection.
2/
if($result->num_rows > 0) {
$row = $result->fetch_array();
}
else {
$row = array();
}
your code need to return empty array if sql result is empty to avoid Undefined variable error.

j query updating div of drop-down after inserting data

I have a drop down which i am filling from database (ss and source attached)
<div id="divmedium">
<label>Medium:</label> <a data-toggle="modal" role="button" href="#medium_m">[Add New Medium]</a>
<select data-placeholder="Select Medium" class="select-full" tabindex="2" id="media" name="media">
<option value=""></option>
<?php
$quee = 'SELECT `media_id` , `mediatype` FROM `media` WHERE `bus_id_fk` = "'. $_SESSION['bus_id_fk'].'" order by `mediatype` asc';
$rs=$DBH->query($quee);
while($row = $rs->fetch_assoc()){
echo "<option value=$row[media_id]>$row[mediatype]</option>";
}
?>
</select>
</div>
if i click on [Add New Medium] , a model appears in which i can add value.
<div id="medium_m" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="icon-paragraph-justify2"></i> Add New Medium </h4>
</div>
<!-- Form inside modal -->
<form action="#" role="form" id="med1">
<div class="modal-body with-padding">
<div class="form-group">
<div class="row">
<div class="col-sm-9">
<label>First Medium</label>
<input type="text" name="fname" placeholder="Eugene" class="form-control">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Close</button>
<button type="submit" id = "m_btn" class="btn btn-primary">Submit form</button>
</div>
</form>
</div>
</div>
click on submit form (AJAX)
$(document).ready(function(){
$('#med1').submit(function(){
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: 'addmedium.php',
//data: formData.serialize()
data: $(this).serialize()
})
.done(function(data){
$('#response').html(data);
if(data.status == 'success'){
$("#divmedium").html(data);
}else if(data.status == 'error'){
alert("Error on query!");
}
})
.fail(function() {
// just in case posting your form failed
alert( "Posting failed." );
});
// to prevent refreshing the whole page page
return false;
});
});
addmedium.php
<?php
session_start();
INCLUDE './config/databases.php';
header('Content-type: application/json');
$loc= $_POST['fname'];
$busid=$_SESSION['bus_id_fk'];
$sql = "INSERT INTO media (mediatype,bus_id_fk)VALUES ( '$loc','$busid' )";
//echo $sql;
if ($DBH->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
// echo "Error: " . $sql . "<br>" . $DBH->error;
}
$response_array['status'] = 'success';
echo json_encode($response_array);
exit;
?>
Now the problem is
data getting inserted in the database but i am unable to refresh the
div,
After clicking on submit form model is not disappearing. i need to click on close or some where else besides model.
after clicking on Submit form , the div divmedium is disappearing.
Let me know what i am doing wrong.
I'll start from the end, if you won't mind.
after clicking on Submit form , the div divmedium is disappearing.
In your AJAX code $("#divmedium").html(data); you are replacing divmedium content with json_encode($response_array);
After clicking on submit form model is not disappearing. i need to click on close or some where else besides model.
I don't see any code that should close it. Try to add data-dismiss="modal"
data getting inserted in the database but i am unable to refresh the div
Same stuff as in 3rd question, check this and edit your AJAX success callback.

Ajax is not updating data

I've got a forum in which user is allowed to edit and delete only his comments, I've defined an "edit" button, that by a click of mouse brings down a modal, and in that modal user is allowed to get access to the data's he/she has been sent before, I've written an ajax to target these field and update them whenever the users clicks on "edit" button, code totally makes sense, but so far the functionality doesn't, to make it more clear, user clicks, modal comes down, whatever he/she has been posted will appear in fields, and there is an "edit" button at the bottom of modal, which is responsible for changing and updating data. here is the modal code :
<button id="btn-btnedit" class="btn btn-primary " data-toggle="modal" data-target="#myModal<?php echo $list['id']; ?>">
Edit <i class="fa fa-pencil-square-o"></i>
</button>
<!-- Modal -->
<div class="modal fade" id="myModal<?php echo $list['id']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<div class="container">
<form style="width: 550px;" action="" method="post" id="signin-form<?php echo $list['id']; ?>" role="form">
<input type="hidden" name="commentID" value="<?php echo $list['id']; ?>">
<div class="from-group">
<label for="title">Title: </label>
<input class="form-control" type="text" name="title" id="txttitle" value="<?php echo $list['title']; ?>" placeholder="Page Title">
</div>
<div class="from-group">
<label for="label">Label: </label>
<input class="form-control" type="text" name="label" id="txtlabel" value="<?php echo $list['label']; ?>" placeholder="Page Label">
</div>
<br>
<div class="from-group">
<label for="body">Body: </label>
<textarea class="form-control editor" name="body" id="txtbody" row="8" placeholder="Page Body"><?php echo $list['body']; ?></textarea>
</div>
<br>
<input type="hidden" name="editted" value="1">
<br>
<br>
<input type="submit" id="btnupdate" value="Edit">
</form>
</div>
</div>
as you can see I've assigned "editted" to my "name" attribute, which is later on used to call the query in the database, sql code is as below :
case 'postupdate';
if(isset($_GET['editted'])){
$title = $_GET['title'];
$label = $_GET['label'];
$body = $_GET['body'];
$action = 'Updated';
$q = "UPDATE posts SET title ='".$title."', label = '".$label."', body = '".$body."' WHERE id = ".$_GET['commentID'];
$r = mysqli_query($dbc, $q);
$message = '<p class="alert alert-success"> Your Post Is Succesfully '.$action.'</p>' ;
}
and here is the ajax code snippet;
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempUrl = "index.php?page=postupdate"+"&title="+tempTitle+"&label="+tempLabel+"&body="+tempBody+"&commentID=30&editted=1";
$.get(tempUrl);
});
I assume there is nothing advance about this segment of code, and i'm missing something very simple, any consideration is highly appreciated :)
This (untested code) may be similar to what you should do:
$('#btnupdate').click(function() {
var tempTitle = $('#txttitle').val();
var tempLabel = $('#txtlabel').val();
var tempBody = $('#txtbody').val();
var tempParams = {"page":"postupdate","title":tempTitle,"label":tempLabel,"body":tempBody,"commentID":30,"editted":1};
$.post("index.php",tempParams,function(data) {
alert(data);
});
});
UPDATE
Try ajax instead of get to see if some error occurs in the loading
$.ajax( {url:"index.php",data:tempParams,type: "POST"} ).done(function() {
alert( "success" );
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});`
UPDATE
Start testing if the click handler works then (just to be sure!):
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
UPDATE
Start testing if the script gets executed then:
alert("yes at least the script gets executed");
$('#btnupdate').click(function() { alert("yes at least the button was pressed"); });
If not you must have a javascript error somewhere.
https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers
If yes, your button does not get caught by JQuery (no idea why)
anyway it's got nothing to do with ajax or get!

Categories

Resources