Ajax JQuery send data to the php script - javascript

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>

Related

form validation codeigniter 3 with ajax always false when update data

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("");
})
}
}
})

PHP redirect after form POST

i'm making a download button on my website that opens a modal with a request for password and then if the password is right should take the user to the real download. This is my javascript:
function submit() {
var postData = $("#passwd").serialize();
//alert(postData);
$.ajax({
type: "POST",
url: "http://www.redcraft.it/submit.php",
data: postData,
success: function(redirect) {
alert('Submitted')
}/*,
error: function() {
alert('Failure');
}*/
});
}
and this is my php:
<?php
function redirect() {
$data = $_POST["postData"];
if($data == is_null()) {
echo "Error";
} else {
echo "<script>window.open('http://www.google.com/" + $data + "', '_self')</script>";
}
}
?>
I'm using echo with a js script in php to try different methods to redirect since header() doesn't work. I'm sure the php is correctly called because i've added a row to create a file when the function is called, and the file is correctly generated.
Please, i need your help and don't kill me if i've made some "noobie" errors.
Edit:
This is the html of the modal:
<div class="modal fade bs-modal-sm" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
<div class="modal-dialog modal-mediom">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Download mondo RedCraft</h4>
</div>
<div class="modal-body">
<p>Per scaricare il mondo della redcraft inserisci la password che trovi nel video di presentazione del download!</p>
<div class="control-group">
<label class="control-label" for="userid">Password:</label>
<div class="controls">
<input id="passwd" required="" name="passwordinput" type="input" class="form-control input-medium">
</div>
</div>
<div class="control-group">
<label class="control-label" for="confirmsignup"></label>
<div class="controls">
<button id="confirm" onClick="submit()" name="confirmsignup" class="btn btn-primary" data-dismiss="modal">Conferma</button>
</div>
</div>
</div>
</div>
</div>
</div>
just add one div in your html
<div id="outputredirect"></div>
and add below line in your ajax success or replace with your alert
if(redirect == "Error"){
alert(redirect);
} else {
jQuery('#outputredirect').html(redirect);
}
Your javascript code should redirect to the url returned by the php script :
function submit() {
var postData = $("#passwd").serialize();
//alert(postData);
$.ajax({
type: "POST",
url: "http://www.redcraft.it/submit.php",
data: postData,
success: function(redirect) {
location.href(redirect);
}/*,
error: function() {
alert('Failure');
}*/
});
}

Show error in modal window, when something went wrong

I need some help. I need to show up the error, when something went wrong in my modal window. Right now, is just closing, also when there are error. I tried to find some Ajax and Javascript to solve the problem, but I can’t get it to work well. Can someone help me and thanks for your help?
if($result->num_rows == 0) {
$this->errors[] = "User not fund";
}else{
Modal window
<!-- Modal -->
<div class="modal fade" id="resetPassword" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div style="background-color:#3a3a38;" class="modal-content">
<div class="modal-header">
<h4 style="color:#fff" class="modal-title">Nulstill adgangskode</h4>
</div>
<div class="modal-body">
<form role="form" action="index.php" method="post">
<div class="form-group">
<label class="sr-only"
for="email_forgot">Email</label>
<input type="text" name="email_forgot"
placeholder="email..." class="form-username form-control" id="form-username">
</div>
<input style="margin-left:auto;margin-
right:auto;" data-backdrop="static" data-keyboard="false" class="btn-lg btn-
default btn-block" type="submit" value="send" name="forgot">
</form>
<?php
if (isset($user)) {
if ($user->errors) {
foreach ($user->errors as $error) {
echo '<a style="color:red">'.$error.'</a>';
}
}
if ($user->messages) {
foreach ($user->messages as $message) {
echo '<span style="color:red">'. $message.'</span>';
}
}
}
?>
</div>
</div>
</div>
Submit the form with ajax and display the error with javascript not with php. Now your page reload and you loss the data.
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
$('form').on('submit', function(event){
event.preventDefault();
var formData = $("form").serializeArray();
$.ajax({
url: "index.php",
type: "POST",
data: formData,
dataType: 'json',
success:function(data){
$('body').html('<h1>Thank You</h1>');
},
error:function(){
$('body').html('<h1>Error</h1>');
}
});
});
There are two different options when it comes down to posting your data; you could ajax-validate the data (which means that you'd validate the content in a different file), or you'd ajax-submit the data (which means that you'd validate and use the data in a different file).
I'd suggest ajax-submitting, seeing as that would suit te needs of your form.
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
var $form = $('#resetPassword form');
$form.submit(function(event) {
event.preventDefault();
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function ( response ) {
if(response != "") {
alert("Errors: " + response);
} else {
alert("Password reset!");
}
}
});
});
</script>
For it to work you'd have to use the METHOD attribute on the form to point to a processing file, which you'll have to create (for example; ajax-reset-password.php). In there just print all errors, if there are any. If no errors occurred, just don't print anything. The javascript above will show the message "Password reset!".

Laravel Patch AJAX

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.

Undefined Index error (Codeigniter)

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.

Categories