Laravel Patch AJAX - javascript

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.

Related

AJAX Codeigniter getting data for modal

I've been using CodeIgniter for a little while, and I'm trying to get a modal to work. I'm using bootstrap library so the model itself is rather simple to show. The thing is I'm trying to load it with dynamic information from a database using ajax. But I can't seem to trigger it. My script doesn't do anything, I've been trying for quite a while now.
function fun(control){
$.ajax({
url:'<?=base_url()?>admin/proveedores/userDetails/'+control.id,
method: 'post',
data: {uid: control.id},
dataType: 'json',
success: function(response){
var len = response.length;
if(len > 0){
// Read values
var uname = response[0].razon_social;
var name = response[0].cuit;
var email = response[0].rubro;
$('#suname').text(uname);
$('#sname').text(name);
$('#semail').text(email);
}
</script>
The HTML PART
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<div >
Username : <span id='suname'></span><br/>
Name : <span id='sname'></span><br/>
Email : <span id='semail'></span><br/>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The function call
<tr id="<?= $e['id'] ?>" onclick="fun(this)" data-toggle="modal" data-target="#myModal" >
The Controller
public function userDetails($cid){
// POST data
// $postData = $this->input->post();
// get data
$data = $this->model_proveedores->get($cid);
echo json_encode($data);
}
I think it will helpful for you.
Please keep the modal content inside a div with id myModal and call ajax within the modal show action.
The Modal
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog" role="document">
// your modal content
</div>
</div>
The Call Button
<tr data-id="<?= $e['id'] ?>" data-toggle="modal" data-target="#myModal">
The Script
var modal = $("#myModal");
modal.on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var id = button.data('id');
$.ajax({
url : '<?= base_url() ?>admin/proveedores/userDetails/'+id,
type : 'post',
dataType : 'json',
data : { uid: id},
success : function(response)
{
var len = response.length;
if(len > 0){
// Read values
var uname = response[0].razon_social;
var name = response[0].cuit;
var email = response[0].rubro;
$('#suname').text(uname);
$('#sname').text(name);
$('#semail').text(email);
}
},
error : function(xhr)
{
console.log(xhr)
}
});
});
Your response is JSON encoded. You must decode that before using it as an object.
response=JSON.parse(response);

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!".

Ajax JQuery send data to the php script

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>

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