Show a modal with receipt after submit form (Codeigniter) - javascript

My target is, after I submit the form, there'll be a modal after reload that shows the transaction details. I have made a next page transaction details, however, it is much better to do the receipt php on onload modal after submission. But I don't know how to start. I provided a screenshot below of my current work. Any help will be appreciated. Thank you
View:
<button type="button" data-id="<?php echo $rows->userID; ?>" data-firstname="<?php echo $rows->firstname; ?>" class=" showmodal btn btn-success btn-sm text-bold " data-toggle="modal" data-target="#fundModal"><i class="fas fa-hand-holding-usd mr-1"></i> FUND </button> // This button shows modal when clicked
//This is my modal for transferring fund
<div class="modal fade" id="fundModal" tabindex="-1" role="dialog">
<div class="modal-dialog " role="document">
<div class="modal-content">
<div class="modal-header bg-green">
<h5 class="modal-title text-bold" id="exampleModalLabel">Fund</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body bg-white text-center">
<label><h3>Transfer fund:</h3></label>
<br>
<!-- FORM -->
<div id="errorMessage" style="color: red; display: none; font-size: 11px"></div>
<form method="POST" action="<?php echo site_url('network/form_validation');?>">
<div class="input-group input-group-sm" style="width: 100%" >
<input type="hidden" id="usertransferid" name="userID">
<input type="hidden" id="firstname" name="receiptname" value="<?php echo $rows->firstname; ?>">
<div class="col-lg-12" >
<input type="text" placeholder="Enter Amount" name="amount" autocomplete="new-amount" value="" class="form-control number" id="box" >
<br>
<?php echo $this->session->flashdata('warning'); ?>
<input type="password" placeholder="Enter Password" autocomplete="new-password" name="fundpass" class="form-control" id="password" required ">
<br>
<!-- buttons -->
<input type="submit" class="btn btn-success text-bold" name="save" id="insert" value="Transfer">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Controller:
public function form_validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$this->load->library('form_validation');
$this->form_validation->set_rules('fundpass', 'fundpass', 'callback_password_check');
if($this->form_validation->run() == false) {
echo '<script>alert("Invalid input of Password!");</script>';
redirect('network/agents', 'refresh');
}
else {
if($this->form_validation->run())
{
$ref= $this->session->userdata('uid') + time ();
$id = $this->input->post('userID');
$fname = $this->input->post('receiptname');
$pData = array(
'userID' => $id,
'transactionSource' => 'FR',
'refNumber' => 'FI' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"in",
);
$this->networks->fundin($pData);
$ref= $this->session->userdata('userID') + time ();
$data1 = array(
'userID' => $this->session->userdata('uid'),
"transactionSource" => 'FR',
"refNumber" => 'FO' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"out",
);
$this->networks->insert_data($data1);
// return json_encode($data1);
$_SESSION["amount"] = $this->input->post("amount");
$_SESSION["receivedID"] = $id;
$_SESSION["receiptFName"] = $fname;
$_SESSION["reference"] = $this->input->post("refNumber");
redirect(base_url() . "network/receipt");
}
else
{
$this->index();
}
}
}
public function password_check($fundpass)
{
$id = $this->session->userdata('uid');
if($this->session->userdata('password')!== md5($fundpass)) {
$this->form_validation->set_message('password_check', 'The {field} does not match');
return false;
}
return true;
}
Model:
function fundin($data)
{
// Fund in
$id = $this->input->post('userID');
$sqlInsertLedger = "INSERT INTO transaction_ledger (transactionSource, transType, refNumber, userID, amount, currentBalance, previousBalance, remarks, createdBy)
select '".$data['transactionSource']."', '".$data['transType']."', '".$data['refNumber']."', ".$data['userID'].", ".$data['amount'].", sum(TU.currentPoints + ".$data['amount'].") as totalPoints, TU.currentPoints,
'funded by agent', '".$this->session->userdata('uid')."'
from users TU where TU.userID=?";
$Q = $this->db->query($sqlInsertLedger, $data['userID']);
//update user table
$sqlUpdate = "update users set currentPoints = currentPoints + ? where userID = ?";
$Q = $this->db->query($sqlUpdate, array($data['amount'], $data['userID']));
}
function insert_data($data1)
{
// fund out
$sql1 = "select * from transaction_ledger where userID = ? order by ledgerID desc limit 0,1";
$Q1 = $this->db->query($sql1, $data1['userID']);
$R1 = $Q1->row_array();
$ref= $this->session->userdata('userID') + time ();
$idata1 = array(
'userID' => $data1['userID'],
'transactionSource' => 'FR',
'transType' => 'out',
'refNumber' => 'FO' . $ref,
'amount' => $data1['amount'],
'currentBalance' => $R1['currentBalance'] - $data1['amount'],
'previousBalance' => $R1['currentBalance'],
'remarks' => 'transfer fund to agent',
);
$this->db->insert('transaction_ledger', $idata1);
$sqlUpdate = "update users set currentPoints = '".$idata1['currentBalance']."', dateUpdated = '".date('Y-m-d h:i:s')."'where userID = ?";
$this->db->query($sqlUpdate, $idata1['userID'] );
}

