hi guys i have problem when update my data using codeigniter and ajax, when update data my form validation always return false.. but when insert data thats work normal. this is my code, i hope someone can help me, thx a lot..
my controller
public function updateFakultas()
{
$id = $this->input->post('id', true);
$fakultas = $this->input->post('fakultas', true);
$this->form_validation->set_rules('fakul', 'Fakultas', 'required');
if ($this->form_validation->run() == FALSE) {
$hasil = [
'error' => true,
'fakultas' => form_error('fakul', '<p class="mt-3 text-danger">', '</p>'),
];
echo json_encode($hasil);
} else {
$this->Fakultas_model->updateData($id, $fakultas);
$hasil = [
'error' => false
];
echo json_encode($hasil);
}
}
ajax
$('#data_fakultas').on('click', '.item_edit', function() {
var id = $(this).attr('data');
$('#id_fakultas').val("");
$('#fakultas2').val("");
$('#fakultas_error2').html("");
$.ajax({
type: 'POST',
url: '<?= base_url() ?>fakultas/getFakultas',
data: {
id: id
},
dataType: 'json',
success: function(data) {
$('#ModalUbahFakultas').modal('show');
$('[name="id"]').val(data[0].id_fakultas);
$('[name="fakul"]').val(data[0].nama_fakultas);
}
})
})
$('#ubah-fakultas').on('click', function() {
var id = $('#id_fakultas').val();
var fakultas = $('#fakultas2').val();
$.ajax({
type: 'post',
url: '<?= base_url() ?>fakultas/updateFakultas',
data: {
id: id,
fakultas: fakultas
},
dataType: 'json',
success: function(data) {
console.log(data);
if (data.error == false) {
$('#ModalUbahFakultas').modal('hide');
swal("Good Job!", "Data berhasil diubah", "success");
$('#fakultas_error2').html("");
$('#fakultas2').val("");
tampil_data_fakultas();
} else {
$('#fakultas_error2').html(data.fakultas);
$('#fakultas2').on('keyup', function() {
$('#fakultas_error2').html("");
})
}
}
})
})
my view
<div class="modal fade" id="ModalUbahFakultas" tabindex="-1" role="dialog" aria-labelledby="UbahLabelFakultas" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="UbahLabelFakultas">Form Ubah Fakultas</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form class="form-horizontal">
<input type="hidden" id="id_fakultas" name="id">
<div class="form-group">
<label for="fakultas2">Nama Fakultas</label>
<input type="text" class="form-control" id="fakultas2" name="fakul">
<div id="fakultas_error2"></div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>
<button type="submit" class="btn btn-primary" id="ubah-fakultas">Update Data</button>
</div>
</div>
</div>
</div>
i already try to console when ajax post, its fine but i think this problem with form_validation->run()..
you are making a silly mistake while setting validation rule.
your code
$this->form_validation->set_rules('fakul', 'Fakultas', 'required');
Change to
$this->form_validation->set_rules('fakultas', 'Fakultas', 'required');
Your mistaking post variable name "fakultas" with "fakul" while making an Ajax post.
Check your Javascript code
$.ajax({
type: 'post',
url: '<?= base_url() ?>fakultas/updateFakultas',
data: {
id: id,
fakultas: fakultas
},
dataType: 'json',
success: function(data) {
console.log(data);
if (data.error == false) {
$('#ModalUbahFakultas').modal('hide');
swal("Good Job!", "Data berhasil diubah", "success");
$('#fakultas_error2').html("");
$('#fakultas2').val("");
tampil_data_fakultas();
} else {
$('#fakultas_error2').html(data.fakultas);
$('#fakultas2').on('keyup', function() {
$('#fakultas_error2').html("");
})
}
}
})
Related
I have a modal that updates information on countries.
// Partial code of the modal
<div id="EditModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Edit <label id="EntityType"></label></h4>
</div>
<div class="modal-body">
<div class="row">
#yield('EditModalBody')
</div>
</div>
<div class="modal-footer" style="text-align: center">
{{ Form::submit('Save', ['class' => 'btn btn-success', 'id' => 'editBtn']) }}
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
I'm trying to implement this with AJAX, so that if there are any errors, the modal does not close and the error messaged appear under each input field.
This is my JS:
<script type="text/javascript">
$("#EditModal").submit(function (e) {
e.preventDefault();
var selector = $(this);
$.ajax({
type: 'PATCH',
dataType: 'json',
url: selector.attr("action"),
data: selector.serialize(),
success: function (data) {
if (data.success) {
alert('go go go');
} else {
// for debugging
alert('data');
}
},
error: function (xhr, textStatus, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
I am getting "405 Method not allowed" error, although I declared my controller as a "ressource" like this:
Route::resource('country', 'CountryController',
['except' => ['show']]);
If I do php artisan route:list I can see that the PATCH route is declared.
Any ideas?
EDIT 1:
This is (part of) my controller:
public function update($id, Request $request)
{
$validator = Validator::make($request->all(), $this->getRules(), $this->getMesssages());
if ($validator->fails()) {
$json = new stdClass();
$json->success = false;
$json->errors = $Validator->errors();
}
else {
$json = new stdClass();
$json->success = true;
}
return Response::json($json);
EDIT 2:
So I added this <input type="hidden" name="_token" value="{{{ csrf_token() }}}"/> in my modal and I no longer get the 405 error. I still have a problem that I always get the "error" part of my JS (only that now I get status 0)
type: 'PATCH' does not exists on HTTP methods thus will not be recognized by Laravel.
Try this:
$.ajax({
type: 'POST',
dataType: 'json',
url: selector.attr("action"),
data: {
'_method': 'PATCH',
'data': selector.serialize(),
},
You have to submit the method PATCH as _method Post data.
Edit
Your controller function looks wrong. The correct order would be
public function update(Request $request, $id)
instead of
public function update($id, Request $request)
OT: I already submitted an addition for the Laravel documentation that gives you a hint about this problem but it was rejected with no comment.
I need to get data from html with javascript and then send to PHP and then send back to javascript the result of the php code.
So I searching around but I can't find code who working in my case.
This is my javascript code when I try to send data to auth-req.php file
(function($){
$('#authModal').modal('show');
$('#auth-btn').click(function (e) {
$.ajax({
url: './libraries/auth-req.php',
type: 'POST',
data: { 'key' : $('#client-security-key').val() },
success: function (data) {
alert(data + ' Success');
},
error: function (data) {
alert(data + ' Error');
},
complete: function () {
alert(data + ' Complete');
},
cache: false,
contentType: false,
processData: false
});
});
})(jQuery);
This is my PHP code when I try to working with data sended from javascript file
echo 'I can make the check of the security key ' . $_POST['key'];
And my html file
<form class="form" method="post">
<div class="modal fade" id="authModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 style="color: #fff !important" class="modal-title" id="myModalLabel">Authentication</h4>
</div>
<div class="modal-body">
<div class="col-md-10 col-md-offset-1">
<div class="form-group col-md-12">
<label for="client-security-key" class="control-label">Security key</label>
<input type="text" id="client-security-key" name="client_security_key" class="form-control" required />
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-primary" id="auth-btn" value="Authenticate" />
</div>
</div>
</div>
</div>
</form>
So I need the data who user put in input with id="client-security-key" I want to get with javascript and send to php file to make some operations. But when I try and send is show me this message (error):
Notice: Undefined index: client_security_key in D:\xampp\htdocs\Smart-Grow-Controller\libraries\auth-req.php on line 6
I can make the check of the security key Success
What I'm doing wrong?
You need to comment two lines of your code -
//contentType: false,
//processData: false
(function($){
$('#authModal').modal('show');
$('#auth-btn').click(function (e) {
$.ajax({
url: './libraries/auth-req.php',
type: 'POST',
data: { 'key' : $('#client-security-key').val() },
success: function (data) {
alert(data + ' Success');
},
error: function (data) {
alert(data + ' Error');
},
complete: function () {
alert(data + ' Complete');
},
cache: false,
//contentType: false,
//processData: false
});
});
})(jQuery);
I thought by setting these headers to false server script is unable to process data. Hope this will help you.
You are set contentType: false and processData: false.Thus it is sending non-processed data (send a DOMDocument) So you need to create new FormData in your data .
change this line from
data: { 'key' : $('#client-security-key').val() },
like below
data: new FormData($('form')[0]),
Also called post name as your input name
echo 'I can make the check of the security key ' . $_POST['client_security_key'];
Try the following, have removed some code to make it clearer. I've also prevented the form submit on enter.
<?php
// if key value has been posted to page
if(isset($_POST['key'])){
// if the key isnt blank echo key value is xxx
if($_POST['key'] != ''){
echo 'Key value is:' . $_POST['key'];
}else{
// key is blank, error
echo "Error!";
}
exit;
}
?>
<script src="http://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript"></script>
<form class="form" method="post">
<div class="modal fade" id="authModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 style="color: #fff !important" class="modal-title" id="myModalLabel">Authentication</h4>
</div>
<div class="modal-body">
<div class="col-md-10 col-md-offset-1">
<div class="form-group col-md-12">
<label for="client-security-key" class="control-label">Security key</label>
<input type="text" id="client-security-key" name="client_security_key" class="form-control" required />
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-primary" id="auth-btn" value="Authenticate" />
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(function($){
$('#auth-btn').click(function (e) {
$.ajax({
type: 'POST',
url: '/auth-req.php',
data: 'key=' + $('#client-security-key').val(),
success: function (result) {
alert(result);
},
error: function (data) {
alert(result);
}
});
return false;
});
// prevent form submit on enter
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
</script>
My code was working fine before. But Now it is not working. I am working on codeigniter and I am uploading a file using jquery ajax. I donot know why my code stop working. If you can find the issue please let me know.
Here is the controller code
public function updatedp()
{
$var = $_FILES['fileUp'];
$img=$_FILES['fileUp'];
$config['upload_path'] = 'webim/dp_images';
$config['overwrite'] = 'TRUE';
$config["allowed_types"] = 'jpg|jpeg|png|gif';
$config["max_size"] = '1400';
$config["max_width"] = '1400';
$config["max_height"] = '1400';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('fileUp'))
{
$this->data['error'] = $this->upload->display_errors();
echo json_encode(array("result"=>$this->data['error']));
exit;
} else {
$data=array('active'=>0);
$this->db->where('userid','1');
$this->db->update('music_user_dp',$data);
$uname['uname'] =$this->session->all_userdata('uname');
$uname['id'] =$this->session->all_userdata('id');
$post_data = array(
'id' => '',
'userid' => $uname['id']['id'],
'profilepic'=>$var['name'],
'updatedate' => date("Y-m-d H:i:s"),
'active' => '1'
);
$this->Userpage_model->insert_dp_to_db($post_data);
echo json_encode(array("result"=>"Success"));
exit;
}
}
My jquery code which calling above function:
$("#btnupdate").click(function(event){
if($("#fileupload2").val() != ''){
if (typeof FormData !== 'undefined') {
var form = $('#formname').get(0);
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "Userpage/updatedp",
data: formData,
mimeType:"multipart/form-data",
dataType: 'json',
xhr: function() {
return $.ajaxSettings.xhr();
},
cache:false,
contentType: false,
processData: false,
success: function(result){
toastr8.info({
message:'Profile Picture Updated',
title:"New Image Uploaded",
iconClass: "fa fa-info",
});
}
});
event.preventDefault();
}
} else {
toastr8.info({
message:'Error Occured',
title:"Please try again",
iconClass: "fa fa-info",
});
}
});
HTML:
<div class="modal fade" id="myModal" role="dialog">
<form enctype="multipart/form-data" name="formname" id="formname" method="post" action="">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header ">
<script type="text/javascript">
$(document).ready(function(){
$('#mgupload-dp').click(function(e){
$('#fileupload2').click();
e.preventDefault();
});
});
</script>
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Create profile picture</h4>
</div>
<div class="modal-body">
<div class="text-center" style="width:100%"> <img src="<?php echo base_url(); ?>img/profile.png" alt="add dp" id="pop-dp" >
<button type="button" class="btn btn-default text-center" id="mgupload-dp">Choose picture to upload</button>
<input type="file" id="fileupload2" name="fileUp" class="hidden-dp" accept="image/*">
</div>
<div class="clearfix"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="btnupdate">Update Picture</button>
</div>
</div>
</div>
</div>
</form>
</div>
Files are not uploading and I am getting this error
A PHP Error was encountered
Severity: Notice
Message: Undefined index: fileUp
Filename: controllers/Userpage.php
Open the Firebug in FF.
Click on the ajax call URL under Console.
See what are passed under "Post" tab.
If fileUp is present there, use $this->input->post('fileUp'); to fetch the contents.
Here is a screenshot of the console.I am a beginner in working with json and Ajax and I am trying to write a login for my website, but I don't know why it is not working.
login-register.js
function loginAjax(){
$.post( "login.js", function( data ) {
if(data == 1){
window.location.replace("/sportime.html");
} else {
shakeModal();
}
});
}
login.js
$(document).ready(function()
{
$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');}
});
}
return false;
});
});
ajaxLogin.php
<?php
include("conectare.php");
session_start();
if(isset($_POST['username']) && isset($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($mysqli,$_POST['username']);
//Here converting passsword into MD5 encryption.
$password=md5(mysqli_real_escape_string($mysqli,$_POST['password']));
$result=mysqli_query($mysqli,"SELECT uid FROM users WHERE username='$username' and password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
$_SESSION['login_user']=$row['uid']; //Storing user session value.
echo $row['uid'];
}
}
?>
sportime.php
<?php
session_start();
if(!empty($_SESSION['login_user']))
{
header('Location: sportime-loggedin.php');
}
?>
and this is the modal for the login from sportime.php
<div class="modal fade login" id="loginModal">
<div class="modal-dialog login animated">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Login</h4>
<div class="content text-center"><h5>Use your University credentials</h5></div>
</div>
<div class="modal-body">
<div class="box">
<div class="content">
<div class="error"></div>
<div class="form loginBox">
<form method="post" action="" onsubmit="loginAjax(); return false;" accept-charset="UTF-8">
<input id="email" class="form-control" type="text" placeholder="University ID" name="id">
<input id="password" class="form-control" type="password" placeholder="Password" name="password">
<input class="btn btn-default btn-login" type="submit" value="Login">
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Why are you trying to post to a js file?
function loginAjax(){
$.post( "login.js", function( data ) {
if(data == 1){
window.location.replace("/sportime.php");
} else {
shakeModal();
}
});
}
Your loginAjax function should look like this
function loginAjax() {
var username = $("#email").val();
var password = $("#password").val();
var dataString = 'username=' + username + '&password=' + password;
if ($.trim(username).length > 0 && $.trim(password).length > 0) {
$.ajax({
type: "POST",
url: "ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function() {
$("#login").val('Connecting...');
}
}).success(function(data) {
if (parseInt(data) > 1) {
window.location.replace("/sportime.html");
} else {
shakeModal();
}
});
}
return false;
}
EDIT
You have misplaced the ids.
Replace
var username = $("#username").val();
with var username = $("#email").val();
I've following code for file upload :
HTML code :
<a href="#" id="promotion_status_1">
<button type="button" class="btn btn-default brmodalbtn" data-toggle="modal" data-target="#BrandImageModal" id="1">On</button>
</a>
<div class="container">
<div class="modal fade" id="BrandImgeModaal">
<div class="modal-dialog">
<div class="modal-content">
<form id="form" enctype="multipart/form-data" role="form">
<input type="text" class="form-control" name="brand_id" id="brand_id" value="{$data.id}">
<input type="text" name="admin_url" id="admin_url" value="http://localhost/abc.com">
<input type="text" name="op" value="upload_brand_image">
<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">Brand Image</h4>
</div>
<div class="modal-body">
<div id="messages"></div>
<input type="file" name="file" id="file">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
jQuery AJAX Code :
$('#form').submit(function(e) {
var form = $(this);
var formdata = false;
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
type : 'POST',
url : 'manufacturers.php',
cache : false,
data : formdata ? formdata : form.serialize(),
//data : formdata ? formdata : form.serialize() + '&' + $.param({'op':'upload_brand_image'}),
contentType : false,
processData : false,
success: function(response) {
if(response != 'error') {
//$('#messages').addClass('alert alert-success').text(response);
// OP requested to close the modal
$('#BrandImgeModaal').modal('hide');
} else {
$('#messages').addClass('alert alert-danger').text(response);
}
}
});
e.preventDefault();
});
Now the PHP code is as follows :
$request = $_REQUEST ;
switch( $op ) {
case "add":
case "upload_brand_image":
//print_d($request);
//here if error comes in validation I've an array of errors which needs to be printed in AJAX response. Following is the array
$error_messages = array(
"email" => "Email Id can't be blank",
"email_invalid" => "Email Id is not valid"
);
die;
break;
}
My issue is how should I use the array $error_messages in ajax response and if the error doesn't come then the success message should be passed to ajax function instead of this $errror_messages array.
How to achieve this? Can someone please help me in this regard?
Thanks.
why not use json format?
$.ajax({
dataType : 'json',
........
........
success: function(response) {
if(response.email_invalid){
//do something
}else{
//do something
}
}
});
then in your php echo the error
$error_messages = array(
"email" => "Email Id can't be blank",
"email_invalid" => "Email Id is not valid"
);
echo json_encode($error_messages);