Re-execute php loop with ajax - javascript

I am using laravel 5.4.
I have many clinics in my database. I just want to retrieve all the clinics and put a delete button on each clinic. Whenever a user clicks the delete button the the clinic should be removed from the database and clinics should be updated in the front end.
This is my code.
#foreach($doctor->clinics as $clinic)
<form method="POST"
action="{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}"
id="formremoveclinic{{$clinic->id}}">
{{csrf_field()}}
<button class="btn btn-sm btn-danger pull-right">
<span class="glyphicon glyphicon-remove"></span>
</button>
</form>
<p class="text-muted">Clinic {{$i++}}</p>
<p class="text-muted">{{$clinic->address}}</p>
<hr>
<script>
$("#formremoveclinic{{$clinic->id}}").submit(function(e){
$('#loading').show();
e.preventDefault();
$.ajax({
url: "{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}",
type: "DELETE",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$('#loading').hide();
},
error: function(data){
var errors = data.responseJSON;
console.log(errors);
$('#loading').hide();
}
});
});
</script>
#endforeach
I don't want to reload the page whenever a clinic is removed. So, how can I re-execute this loop, whenever a clinic is successfully removed using ajax.

A better way to approach this might be to just remove the row using javascript. In the same function where you hide the loader, you can also remove the form from the dom.
Like so:
#foreach($doctor->clinics as $clinic)
<div id="clinic{{$clinic->id}}">
<form method="POST"
action="{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}"
id="formremoveclinic{{$clinic->id}}">
{{csrf_field()}}
<button class="btn btn-sm btn-danger pull-right">
<span class="glyphicon glyphicon-remove"></span>
</button>
</form>
<p class="text-muted">Clinic {{$i++}}</p>
<p class="text-muted">{{$clinic->address}}</p>
<hr>
<script>
$("#formremoveclinic{{$clinic->id}}").submit(function(e){
$('#loading').show();
e.preventDefault();
$.ajax({
url: "{{url('doctors/'.$doctor->id.'/removeclinic/'.$clinic->id)}}",
type: "DELETE",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$('#loading').hide();
// Fade out and remove the form element
$("#clinic{{$clinic->id}}").fadeOut(300, function() {
$(this).remove();
});
},
error: function(data){
var errors = data.responseJSON;
console.log(errors);
$('#loading').hide();
}
});
});
</script>
</div>
#endforeach
This way you don't have to write another ajax function.

Related

in Laravel I GOT AN ERROR The POST method is not supported for this route. Supported methods: GET, HEAD

I am trying to when the customer wants to upload an image or logo I want this image to display it in front of him by span element for him to make sure he uploaded the correct image to the system but when I press on upload I got POST method is not supported for this route. Supported methods: GET, HEAD. error
here is my code in card_view_blade
<div class="form-group row">
<div class="col-md-8">
<form method="post" id="upload-image-form" enctype="multipart/form-data">
#csrf
<div class="input-group" data-type="image">
<input type="file" name="file" class="form-control" id="image-input">
<button type="submit" class="btn btn-success">Upload</button>
</div>
</form>
</div>
<div class="col-md-4">
<div class="alert" id="message" style="display: none"></div>
<span id="uploaded_image"></span>
</div>
</div>
here is the js code
#section('script')
<script type="text/javascript">
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#upload-image-form').submit(function(e) {
e.preventDefault();
let formData = new FormData(this);
$('#message').hide().html('');
$.ajax({
type:'POST',
url: `/upload-images`,
data: formData,
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success: (data) => {
console.log("success-",data);
if (data) {
this.reset();
$('#message').show().html(data.message);
$('#message').addClass(data.class_name);
$('#uploaded_image').html(data.uploaded_image);
}
setTimeout(function(){
$('#message').hide().html('');
}, 3000);
},
error: function(data){
console.log("error-",data);
// $('#image-input-error').text(data.responseJSON.errors.file);
$('#message').show().html('Something went wrong');
$('#message').addClass('danger');
$('#uploaded_image').html('');
setTimeout(function(){
$('#message').hide().html('');
}, 3000);
}
});
});
})
</script>
#endsection
route code
Route::post('/upload-images', 'CheckoutController#storeImage' )->name('images.store');
Nothing seems to be wrong with the code perhaps the routes are cached. Try clearing them first and see if the problem is resolved or not with the following commands:
php artisan route:clear

JQuery not attaching dynamically generated checkbox to modal with first click of button

