I have an ajax form which when submitted shows error or success messages, ideally I'd like to scroll the browser to the top of the form so the user can see these messages,
$('.form-ajax').on('submit',function(e){
e.preventDefault();
var form = $(this);
var url = form.attr('action');
var method = form.attr('method');
var data = form.serialize();
var callback = form.attr('callback');
if(typeof callback !=='string'){
callback = function(response){
$("#error-box").html('<div class="alert alert-success alert-block">'+'<button type="button"
class="close" data-hide-closest=".alert" data-
dismiss="alert">×</button>'+'<strong>'+response.message+'</strong>'+'</div>');
}
}
Helper.ajax (url,method,data,callback)
});
blade :
#if(isset($sections))
<form action="/section/{{$sections->section_id}}" class="form-ajax" method="PUT">
<input type="hidden" value="put" name="_methods">
#csrf()
#else
<form class="form-ajax" action="/section" method="POST">
#csrf()
#endif
<div id="error-box">
</div>
<input type="text">
<button onclick="myFunction()" class="btn btn-dark scroll-top" style="float:right;">Save</button>
<form>
Related
I use AJAX to send data inside a bootstrap modal to a controller in ASP.NET MVC. After its operation is completed inside this controller, a success or failure response is sent back to bootstrap modal using following code:
Controller:
[HttpPost]
public JsonResult Action([Bind(Include = "Id,firstName,lastName")] InqueryViewModel model)
{
JsonResult json = new JsonResult();
if (ModelState.IsValid)
{
Inquery inquery = new Inquery();
inquery.firstName = model.firstName;
inquery.lastName = model.lastName;
var result = SaveInqueries(inquery);
json.Data = new { Success = true };
}
else
{
json.Data = new { Success = false, Message = "Unable to perform an action on sending" };
}
return json;
}
As you notice above, code is dividing the logic into 2 types of responses, i.e., success or failure. Following code inside bootstrap model is used to handle this response:
JavaScript
<script>
$("#actionButton").click(function () {
$.ajax({
url: '#Url.Action("Action","Home")',
type: "post",
data: $("#actionForm").serialize()
})
.done(function (response) {
if (response.Success) {
//data is saved.
$(".alert-success").show();
$("#actionForm").hide();
}
else {
$(".errorDiv").html(response.Message);
}
});
});
</script>
Above code is working as expected if response is a success, but its not showing .errorDiv on a failure response. Instead, bootstrap modal is being disappeared. Following is bootstrap modal code:
HTML:
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Get Your Survey</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="alert alert-success collapse">
<span>
Success
</span>
</div>
<form id="actionForm">
<div class="form-group">
#Html.TextBoxFor(m => m.firstName, new { placeholder = "First Name", #class = "form-control form-control-sm" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.lastName, new { placeholder = "Last Name", #class = "form-control form-control-sm" })
</div>
<button id="actionButton" class="data-btn btn btn-outline-success" type="submit">
<i class='fa fa-paper-plane'></i>
Send
</button>
</form>
<div class="errorDiv">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
Can anyone see why this program is behaving like this?
Thank you.
So I'm done with trying to upload image using modal and ajax, now I want to edit it. So my modal trigger is the uploaded picture itself. My problem is how do I get the data from the database and display it on my modal? Am also having this error:
Uncaught ReferenceError: data is not defined
MODAL TRIGGER: (user/gallery.blade.php)
#foreach($galleries as $art)
<div class="card" style="width: 20rem;">
<img class="card-img-top" src="/storage/upload/{{$art->upload}}" alt="Card image cap" id="editUpload" data_id="{{$art->id}}">
</div>
#endforeach
MODAL: (scripts/editUploadModal.blade.php)
<div class="modal .modal-lg bg-white" tabindex="-1" id="editUploadModal">
<div class="container">
<h3 class="text-center">EDIT UPLOAD</h3>
<form id="editForm" enctype='multipart/form-data'>
<div class="modal-body">
<input type="text" name="id" id="editId">
<input type="file" name="upload" id="editUpload"><br>
<img class="card-img-top" src="#" id="imageResult"><br>
<label>CAPTION</label>
<input type="textarea" class="form-control bg-white border-dark" name="description" id="description">
</div>
<button class="btn btn-danger">DELETE UPLOAD</button>
<button class="btn btn-success">SAVE</button>
</form>
</div>
</div>
SCRIPT: (scripts/editUpload_script.blade.php)
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('body').on('click','#editUpload', function(){
$('#editUploadModal').modal('show');
console.log($(this).attr('data_id')); //DISPLAYS ID
data_id = $(this).attr('data_id');
//THIS IS WERE AM STUCK FROM BECAUSE IT IS NOT DISPLAYING THE DATA IN CONSOLE
$.get("{{route('gallery.index')}}" + '/' + data_id + '/edit', function(Data){
console.log(data.upload + " " + data.description)
$('#editId').val(data.id);
$('#editUpload').val(data.upload);
$('#description').val(data.description);
//display image
reader.onload = function () {
$('#imageResult').attr("/storage/upload/" + data.upload);
});
});
});
</script>
CONTROLLER: (GalleryController.php) btw, I added use Response;
public function edit(Gallery $gallery)
{
return Response::json($gallery);
}
I am using ASP.NET Core.
in one of my page I have a div that different PartialView can be loaded into that
<html>
<body style="background:url('/images/bg.png')">
<div class="text-center">
<div class="container" style="overflow-x:auto; background-color:white">
<input type="button" class="btn btn-primary" value="Patients" onclick="LoadPartial('recipe')" />
<input type="button" class="btn btn-primary" value="Orders" onclick="LoadPartial('orders')" />
<input type="button" class="btn btn-primary" value="Delivered" onclick="LoadPartial('deliveries')" />
<div id="mypage">
<partial name="RecipeList.cshtml" />
</div>
</div>
</div>
<script>
function LoadPartial(type) {
var url = '#Url.Action("Recipes", "Glasses")';
if (type == 'recipe')
url = '#Url.Action("Recipes", "Glasses")';
if (type == 'orders')
url = '#Url.Action("Orders", "Glasses")';
if (type == 'deliveries')
url = '#Url.Action("Deliveries", "Glasses")';
$('#mypage').load(url);
}
</script>
</body>
when user open this page for first time ,it should load the partialview , like the first button get clicked.
when another partialview get loaded and I clicked refresh button on the browser, I want to refresh a partiaview that was loaded not the first one.
how can I do these?
You can store the url in localStorage when you click the button, and get the value from it in $(document).ready() function then load the partial view.
<body>
<div class="text-center">
<div class="container" style="overflow-x:auto; background-color:white">
<input type="button" class="btn btn-primary" value="Patients" onclick="LoadPartial('recipe')" />
<input type="button" class="btn btn-primary" value="Orders" onclick="LoadPartial('orders')" />
<input type="button" class="btn btn-primary" value="Delivered" onclick="LoadPartial('deliveries')" />
<div id="mypage">
</div>
</div>
</div>
</body>
#section scripts{
<script>
$(document).ready(function () {
var url = localStorage.getItem('url');
$('#mypage').load(url);
})
function LoadPartial(type) {
var url = '#Url.Action("Recipes", "Home")';
if (type == 'recipe')
url = '#Url.Action("Recipes", "Home")';
if (type == 'orders')
url = '#Url.Action("Orders", "Home")';
if (type == 'deliveries')
url = '#Url.Action("Deliveries", "Home")';
localStorage.setItem('url', url);
$('#mypage').load(url);
}
</script>
}
Result:
Update:
Use sessionStorage:
<body>
<div class="text-center">
<div class="container" style="overflow-x:auto; background-color:white">
<input type="button" class="btn btn-primary" value="Patients" onclick="LoadPartial('recipe')" />
<input type="button" class="btn btn-primary" value="Orders" onclick="LoadPartial('orders')" />
<input type="button" class="btn btn-primary" value="Delivered" onclick="LoadPartial('deliveries')" />
<div id="mypage">
</div>
</div>
</div>
</body>
#section scripts{
<script>
$(document).ready(function () {
var orignalurl = '#Url.Action("Recipes", "Home")';
var url = sessionStorage.getItem('url');
if(url != null)
$('#mypage').load(url);
else
$('#mypage').load(orignalurl);
})
function LoadPartial(type) {
var url = '#Url.Action("Recipes", "Home")';
if (type == 'recipe')
url = '#Url.Action("Recipes", "Home")';
if (type == 'orders')
url = '#Url.Action("Orders", "Home")';
if (type == 'deliveries')
url = '#Url.Action("Deliveries", "Home")';
sessionStorage.setItem('url', url);
$('#mypage').load(url);
}
</script>
}
I am using ajax but it behaves different. I just want code that I should
in Model , VIEW,Controller.
This while contain two operation insertion and fetching the data from that db.
![In image their is subject and textarea as input.When i click submit the input
dispaly in comment which is just above the Subject input]1
View
<form action="" method="POST">
<input type="hidden" name="myId" id="myId" value="" />
<div class="form-group px-4">
<label for="subject">Subject</label>
<input type="text" id="js_subject" name="js_subject">
</div>
<div class="form-group px-4">
<label for="exampleFormControlTextarea1">Example textarea</label>
<textarea class="form-control" name = "js_text" id="js_text" rows="3"></textarea>
</div>
<input type="submit" id="comment-info" value="submit" name="submit" class="btn btn-primary">
</form>
Use an jQuery Ajax request,and on somepage.php use if and else for insert and select and
echo some message for both and die();
$('form').on('submit', function(event){
event.preventDefault();
$.ajax({
type:'post',
url:'somepage.php',
data:$(this).serialize(),
success:function(data){
var tmp = data;
if(data = "message1"){
//do whatever
}else if(data = "message2"){
//do whatever
}
})
});
just trying to use ajax formRemote in a BS popover.
A simple form works, but the ajax implementation not:
1) gsp code
<div id="addfolder">
<a href="#" class="btn" id="nrfolder" rel="popover">
<i class="icon-folder-close icon-large"></i></a><%--<g:message code="folder" args="[entityName]" default="New Folder"/>--%></a>
</div>
<div id="newRootFolder" style="display:none;">
<form class="form-inline" style="width:280px;">
<g:formRemote name="createRootFolder" url="[controller:'folders',action:'create']" onLoading="showModalSpinnerNewFolder();" onComplete="hideModalSpinnerNewFolder();" onSuccess="doResponseNewFolder(data);" >
<g:textField name="folderName" class="input-small" type="text" placeholder="New folder"/>
<input type="submit" value="Create" class="btn btn-info" />
<a href="#" class="btn" onclick="$('#nrfolder').popover('hide')"/>Cancel</a>
</g:formRemote>
</g:formRemote>
</form>
</div>
2) Popover call with jquery
$('#nrfolder').popover({placement:'right',title:'New Root Folder',html:true,content: function() { return $('#newRootFolder').html();} });
3) jquery success event: doResponseNewFolder function
function doResponseNewFolder(data) {
alert('toto' + data.success);
if (data.success == 'true') {
var msg = data.msg;
// reload tree view
$('#tree').dynatree('getTree').reload();
} else {
var msg = $('<ul class="errors">');
for (var i = 0; i < data.errorList.length; i++) {
msg.append('<li>' + data.errorList[i] + "</li>");
}
}
$('#new_folder_msg').html(msg);
$('#new_folder_msg').show();
}
Any idea?
It seems you're messing up with forms, let me explain: Grails' g:formRemote is a helper for making ajax web forms, so if you look at the resulting HTML there will be a form generated at the call.
The fact is that you already opened a form, which isn't valid HTML syntax. That first form should not exist. You can give its attributes to your g:formRemote though and Grails will pass them to your generated form:
<g:formRemote class="form-inline" style="width:280px;" name="createRootFolder" url="[controller:'folders',action:'create']" onLoading="showModalSpinnerNewFolder();" onComplete="hideModalSpinnerNewFolder();" onSuccess="doResponseNewFolder(data);" >
<g:textField name="folderName" class="input-small" type="text" placeholder="New folder"/>
<input type="submit" value="Create" class="btn btn-info" />
<a href="#" class="btn" onclick="$('#nrfolder').popover('hide')"/>Cancel</a>
</g:formRemote>
This, with no other forms imbricated, will be enough.