codeIgniter Javascript alert with success message on click ok page refresh - javascript

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.

Related

Bootstrap modal popup upon failed login

I have a login page (login.html) that calls a php with POST method to valid login credentials, which works just fine. If the email an password are incorrect, then in my current implementation, an alert pops up and the page reloads. I would like to know how to activate a modal instead of said popup.
<div id="myModal" class="modal fade">
<div class="modal-dialog modal-confirm">
<div class="modal-content">
<div class="modal-header">
<div class="icon-box">
<i class="material-icons"></i>
</div>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body text-center">
<h4>Ooops!</h4>
<p>Something went wrong. File was not uploaded.</p>
<button class="btn btn-success" data-dismiss="modal">Try Again</button>
</div>
</div>
</div>
</div>
Complete PHP File:
<?php
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$conn = new mysqli('localhost','root','','rm');
if($conn->connect_error){
die('Connection Error: '.$conn->connect_error);
}
else{
$sql = "select * from superfan where email='".$email."' and password='".$pwd."' ";
$result = mysqli_query($conn,$sql);
$records = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if ($records==0)
{
echo '<script type="text/javascript">';
echo '$(document).ready(function() {';
echo '$("#myModal").modal("show");';
echo '});';
echo '</script>';
}
else
{
header('location:index.html');
}
mysqli_close($conn);
}
?>

How to submit data from a modal?

These buttons are echo out from the database,
When the user clicks onto the button, the user will get to see a pop out before submitting it.
This is my code,
$con = getDbConnect();
$day = date("l");
if (mysqli_connect_errno($con)) {
"Failed to connect to MySQL: " . mysqli_connect_error();
} else {
$result = mysqli_query($con, "SELECT * FROM timetableschedule WHERE day='" . $day . "'");
while ($schedule = mysqli_fetch_array($result)) {
?>
<div class="col-md-3">
<button class="btn btn-warning" data-toggle="modal" data-target="#myModal" schedule="
<?php
echo "<br/>";
echo $schedule['academicInstitution'] . "<br />";
echo $schedule['startTime'] . "-" . $schedule['endTime'] . "hrs<br />";
echo "<br/>";
?>">
<?php
echo "<br/>";
echo $schedule['academicInstitution'] . "<br />";
echo $schedule['startTime'] . "-" . $schedule['endTime'] . "hrs<br />";
echo "<br/>";
?>
</button>
</div>
<div class="modal fade" id="myModal" 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" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Insert Today's Activity</h4>
</div>
<div class="modal-body">
<p class="activity"></p>
<p>Click on the submit button if the above infomation is correct.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<a class="btn btn-primary btn-ok">Submit</a>
</div>
</div>
</div>
</div>
<script>
$('#myModal').on('show.bs.modal', function(e) {
$(this).find('.btn-ok').attr('schedule', $(e.relatedTarget).attr('schedule'));
$('.activity').html('You have selected: <strong>' + $(this).find('.btn-ok').attr('schedule') + '</strong>');
});
</script>
<?php
}
mysqli_close($con);
}
?>
</div>
Once the user click onto the submit button, the "academicInstitution" and "duration" will be entered into a database called, "myRecord".But I do not know how to connect the submit button to the database.
If you need to stay on the same page, make an ajax post call to a server side php script: http://api.jquery.com/jquery.post/
This way you will be able to execute the query you want on the server
If you can accept to reload the page, you may simply use an html form
This question may be useful for you: jQuery Ajax POST example with PHP
Note that you don't necessarily need the form element if you choose the ajax post approach

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.

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

Send data from controller to pop up modal using bootstrap codeigniter

