j query updating div of drop-down after inserting data - javascript

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.

Related

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.

To display data in the fields in the modal retrieved from the mysql database

Friends I am submitting the form on clicking the submit button and simultaneously i am displaying the just submitted data in the modal.So as soon as i hit the submit button ,the data gets submitted and a modal appears with the data just submitted.Everything is working fine with my code but the only problem that the data does not gets displayed in the modal.
Here is the code for submitting the form-
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(msg){
$('input[type="text"], textarea').val('');
$('#entrysavedmodal').modal('show');
},
error: function(){
alert("failure");
}
});
});
Here is modal which gets displayed when i click on submit button-
<div id="entrysavedmodal" class="modal fade" role="dialog">
<div class="modal-dialog" style="width:1000px;">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Saved Entry</h4>
</div>
<div class="modal-body">
<form class="form-horizontal savedform" id="savedform">
<div class="form-group">
<label class="control-label col-xs-2">Date:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="datepreview" name="datepreview"
value = "<?php
include('db.php');
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$date = $rows['date'];
echo $date;
?>" readonly /> //this field does not show anything and none of the fields show any data.
</div>
<label class="control-label col-xs-2">v_no:</label>
<div class="col-xs-4">
<input type="text" class="form-control" id="v_nopreview" name="v_no" autocomplete="off" readonly /> //same problem
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-info" id="print" name="print" >Print</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
Date field does not show the date value from database and v_nopreview field also does not show anything.
I have tried to give as much details as possible but in case if you need anything then let me know.Please let me know why the data is not being displayed inside the input fields in modal.
Thanks in advance.
Edited part
Here is the data1_post.php code-
<?php
include('db.php');
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
echo "saved";
}
else
{
echo "not saved";
}
?>
As I understand, you expect execution of php code each time after js event. But PHP is a server-side language, it interprets only once, when you request the pages.
So your php code will load some content form DB after refreshing, then you clear input's value before displaying model and as it can't be executed again - you see empty modal.
I recommend you to return saved data from "data1_post.php" and than process it in success callback
UPDATE
if you want to present saved data, your php code would look like the following
include('db.php');
$response = ["success" => false];
$sql = "INSERT INTO `table1` (`date`, `v_no`, `name`,`narration`,`stk_y_n`)
VALUES ( '".$_POST['date']."','".$_POST['v_no']."', '".$_POST['user']."','".$_POST['narration']."', 'No')";
if ($conn->query($sql) === TRUE){
$sql = "SELECT `date` FROM tran ORDER BY id DESC limit 1";
$result = mysqli_query($conn,$sql);
$rows = mysqli_fetch_assoc($result);
$response = ["success" => true, "date" => $rows['date']];
}
header('Content-type: application/json');
echo json_encode($response);
and js
$("#savep").click(function(e){
e.preventDefault();
formData = $('form.pform').serialize() + '&'
+ encodeURI($(this).attr('name'))
+ '='
+ encodeURI($(this).attr('value'));
$.ajax({
type: "POST",
url: "data1_post.php",
data: formData,
success: function(response){
$('input[type="text"], textarea').val('');
if (response.success) {
$('#datepreview').val(response.date);
$('#entrysavedmodal').modal('show');
} else {
alert("failure");
}
},
error: function () {
alert("failure");
}
});
});

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!

How to Upload a file and save to DB using PHP, JavaScript, Bootstrap

