Laravel : Ajax delete with bootstrap modal dialog - laravel

I have a bootstrap modal dialog (see image below)
The red danger button (marked by xx) is where the action is happening. When that button is clicked - the uploaded file ( in this case - 2013-09-18_16h40_47.png) should be deleted while the modal dialog box is still open which is not what is happening right now. The download id is not getting passed to the controller method and the modal dialog is closed when the red button is clicked.
UI code :
{{ Form::open( array('route' => 'download.deletedownload','method' => 'post','id' => 'form-add-setting') ) }}
{{Form::hidden('downloadId',$download->id)}}
<button id="downloadDelete" type="submit" class="btn btn-xs btn-danger">xx</button>
{{Form::close()}}
The route looks like this
Route::post('deletedownload', array('uses' => 'DownloadsController#deletedownload', 'as'=>'download.deletedownload'));
and the controller method look like this
public function deletedownload()
{
if(Request::ajax()) {
dd("this is an ajax request");
};
var_dump('i am in the deletedownload method of the DownloadsController class');
$id = Input::get('id');
dd($id);
return Redirect::back();
}
Javascript :
$('#downloadDelete').click(function (e)
{
$.ajax({
type: 'POST',
url: '<?=URL::to('/')?>/deletedownload',
data: 'dataString',
dataType:'json',
success: function(result)
{
console.log(result);
}
})
});
and this is the output
string(66) "i am in the deletedownload method of the DownloadsController class" NULL
Notice that "this is an ajax request" is not getting echoed. Hence i have reasons to believe that is not an ajax request.
Any help would be well appreciated.
thanks

Where is your Javascript ? Ajax request should be sent explicitly with Javascript or jQuery from the client side. I don't know if Ajax is already attached on that modal button ?
UPDATE:
As I can see you are using named route on a server side, but in Ajax request you are pointing to URL ?

Related

Spring controller does not load view

I calling a controller via button click using ajax. I want it to load hello.html page but I want spring to do it not ajax.
What happens after I click the button is nothing but I'm sure the controller is being hit.
Here is the controller I'm calling via button click using ajax.
#RequestMapping(value="/submitName", method=RequestMethod.GET)
public String submitName(#RequestParam String name, Model model) {
System.out.println(name);
model.addAttribute("name", name);
return "hello";
}
Here is the ajax call.
$('#submit-button').on('click', function() {
$.ajax({
type: 'GET',
url: '/submitName',
data: {name: $('#name').val()}
});
});
Funny thing is in the chrome network tab it shows the page that I'm expecting. Here is a snippet.
I think everything is ok here, except you didn't mention how you want to show your page or where. You have to declare a container where your html returned from controller would appear, like under a div id or something like that.
So, just in your current html page, declare a new tag, may be <div id="current-page-id"></div>
Now, append the hello.html page to your current page using jquery:
$("#current-page-id").html(responseData);
So, basically, do this:
$.ajax({
type: 'GET',
url: '/submitName',
data: {name: $('#name').val()},
dataType: 'html',
success: function (responseData) {
$('#current-page-id').html(responseData);
},
});
Or, simply, load the page as separate html page, not via ajax.
Update:
instead of using ajax-as you asked for in comment section, do this as follows:
function getHtmlPage(String name)
{
location.href = 'submitName/' + name;
}
Now call your method on button click:
$('#submit-button').on('click', function() {
var name=$('#name').val();
getHtmlPage(name);
});
AJAX Calling just send the request to the server (controller) and received a response,
By default, It's dos not responsibility for reloading the page.
In this why when you click the button it hit the server-side but stay on the same page.
Simple there is two way you can load your new page ( hello.html )
1| With AJAX calling:
On the button click method, you have to explicitly load the page (Best practice in Ajax Success block)
adding this window load metbod:
window.location.href = "http://localhost:8080/hello.html";
Like:
$('#submit-button').on('click', function() {
$.ajax({
type: 'GET',
url: '/submitName',
data: {name: $('#name').val()}
window.location.href = "http://localhost:8080/hello.html";
});
});
2| Direct Http Call on the Button
HTML
<a class="btn btn-primary btn-lg pull-right" href="http://localhost:8080/hello" role="button">Hello Page</a>
JSP:
<a class="btn btn-primary btn-lg pull-right" href="${pageContext.request.contextPath}/hello" role="button">Hello page</a>
Thymeleaf
<a class="btn btn-xs" th:href="#{/hello})}">Hello Page </a>