Hello I was going to make a forgot password function using modal bootstrap..
before I have made it without pop up modal.. I do know how to pass the data..
but now I don't know how to send data from controller to pop up modal..
Here is my code:
<div id="forgot-password" class="modal hide fade in" style="display: none; ">
<div class="modal-header" style="background-color:#f39c12; color:#fff;">
<h3 id="helpModalLabel"> Forgot Password</h3>
</div>
<div class="modal-body">
<form class="form-horizontal well" method="post" id="forgot_form" action="<?php echo base_url(); ?>forgotpassword/doforget">
<fieldset>
<legend></legend>
<div class="control-group">
<?php if( isset($info)): ?>
<div class="alert alert-block alert-success fade in" id="alert-message" >
<img src="<?php echo base_url("assets")?>/image/Done.png" width="20px" height="20px">
<button type="button" class="close" data-dismiss="alert">×</button>
<?php echo($info) ?>
</div>
<?php elseif( isset($error)): ?>
<div class="alert alert-block alert-error fade in" id="alert-message">
<img src="<?php echo base_url("assets")?>/img/icon/warning.png" width="20px" height="20px">
<button type="button" class="close" data-dismiss="alert">×</button>
<?php echo($error) ?>
</div>
<?php endif; ?>
<label for="Username" class="control-label span3" >Username</label>
<div class="controls">
<input class="span3" type="text" id="Username" name="Username" placeholder="Input the Registered Username" name="Username"/>
<span id="UsernamehelpText"></span>
</div>
</div>
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="Send Password" name="submitbtn"/>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
Close
</div>
</div>
Controller
public function forget()
{
if (isset($_GET['info'])) {
$data['info'] = $_GET['info'];
}
if (isset($_GET['error'])) {
$data['error'] = $_GET['error'];
}
$page_content["page_title"] = "";
$page_content["title"] = "Forgot Password";
$page_content["icon_title"] = "home";
$menu_params["sub_current_navigable"] = "";
$page_content["navmenu"] = $this->load->view("nav_menu", "", true);
$page_content["menu"] = $this->load->view("main_menu_login", $menu_params, true);
if(isset($data)){
$page_content["content"] = $this->load->view("forgotpassword",$data, true);
}else{
$page_content["content"] = $this->load->view("forgotpassword","", true);
}
$this->load->view("template/main_template", $page_content);
}
public function doforget()
{
$this->load->helper('url');
$username= $_POST['Username'];
$checkuser = $this->forgotpassword_model->getusername($username);
print_r($checkuser);
$getemail = $this->forgotpassword_model->getemail($username);
if(!empty($checkuser))
{
$user = $checkuser['0'];
$email = $getemail['0'];
if(!empty($email['email']))
{
$this->sendpassword($user,$email);
$info= "Password has been reset and has been sent to email id: ". $email['email'];
echo $info;
redirect('login/forget?info='.$info, 'refresh');
}else{
$error = "You don't have email, please contact your admin library ";
echo $error;
redirect('login/forget?error=' . $error, 'refresh');
}
}else
{
$error= "You have input wrong username ";
redirect('login/forget?error=' . $error, 'refresh');
echo $error;
}
}
Can someone help me to migrate this to pop up modal? do I need ajax?
I also want to send the error message to pop up modal..
now I'm using 'login/forget?error=' . $error, 'refresh')
Is it possible for me for still using this?
EDIT
to pass your data from Controller to bootstrap modal you need json. to do that try this:
in your controller
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode( $your_data_array ));
this code change your array data to JSON and then send it to whatever you call this method. with your AJAX call this method and in success get this data parse it with JSON.pars() method and put them to your modal.
In CodeIgniter, before using a model you need to load it. For example you write a model in model folder with name userAuth. Creating a model is as follows:
class UserAuth extends CI_Model{
//your methods
}
In your model you can have some method like forgetPass that will give you an array or data like:
public function forgetPass($dataArray){
//your Code
}
OR
public function forgetPass( $data1, $data2, $data3){
//your code
}
When you want to use your model in a controller method you can load it handily in your controller method or load it in controller constructor like this:
$this->load->model('userAuth');
When you need a method like that, according to the example given you can pass your data to it as:
$this->userAuth->forgetPass($data);
addition:
In CodeIgniter, we have in-built methods to get POST / GET data. They are easy to use and safer. You can use:
$variable = $this->input->post('your_input_name');
OR
$variable = $this->input->get('your_key');
Instead of $_GET['your_key'] or $_POST['your_input_name']

Categories

Resources