Ajax auto fill input fields and image - javascript

The code below auto fills the Full name and Email when the user enters their ID. I also want to display the user's image but i'm having issues.
<script type="text/javascript">
$(function() {
$( "#techid" ).on( 'blur' , function() {
searchString = $(this).val();
var data = 'telefoon='+searchString;
if(searchString) {
$.ajax({
type : "POST",
url : "query2.php",
data : data,
success : function(html){
result = String(html).split("|");
$("#name").val(result[0]);
$("#mail").val(result[1]);
$("#avatar").val(result[2]);
}
});
}
return false;
});
});
</script>
I know I can display the image like this but how do i integrate it with the AJAX?
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include_once("connection.php");
$result = mysql_query("SELECT * FROM players3");
while($res = mysql_fetch_array($result)) {
echo '<img height="80px" width="100px" src="data:image/jpeg; base64,'.base64_encode( $res['image'] ).'"/>';
?>
I tried this:
<div class="form-group">
<label for="telefoon" class="col-sm-2 control-label">Avatar</label>
<div class="col-sm-10">
<img height="80px" width="100px" id="avatar" src="data:image/jpeg;base64,'.base64_encode( )"/>
</div>
</div>
<div class="form-group">
<label for="telefoon" class="col-sm-2 control-label">Tech ID</label>
<div class="col-sm-10">
<input type="text" name="techid" class="form-control" id="techid" placeholder="TechID" >
</div>
</div>
<div class="form-group">
<label for="naam" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" name="name" class="form-control" id="name" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="mail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" name="mail" class="form-control" id="mail" placeholder="email">
</div>
</div>
Like this?
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include_once("connection-db2.php");
$result = mysql_query("SELECT * FROM TechID");
while($res = mysql_fetch_array($result)) {
echo '<li><img height="80px" width="100px" src="data:image/jpeg;base64,'.base64_encode( $res['image'] ).'"/>';
}
?>
JS
$("#image").attr('src', result[4]);

when upload the image, save the image path with image file name. like "images/image1.jpg"
like the name and email, query the path of the image.
make a empty
after ajax success you get the path of the image. right? use this path like this. $("#image_to_show").html("");

<img> tag doesn't have value attribute
You should probably echo just image url and set it as a src attribute of your img tag
PHP:
while($res = mysql_fetch_array($result)) {
echo $res['image'];
// ...
}
JS:
$("#avatar").attr('src', result[2]);
On a side note - it would be better to json_encode response and use it instead of .split("|"). Something like this:
PHP:
$response = array();
while($res = mysql_fetch_array($result)) {
$response['name'] = $res['name'];
$response['email'] = $res['email'];
$response['image'] = $res['image'];
}
echo json_encode($response);
JS:
$.ajax({
type : "POST",
url : "query2.php",
data : data,
dataType : "json",
success : function(result){
$("#name").val(result.name);
$("#mail").val(result.email);
$("#avatar").attr('src', result.image);
}
});

Related

populate 2nd drop down based on 1st drop down result by using ajax in codeigniter php

I'm trying to do the 2nd drop down population based on the 1st drop down by using ajax in codeigniter. But my problem is after I choose for 1st drop down value, when I try to choose for 2nd drop down value, it shows empty only.
(Update: I already fixed my problem. So, I already updated my code.)
Image below shows that the result after I choose for 1st option. When I try to select for 2nd option, it can't shows the value:
Here's is the code for view:
<div class="container">
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center">
<div class="card">
<div class="card-body">
<h3 class="card-title text-center"><?php echo $content_heading;?></h3>
<form action="#" id="form" novalidate>
<div class="form-row">
<div class="col-sm-12">
<div class="form-group">
<label for="subject_name">Subject Name</label>
<select class="form-control" name="subject_name" id="subject_name">
<option>-- Select Subject Name --</option>
<?php foreach($attendance as $row){
echo "<option value='".$row['subject_id']."'>".$row['subject_name']."</option>";
}
?>
</select>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="lecturer_name">Lecturer Name</label>
<input name="lecturer_name" placeholder="Lecturer Name" class="form-control" type="text" disabled="">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="subject_section">Section</label>
<select class="form-control" name = "subject_section" id='subject_section'>
<option>-- Select Subject Section --</option>
</select>
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_date">Date</label>
<input name="attendance_date" placeholder="Date" class="form-control" type="date">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_start_time">From</label>
<input name="attendance_start_time" placeholder="From" class="form-control" type="time">
<div class="invalid-feedback"></div>
</div>
<div class="form-group">
<label for="attendance_end_time">To</label>
<input name="attendance_end_time" placeholder="To" class="form-control" type="time">
<div class="invalid-feedback"></div>
</div>
<button type="button" id="btnSave" class="btn btn-primary btn-block" onclick="save()">Confirm</button>
</div>
</div>
</form>
</div>
</div>
</div>
Here is the javascript for the ajax function. (I already updated my javascript code.)
<script>
$(document).ready(function(){
// Subject change
$('#subject_name').change(function(){
var subject_id = $(this).val();
// AJAX request
$.ajax({
url : "<?php echo site_url('attendance/get_subject_section')?>",
method: 'POST',
data: {subject_id: subject_id},
dataType: 'JSON',
success: function(response){
// Remove options
$('#subjectsection').find('option').not(':first').remove();
// Add options
$.each(response,function(index,data){
$('#subject_section').append('<option value="'+data['subject_id']+'">'+data['subject_section']+'</option>');
});
}
});
});
});
</script>
Here is the code for controller:
<?php class attendance extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->model('Attendance Data/attendance_model','attendance');
}
function index(){
//$this->load->view('Manage User Registration/user_login_view');
$data['meta_title'] = 'Attendance';
$data['content_heading'] = 'Attendance';
$data['main_content'] = 'Manage Student Attendance/attendance';
$data['user_id'] = $this->session->userdata('id');
if($this->session->userdata('user_type')==='lecturer'){
$data['user_type'] = 'lecturer';
$data['meta_user_level_title'] = 'Lecturer';
$data['id'] = $this->session->id;
$data['main_content'] = 'Manage Student Attendance/lecturer_attendance_view';
$this->load->view('template/template', $data);
}else{
echo "Access Denied";
}
}
public function create_attendance()
{
$data['meta_title'] = 'Add Subject Attendance';
$data['content_heading'] = 'Add Subject Attendance';
$data['main_content'] = 'Manage Student Attendance/attendance';
$data['user_id'] = $this->session->userdata('id');
$data['user_type'] = 'lecturer';
$data['heading'] = 'Lecturer';
if($this->session->userdata('user_type')==='lecturer'){
$data['user_type'] = 'lecturer';
$data['attendance'] = $this->attendance->get_subject_name();
$data['meta_user_level_title'] = 'Lecturer';
$data['id'] = $this->session->id;
$data['main_content'] = 'Manage Student Attendance/create_attendance';
$this->load->view('template/template', $data);
}else{
echo "Access Denied";
}
}
public function get_subject_section()
{
// POST data
$subject_id= $this->input->post('subject_id');
// get data
$data = $this->attendance->get_subject_section($subject_id);
echo json_encode($data);
}}
Here is my code for model:
<?php class attendance_model extends CI_Model{
//Get subject name
public function get_subject_name()
{
$user_id = $this->session->userdata("id");
$response = array();
// Select record
$this->db->select('*');
$this->db->where('lecturer_id', $user_id);
$this->db->group_by('subject_id');
$query = $this->db->get('lecturer_timetable');
$response = $query->result_array();
return $response;
}
//Get subject section
public function get_subject_section($subject_id){
$user_id = $this->session->userdata("id");
$response = array();
// Select record
$this->db->select('subject_id, subject_section');
$this->db->where('lecturer_id', $user_id);
$this->db->where('subject_id', $subject_id);
$query = $this->db->get('lecturer_timetable');
$response = $query->result_array();
return $response;
}}
Can someone help me to solve this problem? Thanks.
your url in ajax is unreadable because of quotation. Try to writer in proper quotation. Use either single quotes inside double quotes or use double inside single. Second is, you are using method as 'POST' but in lowercase. Write POST in uppercase.
$.ajax({
url : "<?php echo site_url('attendance/get_subject_section')?>",
method: 'POST',
data: {subject_name: subject_name},
dataType: 'json',
success: function(response){
console.log(response); // first check by console that you are getting records in response. once you get response then append it or do whatever you want
}
});