Django: populate modal with a form through Ajax

I´m trying to show a prepopulated form in a modal so users can click on an item, the modal opens showing a form with that item´s data that users can edit and save.
I can send data from a view to a modal with json serializer but I can´t find how to send a form.
When I test this, I get an error declaring that "Object of type FormularioTareas is not JSON serializable"
The problem seems to be clear, I can´t send the form through a json response. How can I handle this?
Thanks in advance!
The modal call in the template
<form name="form" action="#" id="form_tarea_{{tarea.id}}" method="POST">
{% csrf_token %}
<input name="id" id="tarea_id_submit" type="text" value="{{tarea.id}}" hidden="true"/>
<a href="" id="{{tarea.id}}" class="show_tarea" data-toggle="modal" >Este link</a>
</form>
The Ajax script
Here I´m using now $('#caca').text(tarea_data.caca); only to test I can send some info to the modal correctly. It works.
I guess I should update that "text" type to another one in order to work.
<script>
$(function(){
$('.show_tarea').on('click', function (e) {
e.preventDefault();
let tarea_id = $(this).attr('id');
$.ajax({
url:'/catalog/tareas-detail/',
type:'POST',
data: $('#form_tarea_'+tarea_id).serialize(),
success:function(response){
console.log(response);
$('.show_tarea').trigger("reset");
openModal(response);
},
error:function(){
console.log('something went wrong here');
},
});
});
});
function openModal(tarea_data){
$('#caca').text(tarea_data.caca);
$('#modal_tareas').modal('show');
};
</script>
The view
def TareaDetailView(request):
context = {}
tareas = Tareas.objects.values()
context[tareas] = Tareas.objects.all()
if request.method == 'POST' and request.is_ajax():
ID = request.POST.get('id')
tarea = tareas.get(pk=ID) # So we send the company instance
tareas_form = FormularioTareas(tarea)
caca = ID
return JsonResponse(tareas_form, safe=False)
else:
return render(request, 'catalog/artista.html', context)
Django forms are not json serializable. Either pass your model to json response or return your form as text/json.
return JsonResponse(serializers.serialize('json', tarea), safe=False)
I never use django or phyton before but I will try to help you:
First your ajax, try to use a done insteand of success, in this example you are getting info from some select to fill a form inside a modal with specific
function getData(clientId){
return $.ajax({
method: "POST",
url: "YourUrl",
data: { action: "SLC", clientId: clientId}
})
}
then you get your stuff:
getData(clientId).done(function(response){
//manage your response here and validate it
// then display modal, note: you must have some conditions to get the array
//and fill each input use JSON.parse to get the json array elements
openModal(response);
})
hope it helps

Yii2: 'Save Draft' button

I'd like to have a form with the three buttons:
OK button: It runs validation and post data on success.
Cancel button: Skip validation and posting and redirect to the other view.
Save Draft button: Post data without validation.
I know how to implement OK and Cancel buttons, but how to prevent the validation on 'Save Draft' button click?
To bypass the client-end validation just for the draft button, what i would suggest is not to use the submit button for the Draft , use normal button and save the draft using ajax call , this would trigger the validation if you are typing into the field or blur out but not if you hit the draft button. use $.serialize() to get the form inputs and send call to save as draft.
Hope it will help for someone.
Here is the solution:
Add 'Draft Button' as a normal button in your view:
<?= Html::button('Save Draft', ['class' => 'btn btn-default btn-block', 'id' => 'save-draft-btn']) ?>
Add JS file to your view and specify onClick event for the button:
$('#save-draft-btn').on('click', function (e) {
$.ajax({
type: 'POST',
url: draftUrl,
data: $('#report-index').serialize()
});
});
Add the action to your controller:
public function actionSaveDraft($idSupply)
{
//load models like this
$report = \app\models\Reports::findOne($idSupply);
//fill with the POST data
$report->load(Yii::$app->request->post());
//save without validation
$report->save(false);
//inform the user on success saving
Yii::$app->session->setFlash('success', 'Draft Saved');
//redirect to the editing page
return $this->redirect(['index', 'idSupply' => $report->id_supply]);
}

Laravel 5.2 & AJAX - Display success message after redirect