You can programmatically open the bootstrap modal when document ready
Just like
$(document).ready(function(){
$("#fundModal").modal('show');
});
</script>
I would suggest to do with ajax call for better user experience.
$( "#formId" ).on('submit', function(e){
e.preventDefault();
let $form = $(this);
$.post( 'post-url-here', $form.serialize(), function(result) {
var result = JSON.parse(result);
if( result.status == 'success' ) {
$("#fundModal").modal('show');
}
});
});

Related

Modal box does not close on successfull ajax return

I have a modal window that pops up whenever a screen is ideal for 3 minutes. It asks for a PIN to be entered and there is a Continue button on that to be clicked after the PIN is entered in it. On using this Continue button, an insert is made in a database table. Now my problem here is on entering the PIN and clicking on Continue button, the modal does not hides or closes itself. Although the database insertion is done but the modal does not hides. What can be possibly going wrong in this. Any suggestion will be highly helpful. My code,
<div class="modal fade" id="myModal" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<!-- Modal content-->
<form name="frmActive" id="frmActive" action="" method="post">
<div class="modal-content" style="height:250px;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ideal Time activation</h4>
</div>
<div class="modal-body">
<p>Please enter activation <b>PIN</b><font color="red">*</font><br>
<p id="msg" style="color:#F00;"></p>
<input type="password" name="pin" id="pin" value="" maxlength="4" onKeyUp="checkNumber(this)" class="form-control" placeholder="Enter Pin">
<input type="hidden" id="inactiveTime">
<p style="font-size:11px"><b><font color="red">*</font><font color="grey"><b>PIN</b><i> is mentioned in your welcome email.</font></i></b></p><br>
</div>
<div class="modal-footer">
<button type="button" id="btnSubmit" name="submit" value="submit" class="btn btn-success"><i class="glyphicon glyphicon-floppy-disk"></i> Continue</button>
<input type="hidden" id="module_id" value="<?php echo $moduleId ; ?>">
<input type="hidden" id="chapter_id" value="<?php echo $chapterId ; ?>">
</div>
</div>
</form>
</div>
</div>
jQuery("#btnSubmit").on("click", function(){
var pin = jQuery("#pin").val();
var chapter_id = jQuery("#chapter_id").val();
var module_id = jQuery("#module_id").val();
var nowDate = jQuery.now();
var inactiveTime = jQuery("#inactiveTime").val();
var seconds = (nowDate - inactiveTime) / 1000;
var formData = new FormData();
formData.append("pin", pin);
formData.append("seconds", seconds);
formData.append("module_id", module_id);
formData.append("chapter_id", chapter_id);
$.ajax({
url: "processActivation.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(result){
if(result['status'] == 'active')
{
jQuery('#myModal').modal('hide');
}
else
{
$("#msg").html(result) ;
}
}
});
});
And processActivation.php,
<?php
$uid = $_SESSION['session_user_id'];
$dobCheck = $db->idToField("tbl_user", "dob", $uid);
$dob = explode("-", $dobCheck);
$pin = $_REQUEST['pin'];
$moduleId = $_REQUEST['module_id'];
$chapterId = $_REQUEST['chapter_id'];
$time_taken = $_REQUEST['seconds'];
$created = date("Y-m-d h:i:s");
if($pin != $dob[0])
{
echo "Please enter valid PIN."; die;
}
else
{
$dataactivation = array("user_id"=>$uid, "module_id"=>$moduleId, "chapter_id"=>$chapterId,"time_taken"=>$time_taken, "created"=>$created);
$db->query_insert("tbl_activation", $dataactivation);
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
}
?>
I want to know if
header('Content-Type: application/json', true, 200);
echo json_encode(array('status' => 'active'));
exit();
is the right way?? Because all of the above operations are being performed correctly and upon that console.log(result) does not shows up anything. Something wrong with the above couple of lines. Very helpful if somebody points out the error in this.
Use the hide function from jQuery.
jQuery('#myModal').hide();
As I know modal('hide') is used for bootstrap modals.
A quick fix maybe, instead of doing
echo json_encode(array('status' => 'active')); and if(result['status'] == 'active')
do
echo "active"; and if(result == 'active')
Use
jQuery('#myModal').toggle().click();
instead of
jQuery('#myModal').modal('hide');

