Send data from controller to pop up modal using bootstrap codeigniter - javascript

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']

Related

Display data from database into existing textbox when click submit button

I have a problem. I want to display the data from database in the existing textbox but unfortunately, it does not display the result. My if else loop is not working. I don't want to display the textbox only if the button is click. I want the result display inside the existing textbox after the search button click.
here is my code html code:
<div class="row">
<div class="column middle2" style="background-color:transparent">
<div class="container"><br><br>
<div class="row">
<div class="col-01">
<label for="icno"><b>IC No :</b></label>
</div>
<div class="col-02">
<form action="" method = "POST">
<div class="input-group">
<input type="text" name="icpayer" value = "<?php if(isset($_POST['icpayer'])){echo $_POST['icpayer'];} ?>" class="form-control bg-light border-0 small" >
<div class="input-group-append">
<button type="button" id = "searchValue" class="btn btn-primary">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-01">
<label for="name"><b>Payer Name :</b></label>
</div>
<div class="col-02">
<input type="text" id="payername" name="payername" >
</div>
</div>
</div>
</div>
</div>
here is my javascript code:
$('#searchValue').on('click', function(){
$.ajax({
type : "POST",
url : 'searchIcPatient.php',
success : function(data)
{
$('#payername').val(data);
},
});
});
here is my php code:
<?php
if(isset($_POST['icpayer'])){
$searchValue = $_POST['icpayer'];
$query="SELECT * FROM ptregistration WHERE patientic = '$searchValue'";
$result = mysqli_query($con, $query) or die(mysqli_error($con,$query));
while($row = mysqli_fetch_array($result)){
echo $row['patientname'];
}
}else{
echo "No Record Found";
} ?>
my problem is when I click the search button, the result display "No Record Found" even there is similar data in the database. please help me as I am a beginner.
You should modify the ajax request to send the icpayer parameter. I do not use jQuery so I'm sure a better jQuery method exists but you can do so like this:
$('#searchValue').on('click', function(){
$.ajax({
type : "POST",
data:{
icpayer:document.querySelector('input[name="icpayer"]').value
},
url : 'searchIcPatient.php',
success : function(data)
{
$('#payername').val(data);
},
});
});
The PHP was exposing your database to SQL injection (potentially) so you should use Prepared Statements
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['icpayer'] ) ){
include($_SERVER['DOCUMENT_ROOT'].'/mhcsys/include/config.php');
$icpayer=filter_input( INPUT_POST, 'icpayer', FILTER_SANITIZE_STRING );
$sql='select `patientname` from `ptregistration` where `patientic`=?';
$stmt=$con->prepare($sql);
$stmt->bind_param('s',$icpayer);
$stmt->execute();
$stmt->store_result();
$rows=$stmt->num_rows();
if( $rows > 0 ){
$stmt->bind_result( $patientname );
while( $stmt->fetch() )echo $patientname;
}else{
echo 'No Record Found';
}
}
?>

Preventing bootstrap modal from disappearing in case validation failure using PHP after submit button is clicked