everyone..
i've problem using javascript.
i want to make CRUD using Modal(bootstrap), PHP and javascript. but unfortunatelly til now i can't upload a file and save them to database. i have 3 files (index, form, javascript, process) here is my code :
for modal (index) :
<div id="dialog-admin" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel"></h3>
</div>
<!-- tempat untuk menampilkan form admin -->
<div class="modal-body"></div>
<div class="modal-footer">
<button class="btn btn-danger" data-dismiss="modal" aria-hidden="true">Batal</button>
<button id="simpan-admin" class="btn btn-success">Simpan</button>
</div>
this code for form file :
<form class="form-horizontal" id="form-admin" enctype="multipart/form-data" >
<div> ... bla bla bla.. field.. </div>
<div class="control-group">
<label class="control-label" for="ava">Image</label>
<div class="controls">
<input type="file" id="ava" name="ava" value="<?php echo $ava ?>" required="required" />
</div>
</div>
this code for javascript :
$("#simpan-admin").bind("click", function(event) {
var url = "admin-proses.php";
// mengambil nilai dari inputbox, textbox dan select
var v_username = $('input:text[name=username]').val();
var v_email = $('input:text[name=email]').val();
var v_pass = $('input:text[name=pass]').val();
var v_ava = $('input:file[name=ava]').val();
// mengirimkan data ke berkas transaksi admin-proses.php untuk di proses
$.post(url, {username: v_username, email: v_email, pass: v_pass, ava:v_ava, id: id} ,function() {
// tampilkan data admin yang sudah di perbaharui
// ke dalam <div id="data-admin"></div>
$("#data-admin").load(main);
// sembunyikan modal dialog
$('#dialog-admin').modal('hide');
// kembalikan judul modal dialog
$("#myModalLabel").html("Tambah Data Admin");
});
});
and this code for file process :
require 'dbase.php';
$id = $_POST['id'];
$username = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$imageName = $_FILES['ava']['name'];
$imageSize = $_FILES['ava']['size'];
$imageError = $_FILES['ava']['error'];
if ($imageSize > 0 || $imageError == 0){
$move = move_uploaded_file($_FILES['ava']['tmp_name'], '../uploads/ava/'.$imageName);
if ($move){
echo 'success';
} else {
echo 'failed';
}
} else {
echo 'failed to save file to DB : '.$imageError;
}
mysql_query("INSERT INTO tb_admin VALUES('','$username','$email','$pass','$imageName')") or die (mysql_error());
could you to help me ?
thank
Regard
check whether the post has been done properly in jquery. do step by step debugging.Be sure of getting all input field values.
I would suggest that you should go to this link by W3Schools:
http://www.w3schools.com/php/php_file_upload.asp
It covers all the basics of file uploading.
For Database, go through this:
http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/uploading-files-to-mysql-database.aspx

codeIgniter Javascript alert with success message on click ok page refresh

I have a code like this:
<div class="alert alert-success">
<a class="close" data-dismiss="alert">×</a>
<?php
$message = "Your Upload was successful";
if((isset($message))&&($message!='')){
echo '<script> alert("'.str_replace(array("\r","\n"), '', $message).'"); </script>';
}
redirect($this->uri->uri_string()); //refresh page
?>
I want to show this success alert message and then if the user click on OK it will refresh the browser. In my case it is just refreshing the browser.
What will be the best way to do it.
Thanks a lot in advance.
To make your code work as expected, you have to write the refresh function in Javascript instead of using PHP redirect function like the below:
<?php
$message = "Your Upload was successful";
if ((isset($message)) && ($message != '')) {
echo '<script>
alert("'.str_replace(array("\r","\n"), '', $message).'");
location.reload(true);
</script>';
}
?>
If you want to use Bootstrap modal, try this:
<?php
$message = "Your Upload was successful";
if ((isset($message)) && ($message != '')):
?>
<div class="modal" id="alert-dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Alert</h4>
</div>
<div class="modal-body">
<?php echo $message; ?>
</div>
<div class="modal-footer">
<button data-dismiss="modal" type="button" class="btn btn-primary">OK</button>
</div>
</div>
</div>
</div>
<script>
$(function() {
$('#alert-dialog').modal('show').on('hidden.bs.modal', function () {
location.reload(true);
});
});
</script>
<?php endif; ?>
I'm not sure this is possible with a standard alert box, you can do it with a confirm.
e.g.
var con = confirm('Are you sure');
if (con == true) {
//means the user clicked on `OK`
//refresh the page
} else {
//means the user clicked `Cancel`
}
Alternatively you could use a customized alert box, to find a suitable one just search on google.

Categories

Resources