Codeigniter upload image file with array field name

I'm quite new to the codeigniter library and function. Recently i had a form that had a few dynamic input field to be submit and insert into database for recording purpose.
The image upload file field was dynamically created if user click "+" button, and i was using array name as the name for the input field. However when i trying to call the controller to upload the file or insert with the array field name, it keep prompted me 'You did not select a file to upload'.
If i change the image field's input name to only 'reg_photo' and the do upload field name to 'reg_photo' then everything working fine but that is not i wanted because i wanted to upload it based on the dynamic input array.
I did try to look around the solution at stackoverflow and google but after i try and none of it could help me.
Here are my Controller to do the upload :
//Upload Picture Configuration
$config['upload_path'] = './uploads/profile_picture/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 1920;
$config['max_height'] = 1080;
$this->load->library('upload', $config);
//Check and get the Areas list
$areaList = $this->input->post('areas', true);
$finalSeparator = $areaList;
$resultArea = "";
foreach ($finalSeparator as $i => $a) {
if (next($finalSeparator )) {
$resultArea .= $a.','; // Add comma for all elements instead of last
}
else
{
$resultArea .= $a;
}
}
if ($this->input->post('reg_name')) { // returns false if no property
//Get Last Inserted District ID
$district = "";
$failedUploadNameList = "";
$photoPath = "";
$data = array(
'district_code' => $this->input->post('reg_district_2', true),
'district_country' => '',
);
$this->db->set('district_registered_date', 'NOW()', FALSE); //Submit current date time
if($this->Registerlanguage_admin_model->register_district($data))
{
$district = $this->db->insert_id(); //Last Get ID
$name = $this->input->post('reg_name', true);
$year1 = $this->input->post('reg_year1', true);
$year2 = $this->input->post('reg_year2', true);
$nickname = $this->input->post('reg_nickname', true);
$photo = $this->input->post('reg_photo', true);
foreach ($name as $i => $a) { // need index to match other properties
//Check to whether can upload image or not
if ( ! $this->upload->do_upload($photo[$i]))
{
$error = array('error' => $this->upload->display_errors());
foreach($error as $q)
{
$failedUploadNameList .= $q;
}
}
else
{
$data = array('upload_data' => $this->upload->data('file_name'));
foreach($data as $a)
{
$photoPath = $config['upload_path'].$a;
}
}
$data = array(
'area_district_id' => $district,
'area_name' => $resultArea,
'area_language' => $this->input->post('reg_language', true),
'area_year_1' => isset($year1[$i]) ? $year1[$i] : '',
'area_year_2' => isset($year2[$i]) ? $year2[$i] : '',
'area_leader_name' => isset($name[$i]) ? $name[$i] : '',
'area_leader_nickname' => isset($nickname[$i]) ? $nickname[$i] : '',
'area_leader_photo' => $photoPath
);
$this->db->set('area_registered_date', 'NOW()', FALSE); //Submit current date time
if (!$this->Registerlanguage_admin_model->register_area($data)) {
// quit if insert fails - adjust accordingly
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('index.php/language_admin/index');
}
}
}
else{
// don't redirect inside the loop
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('index.php/language_admin/index');
}
//Redirect back once all successfully insert
$this->session->set_flashdata('msg','<div class="alert alert-success text-center">You are Insert Successfully!</div>'.$failedUploadNameList);
redirect('index.php/language_admin/index');
}
else{
// don't redirect inside the loop
$this->session->set_flashdata('msg','<div class="alert alert-danger text-center">Oops! Error. Please try again later!!!</div>');
redirect('index.php/language_admin/index');
}
Here are my view code :
<?php $attributes = array("name" => "registerdistrictform");
echo form_open_multipart("index.php/registerlanguage_admin/registerDistrict", $attributes);?>
<div class="panel panel-default">
<div class="panel panel-info">
<div class="panel-body panel-group">
<div class="form-group">
<input class="form-control" name="reg_language" type="hidden" value="Japanese" />
<label for="concept" class="col-sm-3 control-label">District :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_district_1" placeholder="Ex : District 3500" type="text" value="<?php echo set_value('reg_district_1'); ?>" required/>
<span class="text-danger"><?php echo form_error('reg_district_1'); ?></span><br/>
<input class="form-control" name="reg_district_2" placeholder="Ex : 3500" type="text" value="<?php echo set_value('reg_district_2'); ?>" required/>
<span class="text-danger"><?php echo form_error('reg_district_2'); ?></span><br/>
</div>
</div>
<div class="form-group">
<label for="concept" class="col-sm-3 control-label">Area :</label>
<div id="areaContainer">
<div class="col-sm-6">
Area Record #0<input class="form-control" name="areas[]" placeholder="Your Language" type="text" value="" required/>
</div>
<div class="col-sm-3">
+<br/>
</div>
</div>
</div>
</div>
</div>
<div id = "profileContainer">
<div class="panel panel-danger">
<div class="panel-heading">Profile #0</div>
<div class="panel-body panel-group">
<div class="form-group">
<label for="concept" class="col-sm-3 control-label">Years :</label>
<div class="col-sm-4">
<input class="form-control" name="reg_year1[]" placeholder="2015" type="text" value="" required/>
</div>
<div class="col-sm-1">
<i class="fa fa-arrow-right" aria-hidden="true" ></i>
</div>
<div class="col-sm-4">
<input class="form-control" name="reg_year2[]" placeholder="2017" type="text" value="" required/><br/>
</div>
</div>
<div class="form-group">
<label for="concept" class="col-sm-12 control-label"><u>District Governer</u></label><br/>
<label for="concept" class="col-sm-3 control-label">Name :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_name[]" placeholder="Your Language" type="text" required/><br/>
</div>
<label for="concept" class="col-sm-3 control-label">Nickname :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_nickname[]" placeholder="English" type="text" required/><br/>
</div>
<label for="concept" class="col-sm-3 control-label">Photo :</label>
<div class="col-sm-9">
<input class="form-control" name="reg_photo[]" type="file" required/><br/>
</div>
</div>
<div class="pull-right">
+
</div>
</div>
</div>
</div>
<div class="panel-body panel-group">
<div class="form-group">
<div class="col-sm-1 text-left">
<button name="submit" type="submit" class="btn btn-info btn-lg" >Submit</button>
<!-- <button name="cancel" type="reset" class="btn btn-info">Cancel</button>-->
</div>
</div>
</div>
</div>
<?php echo form_close(); ?>
</div>
The 'reg_photo[]' are dynamically insert into HTML if user press the '+' button, so if i change to 'reg_photo' which is not dynamic anymore then it work, what should i do if i wanted to use the 'reg_photo[]' as a field name to upload my file? Please guide me through this. Thank! :)
/*
* Code above omitted purposely
* In your HTML form, your input[type=file] must be named *upl_files[]*
*/
/*
* Uploads multiple files creating a queue to fake multiple upload calls to
* $_FILE
*/
public function multiple_upload()
{
$this->load->library('upload');
$number_of_files_uploaded = count($_FILES['upl_files']['name']);
// Faking upload calls to $_FILE
for ($i = 0; $i < $number_of_files_uploaded; $i++){
$_FILES['userfile']['name'] = $_FILES['upl_files']['name'][$i];
$_FILES['userfile']['type'] = $_FILES['upl_files']['type'][$i];
$_FILES['userfile']['tmp_name'] = $_FILES['upl_files']['tmp_name'][$i];
$_FILES['userfile']['error'] = $_FILES['upl_files']['error'][$i];
$_FILES['userfile']['size'] = $_FILES['upl_files']['size'][$i];
$config = array(
'file_name' => <your ouw function to generate random names>,
'allowed_types' => 'jpg|jpeg|png|gif',
'max_size' => 3000,
'overwrite' => FALSE,
/* real path to upload folder ALWAYS */
'upload_path'
=> $_SERVER['DOCUMENT_ROOT'] . '/path/to/upload/folder'
);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}else {
$final_files_data[] = $this->upload->data();
// Continue processing the uploaded data
}
}
}
This Worked for me. reffer to this page this is not my code
https://gist.github.com/zitoloco/1558423
Try this code to upload image
$directory = "./images/";
$config['upload_path'] = $directory;
$config['encrypt_name'] = TRUE;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
if (!$this->upload->do_upload('mainimage'))
{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
else {
$data = array('upload_data' => $this->upload->data());
print_r($data);
}
And one other change is :
Replace upload.php file.
take latest verison upload.php file from system directory -> libraries directory -> upload.php. Copy new version upload.php file and replace in your project
Hope it will work properly.

php mysql update query gives an empty result

I am trying to make update function for my project.
I have a table of Client data,
Delete, Add functions are working but whenever I use update function
it empties data of the row within database to null
I tried other things but didn't work well.
It could be a small mistake but I seem cannot find the problem as I been working on other projects wholeday :<
Update details php file
<?php
// include Database connection file
include("db_connection.php");
// check request
if(isset($_POST))
{
// get values
$id = $_POST['id'];
$Surname = $_POST['update_Surname'];
$Name= $_POST['update_Name'];
$Address = $_POST['update_Address'];
$Telephone = $_POST['update_Telephone'];
$PurchaseDate = $_POST['update_PurchaseDate'];
$Model = $_POST['update_Model'];
$SerialNumber = $_POST['update_SerialNumber'];
$Notes = $_POST['update_Notes'];
// Update User details
$query = "UPDATE Clients SET Surname = '$Surname', Name = '$Name', Address = '$Address', Telephone = '$Telephone', PurchaseDate = '$PurchaseDate', Model = '$Model', SerialNumber = '$SerialNumber', Notes = '$Notes' WHERE id = '$id'";
if (!$result = mysql_query($query)) {
exit(mysql_error());
}
}
update function
function UpdateUserDetails() {
// get values
var update_Surname = $("#update_Surname").val();
var update_Name = $("#update_Name").val();
var update_Address = $("#update_Address").val();
var update_Telephone = $("#update_Telephone").val();
var update_PurchaseDate = $("#update_PurchaseDate").val();
var update_Model = $("#update_Model").val();
var update_SerialNumber = $("#update_SerialNumber").val();
var update_Notes = $("#update_Notes").val();
// get hidden field value
var id = $("#hidden_user_id").val();
// Update the details by requesting to the server using ajax
$.post("ajax/updateUserDetails.php", {
id: id,
Surname: update_Surname,
Name: update_Name,
Address: update_Address,
Telephone: update_Telephone,
PurchaseDate: update_PurchaseDate,
Model: update_Model,
SerialNumber: update_SerialNumber,
Notes: update_Notes
},
function (data, status) {
// hide modal popup
$("#update_user_modal").modal("hide");
// reload Users by using readRecords();
readRecords();
}
);
}
Modal form
<div class="modal fade" id="update_user_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<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" id="myModalLabel">Update</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="update_Surname">Surname</label>
<input type="text" id="update_Surname" placeholder="Surname" class="form-control"/>
</div>
<div class="form-group">
<label for="update_Name">Name</label>
<input type="text" id="update_Name" placeholder="Name" class="form-control"/>
</div>
<div class="form-group">
<label for="update_Address">Address</label>
<input type="text" id="update_Address" placeholder="Address" class="form-control"/>
</div>
<div class="form-group">
<label for="update_Telephone">Telephone</label>
<input type="text" id="update_Telephone" placeholder="Telephone" class="form-control"/>
</div>
<div class="form-group">
<label for="update_PurchaseDate">Purchase Date</label>
<input type="date" id="update_PurchaseDate" placeholder="Purchase Date" class="form-control"/>
</div>
<div class="form-group">
<label for="update_Model">Model</label>
<input type="text" id="update_Model" placeholder="Model" class="form-control"/>
</div>
<div class="form-group">
<label for="update_SerialNumber">Serial Number</label>
<input type="text" id="update_SerialNumber" placeholder="Serial Number" class="form-control"/>
</div>
<div class="form-group">
<label for="update_Notes">Notes</label>
<input type="text" id="update_Notes" placeholder="Notes" class="form-control"/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="UpdateUserDetails()" >Save Changes</button>
<input type="hidden" id="hidden_user_id">
</div>
</div>
</div>
</div>
$id = $_POST['id'];
$Surname = $_POST['update_Surname'];
$Name= $_POST['update_Name'];
$Address = $_POST['update_Address'];
$Telephone = $_POST['update_Telephone'];
$PurchaseDate = $_POST['update_PurchaseDate'];
$Model = $_POST['update_Model'];
$SerialNumber = $_POST['update_SerialNumber'];
$Notes = $_POST['update_Notes'];
you are using update_ as your post variables. But the actual keys are different which you have provided into the jQuery post function. actual keys are defined in following object at left side of each assignment.
{
id: id,
Surname: update_Surname,
Name: update_Name,
Address: update_Address,
Telephone: update_Telephone,
PurchaseDate: update_PurchaseDate,
Model: update_Model,
SerialNumber: update_SerialNumber,
Notes: update_Notes
}
use the following instead.
$id = $_POST['id'];
$Surname = $_POST['Surname'];
$Name= $_POST['Name'];
$Address = $_POST['Address'];
$Telephone = $_POST['Telephone'];
$PurchaseDate = $_POST['PurchaseDate'];
$Model = $_POST['Model'];
$SerialNumber = $_POST['SerialNumber'];
$Notes = $_POST['Notes'];

Codeigniter: Ajax sending id & name but function is receiving only id

I'm getting the id but not the name, what's wrong i'm doing ?
Please take a look at my CI code and ajax function below:
This is View on which i'm calling ajax:
<div class="modal fade" id="myModal<?php echo $values->season_id; ?>"
tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<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" id="myModalLabel">Update Seasons</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="hidden" id="hiddenValue" name="hiddenValue" value="<?php echo $values->season_id; ?>">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">Season Name:
</label>
<div class="title_right">
<div class="input-group">
<input type="text" class="form-control" name="update_name" id="update_name" value="<?php echo $values->names; ?>">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" id="submit" value="Save changes">
</div>
</div>
</div>
</div>
This is Ajax Function:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
alert("Ajax function started working");
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
dataType: 'json',
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
alert("changes made");
}
}
});
});
});
And here i'm trying to capture the value:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$result = $this->model_season->update_season($update_id,$update_name);
if ($query)
{
$query = $query->row();
$data = array(
'season_id' => $query->season_id,
'names' =>$query->names
);
echo json_encode($data);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
You use
if ($query)
{
$query = $query->row();
$data = array(
'season_id' => $query->season_id,
'names' =>$query->names
);
echo json_encode($data);
}
but where your $query. As your code It should have as following
if ($result)
{
$data = array(
'season_id' => $result->season_id,
'names' =>$result->names
);
echo json_encode($data);
}
Now use $result->season_id instead of $query->season_id and make sure you use row() method in your model update_season() for returning desired values

HTML/JS Contact Form Not Sending or Showing Error Message

I have a contact form that I can't seem to send to my Gmail account. It's different from all the contact forms I've seen because the error message is within the HTML. Nothing happens when the submit button is pressed (no email, no error or success message). Please be gentle for I am somewhat new to PHP. I just need some help please.
The HTML
<div class="contactForm">
<div class="successMessage alert alert-success alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Thank You! E-mail was sent.
</div>
<div class="errorMessage alert alert-danger alert-dismissable" style="display: none">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
Oops! An error occured. Please try again later.
</div>
<form class="liveForm" role="form" action="form/send.php" method="post" data-email-subject="Contact Form" data-show-errors="true" data-hide-form="false">
<fieldset>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Name <span>(Required)</span></label>
<input type="text" required name="field[]" class="form-control">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Email <span>(Required)</span></label>
<input type="email" required name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Subject</label>
<input type="text" name="field[]" class="form-control">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Message <span>(Required)</span></label>
<textarea name="field[]" required class="form-control" rows="5"></textarea>
</div>
</div>
</div>
<input type="submit" class="btn btn-primary" value="Send Message">
</fieldset>
</form>
</div>
</div>
The JS
/**
* Contact Form
*/
jQuery(document).ready(function ($) {
"use strict";
$ = jQuery.noConflict();
var debug = false; //show system errors
$('.liveForm').submit(function () {
var $f = $(this);
var showErrors = $f.attr('data-show-errors') == 'true';
var hideForm = $f.attr('data-hide-form') == 'true';
var emailSubject = $f.attr('data-email-subject');
var $submit = $f.find('[type="submit"]');
//prevent double click
if ($submit.hasClass('disabled')) {
return false;
}
$('[name="field[]"]', $f).each(function (key, e) {
var $e = $(e);
var p = $e.parent().find("label").text();
if (p) {
var t = $e.attr('required') ? '[required]' : '[optional]';
var type = $e.attr('type') ? $e.attr('type') : 'unknown';
t = t + '[' + type + ']';
var n = $e.attr('name').replace('[]', '[' + p + ']');
n = n + t;
$e.attr('data-previous-name', $e.attr('name'));
$e.attr('name', n);
}
});
$submit.addClass('disabled');
$f.append('<input class="temp" type="hidden" name="email_subject" value="' + emailSubject + '">');
$.ajax({
url: $f.attr('action'),
method: 'post',
data: $f.serialize(),
dataType: 'json',
success: function (data) {
$('span.error', $f).remove();
$('.error', $f).removeClass('error');
$('.form-group', $f).removeClass('has-error');
if (data.errors) {
$.each(data.errors, function (i, k) {
var input = $('[name^="' + i + '"]', $f).addClass('error');
if (showErrors) {
input.after('<span class="error help-block">' + k + '</span>');
}
if (input.parent('.form-group')) {
input.parent('.form-group').addClass('has-error');
}
});
} else {
var item = data.success ? '.successMessage' : '.errorMessage';
if (hideForm) {
$f.fadeOut(function () {
$f.parent().find(item).show();
});
} else {
$f.parent().find(item).fadeIn();
$f[0].reset();
}
}
$submit.removeClass('disabled');
cleanupForm($f);
},
error: function (data) {
if (debug) {
alert(data.responseText);
}
$submit.removeClass('disabled');
cleanupForm($f);
}
});
return false;
});
function cleanupForm($f) {
$f.find('.temp').remove();
$f.find('[data-previous-name]').each(function () {
var $e = jQuery(this);
$e.attr('name', $e.attr('data-previous-name'));
$e.removeAttr('data-previous-name');
});
}
});
The PHP
<?php
// Contact subject
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Enter your email address
$to ='divagraphicsinc#gmail.com';
$send_contact=mail($to,$subject,$message,$header);
?>
<?php
$ajax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
$ajax = true;
//we do not allow direct script access
if (!$ajax) {
//redirect to contact form
echo "Please enable Javascript";
exit;
}
require_once "config.php";
//we set up subject
$mail->Subject = isset($_REQUEST['email_subject']) ? $_REQUEST['email_subject'] : "Message from site";
//let's validate and return errors if required
$data = $mail->validateDynamic(array('required_error' => $requiredMessage, 'email_error' => $invalidEmail), $_REQUEST);
if ($data['errors']) {
echo json_encode(array('errors' => $data['errors']));
exit;
}
$html = '<div style="width: 640px; font-size: 11px;">
<h2>' . $mail->Subject . '</h2><ul>
';
foreach ($data['fields'] as $label => $val) {
$html .= '<li>' . $label . ': ' . $val . '</li>';
}
$html .= '</ul></div>';
$mail->setup($html, $_REQUEST, array());
$result = array('success' => 1);
if (!$mail->Send()) {
$result['success'] = 0;
}
echo json_encode($result);
exit;

Categories