How to create dynamically tooltip using AJAX in Laravel?
I've got table, each element of table has it own ID, stored in <div id="[numbers]" hover="tooltip(this.id);"></div>
For each element I want to "create" or display tooltip(for displaying data like name, date, etc.).
Is it possible? This is what I've got at the moment:
// blade.view
function test(id)
{
$.ajax({{
type: "GET",
data:
{
id:id,
},
url: "{{ route('box.getData') }}",
success: function(data){
alert("data");
}
}});
}
Route:
Route::get('/box', 'App\Http\Controllers\BoxController#getData')->name('box.getData');
How to proceed with that in Controller?
Added controller:
public function getData(Request $request)
{
$absence = Absence::findOrFail($request->id);
return response()->json($absence, 200);
}
Related
I'm trying to dynamically change <input type="number" name="SLACost" readonly> based on <select name="SLATerm"> option
A table (in DB) that contains:
SLATerms.
SLACost.
SLADeduction
that should be fetched in the "Add new KPI Invoice" form.
I created a function in the controller to fetch the data as json:
/**
** KPI API
**/
public function fetchSLA()
{
$kpiTerms = KPITerms::all();
return response()->json([
'SLATermData' => $kpiTerms, // SLATermData is the name that will be used in Ajax.
]);
}
created a url for ajax to fetch in the web.php as Route::get('kpi/fetch/sla', 'fetchSLA')->name('kpi.fetchSLA'); // The API for fetching SLA as json
Then went ahead and created the ajax request GET
function fetchSLA() {
$.ajax({
type: 'GET',
url: "/management/kpi/fetch/sla",
dataType: 'json',
success: function (response) {
// console.log(response.SLATermData);
$("select[name='SLATerm']").change(function() {
$("input[name='SLACost']").val(response.SLATermData);
});
}
});
}
Obviously, SLATermData will fetch the entire data as json and print it in the SLACost input, it shows as [onject object object]
I tried to do this:
$("select[name='SLATerm']").change(function() {
$("input[name='SLACost']").val(response.SLATermData.SLACost);
});
I thought that adding SLACost after response.SLATermData will do the trick.
What's missing here?
So I made an ajax request to both SLATerm and SLACost and looped through the requested data. Then I made an if statement within the loop to change the SLACost based on the SLATerm selected.
function fetchSLA() {
$.ajax({
type: 'GET',
url: "/management/kpi/fetch/sla",
dataType: 'json',
success: function (response) {
$.each(response.SLATermData, function (key, value) {
$("select[name='SLATerm']").change(function() {
if ( $("select[name='SLATerm']").val() == value.SLATerm ) {
$("input[name='SLACost']").val(value.SLACost);
}
});
});
}
});
}
And here is the Laravel controller for the API:
/**
** KPI API
**/
public function fetchSLA()
{
$kpiTerms = KPITerms::get(['SLATerm' => 'SLATerm', 'SLACost' => 'SLACost']);
return response()->json([
'SLATermData' => $kpiTerms, // SLATermData is the name that will be used in Ajax.
]);
}
Now That I got it working, I'm trying to figure out how to clean the code.
As CBroe mentioned in the comments:
you should rather change your API - requesting all the data over and
over again
Which I am trying to do.
I need a way to generate a new unique id for a user when a person focuses out of a textbox. I am using MVC 5 for this application. Here is my controller, everything in the controller has been unit tested and it does return the string value that I need.
Controller. I was able to visit that URL, and I did download a JSON file with the correct data.
public ActionResult GetNewId()
{
string newId = utils.newEmployeeId();
return Json(new {eId = newId}, JsonRequestBehavior.AllowGet);
}
Javascript, JQuery call to that controller. I do not know how to properly reference the ActionResult. I keep getting undefined errors on eId.
$(function () {
$('#employeeId').focusout(function () {
if($("#employeeId").val() === "NP")
$.ajax({
type: 'GET',
url: '#Html.ActionLink("GetNewId", "Employees")',
data: { 'eId': eId },
dataType: 'json',
success: function (response) {
$("#employeeId").val(eId);
},
error: function (response) {
alert(response);
}
});
});
});
The problem is with yout ajax request:
1.you need to change the url in the reuqest but it like this
{{yourcontroller}/GetNewId}
2.remove the "data: { 'eId': eId }" you dont need it, youre not posting anything to the server.
change your $("#employeeId").val(eId); to
$("#employeeId").val(response.eId);
this will 100% work
I have placed a bootstrap toggle switch in my application
Now i want is to send the On and Off values to my action method
Bellow is my razor syntax
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset style="height:60px">
<legend style="text-align:center; font-size:large; font-family:'Times New Roman'; background-color:#C8E6C9; color:red">Remote On/Off</legend>
<input id="test_id" name="cmdName" type="checkbox" checked data-toggle="toggle">
</fieldset>}
For passing data to controller from JS i have searched many articles and found that ajax is the way to do it
Bellow is my script for ajax inside JS
<script>
var cmdName = '#Session["cmdName"]';
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'On',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("MultiGraph")',
type: 'Post',
data: 'Off',
success: function () {
alert(data)
}
});
}
}); </script>
I have also used session variable but getting null value in it
Bellow is my controller code
public ActionResult MultiGraph(string search, string start_date, string End_date, string cmdName, int? page)
{
//search contain serial number(s)
//cmdName is for input checkbox
}
Bellow is the image for my switch button
When i switch it to Off then this Off string should be sent to my action method and vise versa
Updated Code
After reading comments i have done the following changes to my code
I have added a new action method of type Post
[HttpPost]
public ActionResult ToggleSwitch (string search, string cmdName)
{
List<SelectListItem> items = new List<SelectListItem>();
var dtt = db.ADS_Device_Data.Select(a => a.Device_Serial_Number).Distinct().ToList();
foreach (var item in dtt)
{
if (!string.IsNullOrEmpty(item))
{
items.Add(new SelectListItem { Text = item, Value = item });
}
}
ViewBag.search = items;
return View();
}
Bellow are changes in my razor
$("#test_id").on("change", function (event) {
if ($(this).is(":checked")) {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
});
} else {
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "Off"}',
success: function () {
alert(data)
}
});
}
});
But still i get no alert message, when i inspect element i found this error
I am stuck to this problem from almost 2 days
Any help would be appreciated
You need to use the $ character to invoque jQuery functions and pass your data from page to controller with the same name you defined in the action method using Json notation:
'{"cmdName": "On"}',
$.ajax({
url: '#Url.Action("ToggleSwitch")',
type: 'Post',
data: '{"cmdName": "On"}',
success: function () {
alert(data)
}
Furthermore, you might need to decorate your mvc action whith the [HttpPost] attribute.
I have a web page that uses JavaScript to update a local array of objects, I would like to navigate to another page, passing the array of objects, this gets converted to a List, which I have working fine using Ajax.Post, but, I just want the return view(model) to display the page as it would if using an #Html.ActionScript, or #Url.Action. but it returns to the calling function, with a built up page.
is there a way of calling the post function as a 'fire and forget' type call ?
or is there a way of calling #Html.ActionScript or #UrlAction, passing the complex array as the parameter ?
here is some of the code that i am using
JS
$.ajax({
url: "/Home/About",
type: "POST",
data: JSON.stringify({ 'clients': clients }),
dataType: "json",
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (data) {
alert(data);
},
error: function (data){
alert(data);
},
done: function (data) {
alert(data);
}
});
Controller
[HttpPost]
public ActionResult About(List<ClientDataModels> clients)
{
//Do something, all i need to do is pass the clients
//to the view, and then dynamically add items based
//on the content
return View(clients);
}
About.cshtml
#using SST.Monitoring.Models
#model IEnumerable<ClientDataModels>
#{
//Layout = null;
ViewBag.Title = "About";
}
<h2>#ViewBag.Title.</h2>
<h3>#ViewBag.Message</h3>
<div class="container" style="width:900px">
#if(#Model != null)
{
foreach ( var client in #Model )
{
<div style="width:150px; float:left;">
<div class="tile-container">
<div class="tile bg-cyan fg-white" data-role="tile">
<div class="tile-content iconic">
<span class="icon mif-display mif-2x"></span>
<span id="ClientCount" class="tile-badge bg-darkBlue">0</span>
<span class="tile-label">client.ClientGroup</span>
</div>
</div>
</div>
</div>
}
}
</div>
the page that is returned to the ajax call has the 3 items( tiles ) which i expect, but i would like it to just fire and forget, and let the view just be displayed as it would be with #html.actionscript or event just a href link ?
As i understand you want to achieve something like this.
You could have a method for rendering a view inside your controller.
public static string RenderPartialView(this Controller controller,
string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = controller.ControllerContext.RouteData
.GetRequiredString("action");
controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines
.FindPartialView(controller.ControllerContext, viewName);
var viewContext = new ViewContext(controller.ControllerContext,
viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
This method will create the html you need like if you're returning a view.
You must add this html to your response (json response).
return Json(new
{
HtmlFromRenderPartialView = this.RenderPartialView("_SomeView", yourModel),
Message = message
}, JsonRequestBehavior.AllowGet);
And when you receive your ajax response, you will have the html and just empty() your container and append(response.HtmlFromRenderPartialView) to your container.
UPDATE:
[HttpPost]
public About(List<ClientDataModels> clients)
{
//Do something, all i need to do is pass the clients
//to the view, and then dynamically add items based
//on the content
return Json(new
{
HtmlFromRenderPartialView = this.RenderPartialView("_About", clients),
}, JsonRequestBehavior.AllowGet);
}
$.ajax({
url: "/Home/About",
type: "POST",
data: JSON.stringify({ 'clients': clients }),
dataType: "json",
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
$('#container').html(response.HtmlFromRenderPartialView );
},
ok, so based on the fact that I get the rendered page back as a result, I have just loaded it into the current window..
var w = window.open("","_self");
$(w.document.body).html(data.responseText);
This seems to have done the trick... thanks for your help !!
I'm using MVC 4 and I am trying to send a post request and I am getting a successful return from my controller with the resulting view in HTML form, but I'm not sure what to do with it at that point.
JS
$("form").submit(function (e) {
e.preventDefault();
if ($(this).valid()) {
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
$("#content").html(data);
}
})
}
});
my controller
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
return RedirectToAction("Index");
}
else
{
return View(model);
}
}
So you can see that my controller either returns a View or a RedirectToAction. In the success callback of my ajax call I am doing the following: $("#content").html(data);
But nothing seems to happen. Can someone help push me in the right direction of properly handling the return of the controller action.
Thank you so much!
If I understand correctly, you have a Create Event form on your page and you want to send an AJAX request to create a new event. Then you want to replace a section in your page #content with the results of the CreateEvent action.
It looks like your AJAX is set up correctly so that CreateEvent returns a successful response. I think you're now confused about the response. You have several options but let's choose two.
JSON response
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
var event = service.CreateEvent(model); // however you create an event
return Json(event);
}
else
{
// model is not valid so return to original form
return View("Index", model);
}
...
Now you need to generate html markup from the JSON and insert it into #content.
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
var obj = JSON.Parse(data);
var html; // build html with the obj containing server result
$("#content").html(html);
}
})
or HTML fragment
Instead of returning a full page with a Layout defined we'll return just a PartialView without Layout and all the head and script tags.
[HttpPost]
public ActionResult CreateEvent(EventModel model)
{
if(ModelState.IsValid)
{
var event = service.CreateEvent(model); // however you create an event
return PartialView("CreateEventResult", event);
}
else
{
// model is not valid so return to original form
return View("Index", model);
}
}
Now make a new partial view CreateEventResult.cshtml (Razor)
#model Namespace.EventModelResult
# {
Layout = null;
}
<div>
<!-- this stuff inserted into #content -->
#Model.Date
...
</div>
and the javascript is unchanged
$.ajax({
url: submitUrl, type: "POST", traditional: true,
data: { EventName: 'Name of event'},
success: function(data){
$("#content").html(data);
}
})
Edit:
If your Event creation fails for any reason after you have validated the input, you'll have to decide how you want to respond. One option is to add a response status to the object you return and just display that instead of the newly created Event.