Bootstrap modal email form - ajax

I've searched for an answer but could not find any. Maybe someone here can point me to the right direction.
I have a simple modal form (bootstrap). It's meant to work like this.
You enter the form and click Send. The form-info is sent to e-mailadress. When mail is sent new modal with confirmation is displayed.
I've tried to implement this solution: Bootstrap Modal ajaxified
So far i have this:
The modal:
<div class="hide fade modal" id="input-modal">
<form class="form-horizontal well" data-async data-target="#input-modal" action="/some-endpoint" method="POST">
<fieldset>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<label>Name</label>
<input id="name" type="text" placeholder="Type your name...">
</div>
<div class="modal-footer">
Cancel
<button type="submit" class="btn btn-primary" value="send"/>Send</button>
</div>
</fieldset>
</form>
The Javascript:
jQuery(function($) {
$('body').on('submit','form[data-async]', function(event) {
alert('submit Event');
var $form = $(this);
var $target = $($form.attr('data-target'));
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function(data, status) {
$target.html(data);
}
});
event.preventDefault();
});
});
But I need help with sending the input by mail and also sent info back to modal as a confirmation.
I've tried to solve this by myself for several days now, but now I've given up.

If you're using jQuery >= 1.5 look at the documentation here. This will provide you with a place to handle your new modal when the AJAX call returns. So your code would look something like this.
jQuery(function($) {
$('body').on('submit','form[data-async]', function(event) {
alert('submit Event');
var $form = $(this);
var $target = $($form.attr('data-target'));
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize()
}).done(function(data){
//pop your modal here
$('#your-new-modal').modal('show')
});
event.preventDefault();
});
This is assuming you plan to send the email server side as you can't send it from Javascript. In your example you would have changed the HTML content of the tag to the data returned from the AJAX call instead of opening a new modal. You can find documentation on opening the new modal via Javascript here.
Did not run this so there may be typos.

Related

Yii2 Pjax update div with flash message issue