When a click event fires, a modal will be presented to end-user and pre-populated with checkboxes.
The issue I am encountering is that at the first click of the button, the pre-populated checkboxes do not render on the modal.
If I exit out of the modal and click the button again, the modal then properly displays the checkboxes.
Why is this happening?
(".changeCheckBoxList").click(buttonClickHandler);
function buttonClickHandler() {
var button = $(this);
swal({
html: true,
title: ""
text: $('#chkbox')
},
function(isConfirm)){
if (isConfirm)
{
$.post({
type: 'POST',
url: '/SomeController/AddCheckboxesData',
datatype: 'json',
data: {
//
}
}).done (function(results) {
});
}
};
$.ajax({
type: 'GET',
datatype: 'html',
url: '/SomeController/SomeActionResult' //This is getting back the correcting data
}).done(function (results) {
//dynamically generating the checkboxes below
$.each(results, function(key, value) {
var div = $('<div><input type="checkbox" value="someValue" + <label for= key></label></div>');
div.find('label').text(results[key].Name);
$('#chkbox').append(div);
});
}
}
<button class="btn btn-default changeCheckBoxList" type="button" data-id="">n</button>
<div class="modal-body">
<form id="chkbox">
<div>
<label for="examplecheckbox"> Click a checkbox</label>
<input type="text" id="">
</div>
</form>
</div>

Any way to show div on same page using jquery? Div class has parameters. So normal Div.show() is not working as we can't pass parameter object in it

<!-- Search results tab -->
<div id="testingClass" style="display:none;">
<h3 class="theme-background">Course Results (${courseResponseList.getCourses().size()})</h3>
<br>
<c:forEach items="${courseResponseList.getCourses()}" var="course"
varStatus="loop">
<form action="/search/course/edit" method="post">
<div class="panel panel-default panel-shadow">
<div id="${course.getCourseID()}-panel-heading" class="panel-heading" data-toggle="collapse"
data-target="#${course.getCourseID() }" aria-expanded="false">
<c:set var="showAssignButton" value="false" />
<c:forEach items="${enrolledCourseList}" var="courseEnrolled"
varStatus="loop">
<c:if
test="${courseEnrolled.getCourseID() eq course.getCourseID()}">
<c:set var="showAssignButton" value="true" />
</c:if>
</c:forEach>
<tags:courseNameAndDescription courseResponse="${course}"
showAssignButtonValue="${showAssignButton}" />
</div>
<div id="${course.getCourseID() }" class="panel-body collapse">
<tags:courseMetaData courseResponse="${course}" />
</div>
</div>
</form>
</c:forEach>
</div>
Want to show above div.
jquery script.
<script>
jQuery.noConflict();
$("#searchButton").click(function (e) {
e.preventDefault();
var data = [];
$.ajax({
type: "GET",
contentType : "application/json",
url : "/search/getCourseList",
data : $("#courseSearchForm").serialize(),
contentType:"application/json; charset=utf-8",
dataType:"json",
success : function (data) {
var jsobj = JSON.parse(JSON.stringify(data));
console.log(jsobj);
//WHAT SHOULD I DO HERE ?
alert("reached");
},
error : function(e) {
alert("Failed to search....");
}
});
});
</script>
I'm getting the courselist from ajax call but I'm not able to display it on same page. Jquery.load(url) will also not work as jsp file is in WEB-INF. So we can't access it through url.
Div id="testingClass" is present in the same file.(courseSearchPage.jsp).I want to show this div when I click on search buttom.
I'm trying to best understand your problem, this code snippet works for me.
$("#searchButton").click(function(e) {
e.preventDefault();
var data = [];
$.ajax({
type: "GET",
contentType: "application/json",
url: "http://httpbin.org/get?test=chakram",
data: $("#courseSearchForm").serialize(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#testingClass').show(); //ADD THIS LINE HERE
},
error: function(e) {
alert("Failed to search....");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="searchButton">click me</button>
<div id="testingClass" style="display:none;">
<h3>your div has now been shown!</h3>
</div>

Sending data using ajax to the controller in rails

I am new to JS and rails so recently facing lots of difficulties about using ajax in rails environment. I will very appreciate if you contribute to developing my project. What I am trying to do is that Once a user selects data from the modal, I want to send the selected data to an action in the controller so that I can handle the data. I am not really sure where I can start with that. Please help guys :( Thanks a lot
view:
<form id= "selected_form" action="" method="">
<div id= "selected_form">
<p id="checkids"></p>
</div>
</form>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<div>
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Select Task</h4>
</div>
<div class="modal-body">
<fieldset>
<% #tasks.each do |task|%>
<div>
<label><input type="checkbox" value="<%=task.id%>" name="selected"><%=task.title%></label>
</div>
<% end %>
</fieldset>
</div>
<div class="modal-footer">
<button type="button" id="save" class="btn btn-default" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</div>
JS
<script>
$(function(){
$(document).ready(function(){
$("#save").click(function(){
var checkedItem = [];
$.each($("input[name='selected']:checked"), function(){
checkedItem.push($(this).val());
});
$('#values').html("selected values are: " + checkedItem.join(", "));
$.ajax({
type: "POST", // request method for your action like get,post,put,delete
url: "/users/<%= current_user.id %>/test", // route of your rails action
data: {checked_items: checkedItem.join(", ")}, // attach data here you will get this data in your controller action with params[:checked_items]
success: function(data, textStatus, jqXHR){}, // do whatever you want when it success
error: function(jqXHR, textStatus, errorThrown){}
})
});
});
});
</script>
Please check script below
<script>
$(function(){
$(document).ready(function(){
$("#save").click(function(){
var checkedItem = [];
$.each($("input[name='selected']:checked"), function(){
checkedItem.push($(this).val());
});
$('#values').html("selected values are: " + checkedItem.join(", "));
$.ajax({
type: "POST", // request method for your action like get,post,put,delete
url: "/things", // route of your rails action
data: {checked_items: checkedItem }, // attach data here you will get this data in your controller action with params[:checked_items]
success: function(data, textStatus, jqXHR){...}, // do whatever you want when it success
error: function(jqXHR, textStatus, errorThrown){...}
})
});
});
});
</script>
For simplicity you can inject rails path to that controller as dataset attribute.
for e.g
<form method="post" data-url="<%= tasks_path %>">
and in js part
$('#save').on('click', function (e) {
e.preventDefault();
$.ajax({
type: $(this).method || "GET",
url: this.dataset.url,
data: $(this).serialize(),
success: function (response) {
console.log(response)
},
error: function (error) {
console.log(error);
}
});
});

serialized form not sending ajax

I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!

Categories

Resources