My question is how do I stop modal from closing, on two occasions, when user clicks the sign up button:
if the inputs are invalid? and display PHP error message
inputs are valid and to display PHP success message for couple of seconds before closing modal?
for the first case if I reopen the modal I can see the validation error messages which are displayed by PHP.
I have checked this similar question but haven't figure it out how to do it in my case yet so any help will be much appreciated. I would like to fully understand what is going on and what I am doing.
So far after reading here and there I noticed that this can probably be achieved by:
JQuery / JavaScript to do the form validation and not to use PHP
some people suggested using iframe
Is there a way to use the PHP code below and display error / success messages from this code? or it has to be done via JQuery/JS?
My PHP with HTML code
<?php
ob_start();
include('header.php');
include_once("db files/db_connect.php");
if(isset($_SESSION['user_id'])) {
header("Location: index.php");
}
$error = false;
if (isset($_POST['signup'])) {
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']);
if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$uname_error = "Name must contain only alphabets and space";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$error = true;
$email_error = "Please Enter Valid Email ID";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($password != $cpassword) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (!$error) {
if(mysqli_query($conn, "INSERT INTO users(user, email, pass) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
$success_message = "Successfully Registered!";
} else {
$error_message = "Error in registering...Please try again later!";
}
}
}
?>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="registrationFormLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content" >
<div class="modal-header">
<h5 class="modal-title" id="registrationFormLabel">Register</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- REGISTRATION FORM -->
<div class="container">
<div class="form-row">
<div class="col">
<form onsubmit="return validateForm()" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
<fieldset>
<legend>Sign Up</legend>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Enter Full Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($uname_error)) echo $uname_error; ?></span>
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" placeholder="Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($email_error)) echo $email_error; ?></span>
</div>
<div class="form-group">
<label for="name">Password</label>
<input type="password" name="password" placeholder="Password" required class="form-control" />
<span class="text-danger"><?php if (isset($password_error)) echo $password_error; ?></span>
</div>
<div class="form-group">
<label for="name">Confirm Password</label>
<input type="password" name="cpassword" placeholder="Confirm Password" required class="form-control" />
<span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
</div>
<div class="form-group text-center">
<input id="modalSubmit" type="submit" name="signup" value="Sign Up" class="btn btn-primary" formnovalidate />
</div>
</fieldset>
</form>
<span class="text-success"><?php if (isset($success_message)) { echo $success_message; } ?></span>
<span class="text-danger"><?php if (isset($error_message)) { echo $error_message; } ?></span>
</div><!-- / col -->
</div><!-- / form-row -->
<!-- already registered row -->
<div class="row">
<div class="col text-center">
Already Registered? Login Here
</div>
</div> <!-- / already registered row -->
</div><!-- / REGISTRATION FORM container-->
</div><!-- / Modal body div -->
</div>
</div>
</div><!-- / Modal -->
My modal opens when the user clicks the button on index page and here is the JQuery code
$(document).ready(function(){
$("#myBtn").click(function(){
$("#myModal").modal();
});
});
Add below PHP script after end of document (/html) before script tag
<?php
if ($error) {
echo '<script>$("#myModal").modal("show");</script>';
} else {
echo '<script>$("#myModal").modal("hide");</script>';
}
?>
Invalid:
You can stop the submit button from submitting if the inputs are invalid.
To stop submit use the code
$(':input[type="submit"]').prop('disabled', true);
To show modal
$("#myModal").modal('show');
To enable submit again, when modal is closed due to error, use the code
(You will want to enable it again so the user can try again)
$("#myModal").on('hidden.bs.modal', function (e) {
$(':input[type="submit"]').prop('disabled', false);
});
For the validation I would do it this way (add a success variable):
if (!$error) {
if(mysqli_query($conn, "INSERT INTO users(user, email, pass) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
$success = 1;
} else {
$success = 2;
}
And then call it like this:
<?php if($success == 1){ ?>
<script>
$(document).ready(function() {
$("#yoursuccessmodal").modal('show');
});
</script> <?php } ?>
You can then choose to add a fade to it, or have the user click it away.
The modal will then show AFTER the submition has been sent.
This better work, as I have used it this way in my project as well and it works like a charm for me.

JavaScript Username authentication

The following represent my registration link which lead to open a modal:
Register Here
The following represents the code for my modal dialog:
<div class="modal fade" id="registermodal" role="dialog" style="overflow: scroll;">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal" name="f2" id="regisform" method="post" onsubmit="return false;" role="form">
<div class="modal-header">
<h4>Registration<button class="close" data-dismiss="modal">×</button></h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="inputusername3" class="col-sm-2 control-label">Username</label>
<div class="col-lg-8">
<input type="text" name="txtusername" class="form-control" id="inputusername3" placeholder="username">
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" name="submit" id="regisBtn" class="btn btn-primary" value="Registration">
<a class="btn btn-default" data-dismiss="modal">Cancel</a>
</div>
</form>
</div>
</div>
</div>
The below represent the JavaScript Code:
$(document).ready(function(){
$("#regisBtn").click(function(){
var username1=$("#inputusername3").val();
$.post("registercheck.php", {username:username1}, function(result){
if(result==='true')
alert("true");
else
alert("false");
});
});
});
The below represent my php code:
<?php
$username1=$_POST['username'];
$con= mysql_connect("localhost","root","");
mysql_select_db("onlineshop",$con);
$query1= mysql_query("select username from users where username=$username1",$con);
if(mysql_num_rows($query1)==1){
echo 'false';
}else{
mysql_query("insert into users(username)values ('".$username1."')",$con);
session_start();
$_SESSION['username']=$username1;
echo 'true';
}
There is error in mysqli_num_rows() shows that it expects parameter 1 to be resource, Boolean given in something like that
I dont knw why my code is not working. please help me with my code to check whether the username is exists or not?
You have 4 problems with your code. First, you are using mysql_* functions. Use mysqli_* instead, mysql_* is deprecated. Second, you are vulnerable to SQL injection. This is fixed below by using mysqli_real_escape_string. Consider using PDO instead. Third, your select query is malformed - any string in the query must be wrapped in single quotes. Fourth, in a couple of mysql_* function calls, your database link is the last parameter. It should always be the first parameter in the call.
<?php
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con, "onlineshop");
$clean_username1 = mysqli_real_escape_string($con, $_POST['username']);
$query1 = mysqli_query($con, "select username from users where username = '".$clean_username1."'");
if (mysqli_num_rows($query1) == 1){
echo 'false';
} else {
mysqli_query($con, "insert into users (username) values ('".$clean_username1."')");
session_start();
$_SESSION['username'] = $_POST['username'];
echo 'true';
}

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