Jquery ajax FormData is always empty

I want to sent some data with ajax to a php file. I created a FormData, and then, i append all the data to it, that i want to send. I dont get any error message in the console.
My problem is, that the formdata is always empty, and the php file is not getting any data also.
The form:
<div class="tab-pane show" id="tab5">
<form id="AllapotForm" class="form-horizontal" method="post" enctype="multipart/form-data">
<table id="products" class="table table-hover">
<thead>
<tr class="tr_bold">
<!--width="33.3%"-->
<td class="left" >Létrehozva</td>
<td class="left" >Állapot</td>
<td class="left" >A megrendelő értesítve email-ben</td>
<td class="left" >Megjegyzés</td>
</tr>
</thead>
<tbody id="allapotok">
<?php
$get_r_allaptok = mysqli_query($kapcs,
"
SELECT
rendeles_allapot.*,
rendeles_allapotok.rendeles_allapotok_nev
FROM rendeles_allapot
LEFT JOIN rendeles_allapotok ON rendeles_allapot.allapot_allapot_id = rendeles_allapotok.rendeles_allapotok_id
WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id ASC
")
or die(mysqli_error($kapcs));
if(mysqli_num_rows($get_r_allaptok) > 0 )
{
while($r_allapot = mysqli_fetch_assoc($get_r_allaptok))
{
if($r_allapot['allapot_notify'] == 0 ) { $ertesitve = "Nem"; }
if($r_allapot['allapot_notify'] == 1 ) { $ertesitve = "Igen"; }
echo '<tr>
<td class="left">'.$r_allapot['allapot_datetime'].'</td>
<td class="left">'.$r_allapot['rendeles_allapotok_nev'].'</td>
<td class="left">'.$ertesitve.'</td>
<td class="left">'.$r_allapot['allapot_comment'].'</td>
</tr>';
}
}
?>
</tbody>
</table>
<img src="<?php echo $host; ?>/images/assets/preloader.gif" id="preloaderImage2" style="display:none" class="img-responsive" style="margin:10px auto;">
<div class="form-group row">
<label class="control-label col-md-2">Állapot:</label>
<div class="col-md-2">
<select name="allapot" id="allapot" class="input input-select form-control">
<?php
$check_allapot = mysqli_query($kapcs, "SELECT allapot_allapot_id FROM rendeles_allapot WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id DESC LIMIT 1");
if(mysqli_num_rows($check_allapot) > 0 )
{
$allapot_fetch = mysqli_fetch_assoc($check_allapot);
$ertek = $allapot_fetch['allapot_allapot_id'];
}
else
{
$ertek = intval($a['status']);
}
$get_allapotok = mysqli_query($kapcs, "SELECT rendeles_allapotok_id, rendeles_allapotok_nev FROM rendeles_allapotok WHERE rendeles_allapotok_status = 1 ORDER BY rendeles_allapotok_nev ASC");
if(mysqli_num_rows($get_allapotok) > 0 )
{
while($allapot = mysqli_fetch_assoc($get_allapotok))
{
$selected = $ertek == $allapot['rendeles_allapotok_id'] ? ' selected="selected"':'';
echo '<option ' . $selected . ' value="' . $allapot['rendeles_allapotok_id'] . '">' . $allapot['rendeles_allapotok_nev'] . '</option>'."\n";
}
}
?>
</select>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megrendelő értesítése email-ben:</label>
<div class="col-md-2">
<input type="checkbox" name="notify" id="notify" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés hozzáadása az email-hez:<span class="help">Amennyiben ezt bepipálja, a megjegyzés az ügyfélnek kiküldött üzenetbe is bele fog kerülni.</span></label>
<div class="col-md-2">
<input type="checkbox" name="add_text" id="add_text" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Fájl csatolása az email-hez:</label>
<div class="col-md-2">
<input type="file" name="file" id="file" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés:</label>
<div class="col-md-8">
<textarea name="comment" id="comment" style="width:100%;height:200px;"></textarea>
<div style="margin-top: 10px; text-align: center;">
<a class="saveButton btn btn-primary" style="color:#fff" onclick="allapot_modosit();" id="history_button">Állapot módosítása</a>
</div>
</div>
</div>
</form>
</div>
I call this function on a button click event.
function send_data()
{
var html;
var RendelesID = <?php echo $id; ?>;
var RendelesUserEmail = "<?php echo html($a['email']); ?>";
var RendelesUserName = "<?php echo html($a['nev']); ?>";
var webshopEmail = "<?php echo $webshopEmail; ?>";
var webshopName = "<?php echo $webshopName; ?>";
var Allapot = $( "#allapot option:selected" ).val();
var Comment = CKEDITOR.instances['comment'].getData();
if($("#notify").is(':checked')){var Notify = 1;}else{var Notify = 0;}
if($("#add_text").is(':checked')){var AddToEmail = 1;}else{var AddToEmail = 0;}
var formData = new FormData($('#AllapotForm')[0]);
formData.append('fileName', $('#file')[0].files[0]);
formData.append(RendelesID, RendelesID);
formData.append(RendelesUserEmail, RendelesUserEmail);
formData.append(RendelesUserName, RendelesUserName);
formData.append(webshopEmail, webshopEmail);
formData.append(webshopName, webshopName);
formData.append(Allapot, Allapot);
formData.append(Comment, Comment);
formData.append(Notify, Notify);
formData.append(AddToEmail, AddToEmail);
console.log(formData);
$.ajax({
type: 'POST',
cache: false,
url: 'files/update_rendeles_allapot.php',
//dataType: 'html',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: { formData:formData },
beforeSend: function(){
$('#preloaderImage2').show();
},
success: function(data)
{
alert(data);
},
complete: function(){
$('#preloaderImage2').hide();
},
error: function (e) {
alert(e.responseText);
console.log(e);
}
});
}
data: { formData:formData },
You need to pass the form data object itself, not a plain object.
data: formData
Have you already seen this?
FormData created from an existing form seems empty when I log it
If yes try to check your network look to the Network then take a look at your request.
You can also try to check your API via Postman if it's working properly.

Send data-attribute ID in JS to PHP on same index page using ajax?

I am not sure how to word this title. Feel free to edit it.
Intro I am doing a datatables.net library server-side table using JSON and PHP. I am basically done except for the edit form.
My first problem was solved. I had a while loop instead of an if statement.
My second problem is now going to be transferring this Javascript code near before the AJAX call:
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
to here which is php:
$edit_id = $_POST['edit_id'];
They are both on the same page, index.php so I do not think I can use ajax for this.
Index.php
<script type="text/javascript">
$(document).on('click', '.edit_btn', function() {
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
$("#form2").show();
//console.log(edit_id[0]);
$.ajax({
type: 'POST',
url: 'edit.php',
data: {
edit_id: edit_id,
first_name: $("#edit2").val(),
last_name: $("#edit3").val(),
position: $("#edit4").val(),
updated: $("#edit5").val(),
},
success: function(data) {
alert(data);
if (data == 'EDIT_OK') {
alert("success");
} else {
// alert('something wrong');
}
}
})
});
</script>
<?php
$sql="select * from employees WHERE id=$edit_id";
$run_sql=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($run_sql)){
$per_id=$row[0];
$per_first=$row[1];
$per_last=$row[2];
$per_position=$row[3];
//$per_date=$row[4];
$per_updated=$row[5];
?>
<form id="form2" class="form-horizontal">
<label class="col-sm-4 control-label" for="txtid">ID</label>
<input id="edit1" type="text" class="form-control" name="txtid" value="<?php echo $per_id;?>" readonly>
<div class="form-group">
<label class="col-sm-4 control-label" id="edit2" for="txtname">First Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="txtname" name="txtname" value="<?php echo $per_first;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtsalary">Last Name</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit3" name="txtsalary" value="<?php echo $per_last;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Position</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit4" name="txtage" value="<?php echo $per_position;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Updated</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit5" name="txtage" value="<?php echo $per_updated;?>">
</div>
<button type="button" class="close" value="Cancel" data-dismiss="modal">×</button>
<button type="button" class="update" value="Update"></button>
</form>
edit.php
$edit_id = $_POST['edit_id'];
$stmt = $conn->prepare("UPDATE employees SET first_name=?, last_name=?, position=?, updated=? WHERE id=?");
$stmt->bind_param('ssssi', $_POST['first_name'], $_POST['last_name'], $_POST['position'], $_POST['updated'], $_POST['edit_id']);
$confirmUpdate = $stmt->execute();
if($confirmUpdate) {
echo "EDIT_OK";
}else {
trigger_error($conn->error, E_USER_ERROR);
return;
}
?>
I eventually figured it out:
<script type="text/javascript">
$(document).on('click','.edit_btn',function (){
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row( id ).data();
var edit_id = edit_id[0];
alert(edit_id);
$.ajax({
url: 'index.php',
data: { edit_id : edit_id },
contentType: 'application/json; charset=utf-8',
success: function(result) {
//alert(result);
}
});
});
</script>

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.

Custom AJAX form not working async

I have a contact from that uses PHP mailer that I have integrated into my Wordpress blog. The script sends emails no problem - the issue is that it does not work async so once the form is submitted I am taken to another page with the following text on it: {"message":"Your message was successfully submitted from PHP."}. The script works as expected when used outside of wordpress - I have no idea whats going on.
PHP
<?php
/**
* Sets error header and json error message response.
*
* #param String $messsage error message of response
* #return void
*/
function errorResponse ($messsage) {
header('HTTP/1.1 500 Internal Server Error');
die(json_encode(array('message' => $messsage)));
}
/**
* Pulls posted values for all fields in $fields_req array.
* If a required field does not have a value, an error response is given.
*/
function constructMessageBody () {
$fields_req = array("name" => true, "description" => true, "email" => true, "number" => true);
$message_body = "";
foreach ($fields_req as $name => $required) {
$postedValue = $_POST[$name];
if ($required && empty($postedValue)) {
errorResponse("$name is empty.");
} else {
$message_body .= ucfirst($name) . ": " . $postedValue . "\n";
}
}
return $message_body;
}
//header('Content-type: application/json');
//attempt to send email
$messageBody = constructMessageBody();
require 'php_mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress("example#example.com");
$mail->Subject = $_POST['name'];
$mail->Body = $messageBody;
//try to send the message
if($mail->send()) {
echo json_encode(array('message' => 'Your message was successfully submitted from PHP.'));
} else {
errorResponse('An expected error occured while attempting to send the email: ' . $mail->ErrorInfo);
}
?>
(function($) {
$('#form').on('submit', function(){
event.preventDefault();
var contactFormUtils = {
clearForm: function () {
grecaptcha.reset();
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").append('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
$('#submit-email').prop('disabled', true).html("sending");
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log('success');
$('#form').fadeOut(400)
contactFormUtils.addAjaxMessage(data.message, false);
contactFormUtils.clearForm();
},
error: function(response) {
console.log('error');
contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
$('#submit-report').prop('disabled', false).html("Send message");
contactFormUtils.clearForm();
},
complete: function() {
console.log('complete');
}
});
return false;
});
})( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-8 site-block">
<form id="form" method="post" class="form-horizontal ajax" action="<?php echo get_template_directory_uri(); ?>/assets/php/process-contact.php" data-toggle="validator">
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input name="name" type="text" class="form-control" id="inputName" placeholder="Enter your full name and title here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10">
<input name="number" type="number" class="form-control" id="inputEmail3" placeholder="Enter your preferred telephone number here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Enter your preferred email address here" required>
</div>
</div>
<div class="form-group">
<label for="inputMessage" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea name="description" class="form-control" id="inputMessage" placeholder="Type your message here" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="submit-email" name="submit" type="submit" class="btn btn-danger">Submit</button>
</div>
</div>
</form>
<div id="feedbackSubmit"></div>
</div>
change
jQuery('#form').on('submit', function(){
to
jQuery('.ajax').on('submit', function(event){
and replace ALL $ with jQuery
and
wrap your code in document ready function
jQuery(function(){});

Categories