I don't know what's wrong with my code, it didn't work.
My controller :
public function add_user_driver()
{
if(!$this->user_permission->check_permission())return;
$plate_number = $this->input->post('plate_number');
$location_id = $this->input->post('location_id');
$data_user = array(
'plate_number' => $plate_number,
'location_id' => $location_id,
);
$this->db->insert('user_driver', $data_user);
echo json_encode(array("plate_number" => $plate_number, "location_id" => $location_id));
}
The view :
<div class="modal fade" id="usermodal" 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">USER_DRIVER</h4>
</div>
<div class="modal-body" id='add'>
<div class="row" id="form_pesan">
<input type="hidden" name="id" id="id" />
<div class="col-sm-6">
<input type="text" class="form-control input-lg" id="plate_number" name="plate_number" placeholder="Plate Number" required>
</div>
<div class="col-sm-6">
<input type="text" class="form-control input-lg" id="location_id" name="location_id" placeholder="Location Id" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="add" type="button" class="btn btn-primary btn-md" onclick=add()>Add</button>
</div>
</div>
<div id="form_submit_result"></div>
</div>
</div>
JavaScript :
$(document).ready(function(){
matchFormFields = "#form_pesan input[required]";
matchFormSubmitResult = "#form_submit_result";
errorColor = 'red';
});
function add(){
var formIsValid = true;
$(matchFormFields).each(function() {
$(this).css('border-color', '');
if(!$.trim($(this).val())) {
$(this).css('border-color', errorColor);
formIsValid = false;
}
});
if (formIsValid) {
plate_number = $("#plate_number").val();
location_id = $("#location_id").val();
$.ajax
({
url : "<?php echo site_url('admin/add_user_driver')?>/",
type: "POST",
dataType: "text",
data:{plate_number: plate_number, location_id: location_id},
success: function(data)
{
$("#usermodal").modal("hide");
$("#alert").show();
//location.reload();
},
error: function (jqXHR, textStatus, errorThrown)
{
notify('Error data');
}
});
};
}
I want to submit value from input text to JavaScript add function, but somehow, the .val() doesn't return the actual value. What did I do wrong?
please try this
datatype: "json"
or
datatype: "text"
JSON.stringify({plate_number: plate_number, location_id: location_id})
var abc = $("#plate_number").val();
alert(abc);
return false;
You can use the variable abc in javascript.
Related
HTML required attribute not working with AJAX submission
I have created a model Form and set its input field to require attribute but its not working with ajax
<div class="modal fade hide" id="ajax-book-model" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="ajaxBookModel">Add New Machine</h5>
<!-- <button type="reset" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> -->
<button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" onClick="window.location.reload();">
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST">
<input type="hidden" name="id" id="id">
<input type="hidden" name="user_id" id="user_id" value="{{ Auth::user()->id }}">
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Name</label>
<input type="text" id="machine_name" name="machine_name" class="form-control form-control-sm" placeholder="Enter Machine Name" required>
<span class="text-danger">{{ $errors->first('machine_name') }}</span>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>IOT Device ID</label>
<input type="text" id="iot_device_id" name="iot_device_id" class="form-control form-control-sm" placeholder="Enter IOT Device ID" required>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Local device ID</label>
<input type="text" id="local_device_id" name="local_device_id" class="form-control form-control-sm" placeholder="Enter Local Device ID" required>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-gradient-danger mb-2" data-dismiss="modal" onClick="window.location.reload();">Close</button>
<button type="submit" id="btn-save" value="addNewBook" class="btn btn-sm btn-gradient-danger mb-2">Save</button>
</div>
</form>
</div>
</div>
</div>
and this is ajax code
i just want to run simpal html required field validation with ajax
$('body').on('click','#btn-save', function (event){
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save"). attr("disabled", true);
// ajax
$.ajax({
type:"POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id:id,
user_id:user_id,
machine_name:machine_name,
iot_device_id:iot_device_id,
local_device_id:local_device_id,
},
dataType: 'json',
success: function(res){
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save"). attr("disabled", false);
}
});
});
i just want to run required field validation with ajax i could not find any solution .
Try changing your btn click event to form submit event.
$('body').on('submit', '#addEditBookForm', function (event) {
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save").attr("disabled", true);
// ajax
$.ajax({
type: "POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id: id,
user_id: user_id,
machine_name: machine_name,
iot_device_id: iot_device_id,
local_device_id: local_device_id,
},
dataType: 'json',
success: function (res) {
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save").attr("disabled", false);
}
});
});
The following should help: change to a form confirmation event instead of a Click button event. And do not forget to write this code so that the page does not reload:
event.preventDefault();
I want to get data from a controller and display it in a html pop-up when a button is clicked.
At this point the POPUP is showing when the button is clicked but the data isn't loaded
At this point I need that onclick the values get loaded and show them in the popup.
index.blade.php
<button data-toggle="modal" data-target="#edit" id ="uid" name="uid" value="<?php echo $user->id ?>">
</button>
<div class="modal fade" id="edit" tabindex="-1" role="">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="card card-signup card-plain">
<div class="modal-header">
<div class="card-header card-header-primary text-center">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="material-icons">clear</i>
</button>
<h4 class="card-title">Editar</h4>
</div>
</div>
<div class="modal-body">
<form class="form" method="POST" action = "{{ route('/alteruser') }}" name = 'user'>
#csrf
<div class="card-body">
<div class="form-group bmd-form-group">
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text">
<i class="material-icons"></i>
</div>
</div>
<input name = 'name' type="text" class="form-control" placeholder="<?php echo $seluser->id ?? ''?>" id='id' disabled>
<input name = 'name' type="text" class="form-control" "<?php echo $seluser->name ?? ''?>" id='name'>
<input type="text" class="form-control" placeholder="<?php echo $seluser->email ?? ''?>" id = 'email'>
<input type="password" placeholder="<?php echo $seluser->password ?? ''?>" class="form-control" id = 'password'>
<input type="text" placeholder="<?php echo $seluser->nif ?? ''?>" class="form-control" id = 'nif'>
<input type="text" placeholder="<?php echo $seluser->contacto ?? ''?>" class="form-control" id = 'contact'>
<input type="text" placeholder="Grupo" class="form-control" id = 'grupo'>
</div>
</div>
<button type="submit" class="btn btn-primary btn-link btn-wd btn-lg" name = 'uid'>Confirmar</a>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
UserController#GetUser:
public function getUser() {
$id = $_POST['uid'];
$seluser = DB::table('users') -> where('id', $id) -> first();
$view = view('/users/index',compact('seluser'))->render();
return response(['status'=> 1, 'data' => $view]);
}
Ajax code in index.blade.php:
$(document).ready(function(){
$("#uid").click(function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: baseUrl+"/getUser",
data:{uid: $("#uid").val()},
dataType: 'json',
success: function(data) {
$('#edit').html(data.html);
}
});
});
});
I'm new at AJAX so i assume the error is in it
Here is an example for what you're trying to do :
Controller for GET request :
$users = \App\User::all();
return view('users', ['users' => $users]);
View users :
<div class="container">
#foreach ($users as $user)
<button class="btn btn-primary" data-toggle="modal" data-target="#edit" id ="uid" data-id="{{$user->id}}">
click here
</button>
#endforeach
#csrf
<div class="modal fade" id="edit" tabindex="-1" role="">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="card card-signup card-plain">
<div class="modal-header">
<div class="card-header card-header-primary text-center">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<i class="material-icons">clear</i>
</button>
<h4 class="card-title">Editar</h4>
</div>
</div>
<div class="modal-body">
<div id="user">
<h1 id="name"></h1>
<p id="email"></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
JS code :
<script>
/* eslint disabled */
$(
() => {
$('#uid').click(
(e) => {
var uid = $(event.target).data('id');
$.ajax({
type: 'POST',
url: 'users/' + uid,
data: {'_token': $("input[name='_token']").val()},
success: function(data){
// or use : $('#user').html(data);
$('#user #name').text(data.name);
$('#user #email').text(data.email);
}
});
}
);
}
);
</script>
Controller (Route) POST request :
Route::post('users/{id}', function ($id) {
$data = \DB::table('users')->where('id', $id)->first();
return response()->json($data, 200);
});
This code allow to the client , for each user in db there're modal button to open popup , and after clicking on user's button i get a pop up with mail and name for this user
My modal window is not getting opened. It seems there is an issue with my php.action action - or within ajax call.
Please can someone have a look?
My javascript - alert shows the record id.
$(document).ready(function(){
// Fetch single data
$(document).on("click","#editId",function(e){
e.preventDefault();
//alert("you click edit button");
var action ='FetchSingle';
var editId = $(this).attr('data-editId');
alert("you click edit button:" + editId);
$('#edit').modal('show'); //This works but not wihtin success:function(data)
$.ajax({
url:"action.php",
method:"POST",
data:{action:action,editId:editId},
dataType:"json",
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
alert(err.Message);
},
success:function(data){
$('#name').val(data.name);
$("#designation").val(data.designation);
$("#sex").val(data.sex);
$('#edit').modal('show');
}
});
});
});});
Here is my action.php
if (isset($_POST['action'])) {
if ($_POST['action'] =='FetchSingle') {
$editId = $_POST['editId'];
$output = '';
$sql = "SELECT * FROM tbl_employee_info WHERE id='".$editId."'";
$data = $DBObj->select($sql);
foreach ($data as $value) {
$output['image'] = $value['image'];
$output['name'] = $value['name'];
$output['designation'] = $value['designation'];
$output['sex'] = $value['sex'];
$output['uploaded_hidden_image'] = '<img width="70px" height="70px" src="upload/'.$value['image'].'">';
}
echo json_encode($output);
} //end of isset post action
} //end of if isset post
my Modal window
<!-- Modal -->
<div class="modal fade" id="edit" 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">Edit Details</h4>
</div>
<div class="modal-body">
<div class="form-group pmd-textfield pmd-textfield-floating-label">
<label for="name" class="control-label">Name</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<div class="form-group pmd-textfield pmd-textfield-floating-label">
<label for="Designation" class="control-label">Designation</label>
<input type="text" class="form-control" name="designation" id="designation">
</div>
<div class="form-group pmd-textfield pmd-textfield-floating-label">
<label for="sex" class="control-label">Select a sex</label>
<input type="text" class="form-control" name="sex" id="sex">
<select class="select-simple form-control pmd-select2" name="sex" id="sex">
<option></option>
<option value="1">Male</option>
<option value="2">Fmale</option>
<option value="3">Others</option>
</select>
<!-- end of display data here -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<!-- /.Modal -->
Any suggestions or a way to debug the issue would be highly appreciated. The problems seems to be in my action.php script.
I'm working with DataTables and CodeIgniter, and Right now I want to be able to edit any row in my table, and I'm already doing it! But I'm only updating the row that has the ID = 1, that's because in my controller I defined this :
$this->db->set('NameContact', $_POST['Name']);
$this->db->set('NumberContact', $_POST['Number']);
$this->db->where('IdContact', 1);
$this->db->update('contacts');
As you can see I need to get the id of the selected row in the table to pass it with the $_POST method. But I can't seem to find a right way to do it via JS. Any help pls?
My HTML:
{Contacts}
<tr>
<td id="{IdContact}">{IdContact}</td>
<td>{NameContact}</td>
<td>{NumberContact}</td>
<td><a data-toggle="modal" data-target="#EditNumber"> <i class="fa fa-edit"></i></a></td>
</tr>
{/Contacts}
My JS:
function EditPhoneNumber(){
var Name = document.getElementById("EditName").value;
var Number = document.getElementById("EditNumber").value;
console.log(Name);
console.log(Number);
jQuery.ajax({
type: "POST",
url: 'http://localhost/projeto/index.php/Backoffice_Controller/EditContacts',
data: {Name: Name, Number: Number},
success: function (response) {
console.log("success");
console.log(response);
},
error: function(response){
console.log("error");
console.log(response);
}
});
}
Here is my Modal:
<div id="EditNumber" class="modal fade" role="dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Editar Contacto</h4>
</div>
<div class="modal-body">
<input type="text" name="NameContact" placeholder="Name" id="EditName"><br>
<input type="text" name="NumberContact" placeholder="Number" id="EditNumber">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-default" onclick="EditPhoneNumber()">Editar</button>
</div>
</div>
Pass data-id into your html tag like below and on tag click you need to manage function instead of opening modal directly.Look at the below code.
HTML
{Contacts}
<tr>
<td id="{IdContact}">{IdContact}</td>
<td>{NameContact}</td>
<td>{NumberContact}</td>
<td> <i class="fa fa-edit"></i></td>
</tr>
{/Contacts}
In your Modal
<div id="EditNumber" class="modal fade" role="dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Editar Contacto</h4>
</div>
<div class="modal-body">
<input type="text" name="NameContact" placeholder="Name" id="EditName"><br>
<input type="text" name="NumberContact" placeholder="Number" id="EditNumber">
<input type="hidden" name="NumberContactId" id="EditId">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-default" onclick="EditPhoneNumber()">Editar</button>
</div>
</div>
</div>
JS
function editNumberModal(obj){
vat id = jQuery(obj).attr('data-id');
jQuery('#EditNumber').modal();
}
function EditPhoneNumber(){
var Name = document.getElementById("EditName").value;
var Number = document.getElementById("EditNumber").value;
var Id = document.getElementById("EditId").value;
console.log(Name);
console.log(Number);
jQuery.ajax({
type: "POST",
url: 'http://localhost/projeto/index.php/Backoffice_Controller/EditContacts',
data: {Name: Name, Number: Number, Id:Id},
success: function (response) {
console.log("success");
console.log(response);
},
error: function(response){
console.log("error");
console.log(response);
}
});
}
$(document).on('submit','#form_pem', function(event){
event.preventDefault();
var kodebayar = $('#kodebayar').val();
var nama = $('#nama').val;
var harga = $('#harga').val;
var postData = new FormData(this);
if(kodebayar != '' && nama != '' && harga != ''){
$.ajax({
url:"<?=site_url('bpem/user_action')?>",
method:"POST",
data:postData,
contentType:false,
proccessData:false,
success: function(data)
{
alert(data);
$('#form_pem')[0].reset();
$('#modalpem').modal('hide');
dataTable.ajax.reload();
}
});
}
else{
alert("Silahkan isikan semua data!");
}
});
this is my JS
<div class="modal fade text-xs-left" id="modalpem" tabindex="-1" role="dialog" aria-labelledby="myModalLabel35" aria-hidden="true">
<div class="modal-dialog modal-sm">
<form method= "post" id="form_pem">
<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>
<h3 class="modal-title text-xs-center">Tambah Biaya Pembayaran</h3>
</div>
<div class="modal-body">
<fieldset class="form-group floating-label-form-group">
<label for="Kode">Kode <span class="required">*</span></label>
<input type="text" class="form-control" name="kodebayar" id="kodebayar" placeholder="Kode Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="nama">Nama <span class="required">*</span></label>
<input type="text" class="form-control" name="nama" id="nama" placeholder="Nama Pembayaran">
</fieldset>
<fieldset class="form-group floating-label-form-group">
<label for="projectinput7">Biaya Perbulan <span class="required">*</span></label>
<div class="input-group">
<span class="input-group-addon">Rp.</span>
<input type="number" class="form-control" placeholder="Biaya Perbulan" aria-label="Amount (to the nearest dollar)" name="harga" id="harga">
<span class="input-group-addon">.00</span>
</div>
</fieldset>
</div>
<div class="modal-footer">
<input type="reset" class="btn btn-grey" value="Bersihkan">
<input type="submit" class="btn btn-warning" name="action" id="action" value="Tambah">
</div>
</div>
</form>
</div>
</div>
and this is the view.
But i got an error like
TypeError: 'append' called on an object that does not implement interface FormData.
Did i forget something to add? What should i do? thankyou for your help
Need a correction for typo :)
proccessData:false
should be
processData: false
To avoid FormData errors make sure that the ajax options must be like
$.ajax({
url : "url",
type: "POST",
data : postData,
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR){
//
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});