i've a problem with Pjax and Yii2.
I have a view with a select input.
When i select an option i load a form via Ajax into a modal window.
If i submit the form i'll make a second Ajax call to a Controller function. In the controller i set a flash message and return an array.
In my jquery code if i use Pjax to reload the div where i see the flash message the entire page is reloaded.
I use timeout false but i think the problem is because i made two ajax call and so pjax reload the entire page. How i can prevent this ?
Pjax container
<!-- START PJAX -->
{Pjax id='refresh-flash' timeout=false}
{AlertBs4::widget(['options' => ['class' => 'show']])}
{/Pjax}
<!-- END PJAX -->
view
<div class="modal" id="modal-form" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document" style="max-width:900px;" >
<div class="modal-content" >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body" >
<!-- Here goes the form -->
<div class="modal-footer">
<button type="button" class="btn btn-default" id="apiCall" data-pjax="0">Ok</button><!-- this button makes the second ajax call -->
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS
$(document).ready(function(){
//Get Starter html
let html_start = $('.modal-body').html();
$('#eventi-event_trasp').on('change',function(){
let trasp = $(this).val();
$.ajax({
url: '$url',
type: 'get',
data: {
trasp_cod : trasp
},
success: function (data) {
if(data){
$('.modal-body').empty();
$('.modal-body').append(data);
$('#modal-form').modal('show');
}
},
error: function(data){
console.log(data);
}
});
});
//Click ok from form loaded via ajax
$('#apiCall').on('click',function(event){
$.ajax({
url: $('#form_corrieri').attr('action'),
type: 'post',
data: $('#form_corrieri').serialize(),
success: function (data) {
// THIS CAUSE RELOAD ENTIRE PAGE
//$.pjax.reload({container: '#refresh-flash', async: false, timeout: 0 ,push: false, replace: false});
$('#eventi-eventi_info').val(data);
$('#modal-form').modal('hide');
},
error: function(data){
console.log('error');
}
});
//$.pjax.click(event, {container: '#refresh-flash'})
});

every bootstrap modal repeat same id in laravel with ajax

i wrote some code to view my all showing events details using bootstrap modal popup when click read more button. but when i click read more button every response repeats same id.
this is my laravel code
#if(!empty($event))
#foreach($event as $value)
<!-- Single Blog Post -->
<div class="single-blog-post d-flex" id="event_tag">
<div class="post-thumbnail">
<img src="{{asset('images/'.$value->image)}}" alt="">
</div>
<div class="post-content">
<a class="post-title">
#if(strlen($value->title) <= 35)
{{$value->title}}
#else
{{substr($value->title, 0, 35) . '...'}}
#endif
</a>
<div class="post-meta d-flex justify-content-between">
<center><button id="event_button" class="post-cata cata-sm cata-success text_white" data-toggle="modal" data-target="#myModal">Read More</button></center>
</div>
</div>
<input type="hidden" name="event_id" id="event_id" value="{{$value->id}}"></div>
#endforeach
#endif
and this is javascript code to get id and show every id detail.
<script>
$(document).on("click", "#event_button", function() {
var id = $("event_id").val();
console.log(id);
$.ajax({
url: "/event/" + id + "/show",
dataType: "json",
success: function(html) {
$("#event_title").html(html.data.title);
}
});
})
</script>
every time repeats id no 2 when click each event read more button. how can i fix this?
Your code has some mistakes in html too. For example, has fixes ids in html.
'event_id'
'event_button'...
Try this...
<button id="event_button-{!! $value->id !!}" data-target="event_id-{!! $value->id !!}"
<input type="hidden" name="event_id" id="event_id-{!! $value->id !!}"
The code above will fixed the id issue.
Now let's to the JS code... Change the click event:
$(document).on("click", "button.post-cata", function() {
var id = $("#" . $(this).data("target").val();
...
Do you need to associate tags to work with the right value. Avoid to put fixes ids inside a php loop. The html id element must be unique in document.
So, has many ways to do this. In this case, the input hidden fild is not necessary. you can put the id in a attribute in the button tag too.
<button data-id="{!! $value->id !!}...
So in the jquery click event do:
var id = $(this).data('id');
It's more ease and clean.
give class name to button and add attribute to button
<button class="event_button post-cata cata-sm cata-success text_white" data-eventid="{{$value->id}}">Read More</button>
so no need to use hidden input id
now using jQuery :
$(document).on('click','.event_button',function(){
var event_id = $(this).attr("data-eventid");
$("#myModal").modal("show");
$.ajax({
url: "/event/" + event_id+ "/show",
dataType: "json",
success: function(html) {
$("#event_title").html(html.data.title);
}
});
});

Browser-independent way to save text in a TextAreaFor

Using ASP.NET MVC, I have a View that contains a TextAreaFor, where I want users to be able to type in some notes and save them on-the-fly, see notes that were saved there before (whether by them or some other user), as well as modify existing notes (like to add additional notes). Here's what I have....
The divs in the View:
<div class="form-group">
<label for="InternalNotes" class="control-label">Internal Notes</label>
#Html.TextAreaFor(w => w.InternalNotes, new { #class = "form-control" , #id="notes" }) #*this is editable*#
</div>
<div class="form-group">
<div class="col-xs-6">
<button type="button" id="savenotes" class="btn btn-default btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save Request Notes</button>
<div style="color:green; display:none" id="notessuccess">Notes successfully saved</div>
<div style="color:red; display:none" id="noteserror">Notes unable to be saved</div>
</div>
<div class="col-xs-6 text-right">
<button type="submit" id="deletereq" class="btn btn-default btn-primary" value="delete" name="submit"><span class="glyphicon glyphicon-remove"></span> Delete Request</button>
</div>
</div>
So the user could type something into the TextAreaFor, then hit the "savenotes" button, which should save them via Ajax. This is the jQuery for that:
$(document).ready(function () {
$("#savenotes").click(function () {
$("#notessuccess").hide();
$("#noteserror").hide();
var id = #Model.AccessRequestId;
var notes = document.getElementById("notes").textContent; //innerText;
$.ajax({
data: { 'id': id, 'notes': notes },
type: 'POST',
//contentType: "application/json; charset=utf-8",
url: '/Administration/SaveRequestNotes',
success: function (data) {
if (data.success == "ok") {
$("#notessuccess").fadeIn();
} else {
$("#noteserror").fadeIn();
}
},
fail: function (data) {
$("#noteserror").fadeIn();
}
});
});
});
The "innerText" is commented out because that's what I was originally using, but it was only working in Internet Explorer - another user is using Chrome, where he could see the other user's notes that were already there, but when he'd try to save notes in addition to theirs, it would blow it all out so the notes would be empty!
So I changed it to "textContent". That still works in Internet Explorer, but now in both Chrome and Firefox while it won't empty out existing notes, it still won't save new notes added. What is a browser-independent way I can make this work so everyone's notes will get properly saved whatever they are using?
Thank you!
You can use the jQuery val() method get the text user entered to the textarea
var notes = $("#notes").val();
alert(notes);
You might also consider using the Url.Action helper method to generate the correct relative path to your action method.
url: '#Url.Action("SaveRequestNotes","Administration")',

Play framework write Action with Ok(...) that doesn't load new page

Play framework 2.4.x. A button is pressed on my home page that executes some code via Ajax, and returns its results beneath the button without loading a new page. The results wait for a user to input some text in a field and press "submit". Those results Look like this:
<li class="item">
<div>
<h3>Email: </h3>
<a>#email.tail.init</a>
<h3>Name: </h3>
<a>#name</a>
</div>
<div>
<h3>Linkedin: </h3>
<form class="linkedinForm" action="#routes.Application.createLinkedin" method="POST">
<input type="number" class="id" name="id" value="#id" readonly>
<input type="text" class="email" name="email" value="#email" />
<input type="text" class="emailsecondary" name="emailsecondary" value="" />
<input type="text" class="name" name="email" value="#name" />
<input type="text" class="linkedin" name="linkedin" value="" />
<input type="submit" value="submit" class="hideme"/>
</form>
</div>
<div>
<form action="#routes.Application.delete(id)" method="POST">
<input type="submit" value="delete" />
</form>
</div>
</li>
Along with some jquery that slides up a li after submission:
$(document).ready(function(){
$(".hideme").click(function(){
$(this).closest('li.item').slideUp();
});
});
However, since a form POST goes inside an Action that must a return an Ok(...) or Redirect(...) I can't get the page to not reload or redirect. Right now my Action looks like this (which doesn't compile):
newLinkedinForm.bindFromRequest.fold(
errors => {
Ok("didnt work" +errors)
},
linkedin => {
addLinkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
if (checkURL(linkedin.url)) {
linkedinParse ! Linkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
Ok(views.html.index)
}else{
Ok(views.html.index)
}
}
)
Is it possible to return Ok(...) without redirecting or reloading? If not how would you do a form POST while staying on the same page?
EDIT: Here is my attempt at handling form submission with jquery so far:
$(document).ready(function(){
$(".linkedinForm").submit(function( event ) {
var formData = {
'id' : $('input[name=id]').val(),
'name' : $('input[name=name]').val(),
'email' : $('input[name=email']).val(),
'emailsecondary' : $('input[name=emailsecondary]').val(),
'url' : $('input[name=url]').val()
};
jsRoutes.controllers.Application.createLinkedin.ajax({
type :'POST',
data : formData
})
.done(function(data) {
console.log(data);
});
.fail(function(data) {
console.log(data);
});
event.preventDefault();
};
});
This is an issue with the browser's behavior on form submission, not any of Play's doing. You can get around it by changing the behavior of the form when the user clicks submit.
You will first want to attach a listener to the form's submission. You can use jQuery for this. Then, in that handler, post the data yourself and call .preventDefault() on the event. Since your javascript is now in charge of the POST, you can process the data yourself and update your page's HTML rather than reloading the page.
What you need is use ajax to submit a form, check this: Submitting HTML form using Jquery AJAX
In your case, you can get the form object via var form = $(this), and then start a ajax with data from the form by form.serialize()
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert('ok');
}
});
In order to accomplish this task, i had to use play's javascriptRouting
This question's answer helped a lot.
I'm not experienced with jquery so writing that correctly was difficult. For those that find this, here is my final jquery that worked:
$(document).ready(function(){
$("div#results").on("click", ".hideme", function(event) {
var $form = $(this).closest("form");
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
var email = $form.find("input[name='email']").val();
var emailsecondary = $form.find("input[name='emailsecondary']").val();
var url = $form.find("input[name='url']").val();
$.ajax(jsRoutes.controllers.Application.createLinkedin(id, name, email, emailsecondary, url))
.done(function(data) {
console.log(data);
$form.closest('li.item').slideUp()
})
.fail(function(data) {
console.log(data);
});
});
});
Note that my submit button was class="hideme", the div that gets filled with results from the DB was div#results and the forms were contained within li's that were class="item". So what this jquery is doing is attaching a listener to the static div that is always there:
<div id="results">
It waits for an element with class="hideme" to get clicked. When it gets clicked it grabs the data from the closest form element then sends that data to my controller via ajax. If the send is successful, it takes that form, looks for the closest li and does a .slideUp()
Hope this helps

Jquery Ajax call to servlet

I am trying to make an Ajax call using JQuery to a servlet that returns a JSON object.
In the JSP page I have a form, at first I didn't know how the get the data from the form,
then I found .serialize.
I have the following JavaScript:
$(document).ready(function() {
$("#submit").click(function blabla() {
var formData = $('form').serialize();
$.ajax({
type: "POST",
url: "/ArchiveSearch/Search",
dataType: "json",
data: formData,
});
});
});
The information comes from the following form:
<form method= post">
<div class="searchCiteria">
<div id="searchValueBlock1">
<div><span class="label">Case ID:</span><input type="text" name="messagecaseid" size="25"/></div>
<div><span class="label">Onderwerp:</span><input type="text" name="messagesubject" size="25" /></div>
<div><span class="label">Afzender:</span><input type="text" name="messagesender" size="25"/></div>
<div><span class="label">Ontvanger:</span><input type="text" name="messagereceiver" size="25"/></div>
</div>
<div id= "searchValueBlock2">
<div><span class="label">Datum:</span><input type="text" name="date1" size="25"/></div>
<div><span class="label"></span><input type="text" name="date2" size="25"/></div>
<div class="submit">
<input type="submit" value="Search">
</div>
</div>
</div>
</form>
When I use the action parameter in the form the servlet repondes like it should.
But I can't seem to get the Ajax call to work.
What am I doing wrong?
you must add the success param to ajax function
$.ajax({
type: "POST",
url: "/ArchiveSearch/Search",
dataType: "json",
data: formData,
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
The default behavior of the submit button is to POST the form, which will redirect the user to a URL of the action attribute ond the form. When you don't(which you should...) have an action attribute it will reload the page. To prevent the page from reloading you need to prevent the default behavior by returning false at the end of your $("#submit").click function.

Resources