I'm creating a CRUD system in L5.2 and am using Bootstrap Modal to display forms. I've used BootForms and Laravel Bootstrap Modal Form to validate forms and display error messages inside Modal without closing it.
Basically I'm opening Add / Edit forms inside a modal on same page, the form validation is done inside Modal and once everything is okay the data is being inserted in database and the modal closes. After that the page refreshes and shows updated data.
Everything is working fine, except in case of success I am not able to display a success message on my page.
Following is my code:
AJAX
$.ajax({
type: "POST",
url: url,
data: data,
dataType: 'json',
cache: false,
contentType: contentType,
processData: false
// Response.
}).always(function(response, status) {
// Reset errors.
resetModalFormErrors();
// Check for errors.
if (response.status == 422) {
var errors = $.parseJSON(response.responseText);
// Iterate through errors object.
$.each(errors, function(field, message) {
console.error(field+': '+message);
var formGroup = $('[name='+field+']', form).closest('.form-group');
formGroup.addClass('has-error').append('<p class="help-block">'+message+'</p>');
});
// Reset submit.
if (submit.is('button')) {
submit.html(submitOriginal);
} else if (submit.is('input')) {
submit.val(submitOriginal);
}
// If successful, reload.
} else {
location.reload();
}
});
Controller:
public function store(CustomerRequest $request)
{
Customer::create($request->all());
return redirect('customers')
->with('message', 'New customer added successfully.')
->with('message-type', 'success');
}
View: (to display success message)
#if(Session::has('message'))
<div class="alert alert-{{ Session::get('message-type') }} alert-dismissable">
<button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
<i class="glyphicon glyphicon-{{ Session::get('message-type') == 'success' ? 'ok' : 'remove'}}"></i> {{ Session::get('message') }}
</div>
#endif
You can see in case of success AJAX just reloading the page, I want it to redirect to the page specified in Controller function and display that success message.
You are returning a HTTP redirect from the response, which doesn't work with AJAX requests. A client such as a browser would be able to intercept and consume the header information which would then reload the page.
Instead, for your particular problem, consider:
https://laravel.com/docs/5.2/session#flash-data
public function store(CustomerRequest $request)
{
Customer::create($request->all());
$request->session()->flash('message', 'New customer added successfully.');
$request->session()->flash('message-type', 'success');
return response()->json(['status'=>'Hooray']);
}
Now, the HTTP/200 OK response received by your AJAX will execute location.reload and the flashed session data will be available to the view.

Render different Zend forms based on Ajax post request

I am trying to display different forms based on user type using Ajax post request. The request response works fine but I don't know how to display the form. For example, if the user selects parent then I want the parent form to be displayed and so on. I'm using ZF 1.12.
public function init() {
$contextSwitch = $this->_helper->getHelper('AjaxContext');
$contextSwitch =$this->_helper->contextSwitch();
$contextSwitch->addActionContext('index', 'json')
->setAutoJsonSerialization(false)
->initContext();
}
public function indexAction() {
$this->view->user = $this->_userModel->loadUser($userId);
//if($this->_request->isXmlHttpRequest()) {
//$this->_helper->layout->disableLayout();
//$this->_helper->viewRenderer->setNoRender(true);
if ($this->getRequest()->isPost()){
$type = $_POST['type'];
$this->view->userForm = $this->getUserForm($type)->populate(
$this->view->user
);
}
}
And here's what I have on the client side. What do I need to write in the success section?
<script type="text/javascript">
$(document).ready(function(){
$('#userType').on('change', function(){
var type = $(this).val();
select(type);
});
});
function select(type) {
$.ajax({
type: "POST",
url: "admin/index/",
//Context: document.body,
data: {'type':type},
data: 'format=json',
//dataType: "html",
success: function(data){
// what to do here?
},
error: function(XMLHttpRequest, textStatus, errorThrown) {}
});
}
</script>
<form id="type" name="type" method="post" action="admin/index">
<select name='userType' id='userType' size='30'>
<option>admin</option>
<option>parent</option>
<option>teacher</option>
</select>
</form>
<div id="show">
<?php //echo $this->userForm;?>
</div>
If your ajax request form returns you the HTML from the Zend_Form, you could simply write the HTML in the #show div.
In you view you will need to do this :
echo $this->userForm;
This way, all the required HTML will be written on the server side, before sending the response to the HTML page. In the HTML page you then just have to write the response in the right location with the method $('#show').html(data). You also have to make sure that each of your forms has the right action when you render them.
The other option would be to have all three forms hidden in your page (through Javascript) upon loading and based on the select (Generated with JS), display the right form. This way you don't have to load data from an external source and if someone have JS disabled, he still can use the application. On the other hand, this method will have each page load about 1/2 a KB more of data.

Resources