How to pass JS variable to Modal route - javascript

im trying to update data from modal so that i want pass id to my form route how can i do here
$("body").on("click",".edit-item",function(){
var id = $(this).parent("td").data('id');
console.log(id);
var description = $(this).parent("td").prev("td").prev("td").text();
var log_time = $(this).parent("td").prev("td").text();
var url = '{{url('calls/'.$call->id.'/sub_calls/'.$subCall->id.'logs')}}}'
$("#edit-item").find("input[name='description']").val(description);
$("#edit-item").find("textarea[name='log_time']").val(log_time);
$("#edit-item").find("form").attr("action",url + '/' + id);
});
i want pass this var id to modal route here next to $subcall->id
{!! Form::model(['route' => ['calls.sub_calls.logs.update',$call->id,$subCall->id],'class'=>'form-horizontal','role'=>'form']) !!}
my route
Route::model('logs','App\Models\SubCalls\SubPortLog');
Route::resource('calls.sub_calls.logs','SubPortLogController');

You need to pass it in the routing file (it's wher you define routes) like this:
Route::post('calls/sub_calls/logs/{id}/update/{subId?}', ['uses' => 'SomeController#upddate']);
if you have derfined this route with Route::resource method then you should put my example from above just in front of this declaration like this:
Route::post('calls/sub_calls/logs/{id}/update/{subId?}', ['uses' => 'SomeController#upddate']);
Route::resource('calls/sub_calls/logs','SubPortLogController');
And then in your controller metyhod do it like this:
public function update($id, $subId = null)
UPDATE:
Try this:
Define form with a shortcode as a secound parameter i.e. :subId:
{!! Form::model(['route' => ['calls.sub_calls.logs.update',$call->id, ':subCallId'],'class'=>'form-horizontal','role'=>'form']) !!}
and then just replace it with the value that you want:
$("body").on("click",".edit-item",function() {
var id = $(this).parent("td").data('id'),
action = $('form').prop('action').replace();
$('form').prop('action', action);
(...)
}

Related

Laravel - JS : search function without reloading page, return html

on a small project using laravel and javascript, I would like to implement a search functionality
For this, I would like that once the search is submitted, the page content changes without reloading
So I have a first method in my controller, which renders the page view complete with my data
In the page template, I included a file of partials, containing only my foreach loop and the associated html
Here is the controller method
public function __invoke(MyService $myService)
{
return view('posts.index', [
'posts' => $myService->getAll(),
]);
}
and my partials present in posts.index
#foreach($posts as $post)
<div class="">
{{ $post->name }}
<p class="my-4">
{{ str($post->data)->limit(150) }}
</p>
</div>
#endforeach
So, in my posts.index, I add this JS
var search = document.getElementById("search");
var by = document.getElementById("by");
var form = document.getElementById("form");
form.addEventListener("submit", function(evt) {
evt.preventDefault();
fetch('/search?search=' + search.value + '&by=' + by.value)
.then(response => response.json())
.then(data => {
var elem = document.querySelector('#result');
elem.innerHTML = JSON.stringify(data.html)
});
});
The #result element is where I'm including the partials
There is my search function
public function search(Request $request){
$by = $request->input('by');
switch ($by){
case 'name':
$service = new MyService();
$result = $service->getPostsForName($request->input('search');
$html = view('partials.list', ['posts' => compact('result')])->render();
return response()->json(compact('html'));
break;
}
}
The two methods of the controller return me an Array of Post (my model)
But when I run a search I always get the following error
attempt to read property "url" on array in file
I can't understand why, could you help me please ?

How do i pass data from blade to blade file

I try to pass two value from javascript to another blade file after click button to redirect to new window ...Here is my code
ReportCreate.blade.php js
$("#state").on("change", function() {
var id = $(this).val();
console.log(id)
var cuid = document.getElementById("cu").value;
console.log(cuid)
});
</script>
Click button to open new window which is carry two value from javascript
onclick="openNewWindow('{{ route('sla.slaCategoryTreeListScreen') }}')"
slaCategoryTreeListScreen.blade.php
<!DOCTYPE html>
<script>
// how do i retrieve two value from another blade file
</script>
</html>
First, You'll need to send those values when making the request. You can do this with query params passing a second argument on the route() helper:
onclick="openNewWindow('{{ route('sla.slaCategoryTreeListScreen', ['id' => 123, 'cuid' => 456]) }}')"
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Then, you get those values in your controller to finally return them to the second blade file:
# MyCoolController.php
public function toMySecondView(Request $request)
{
$id = $request->get('id');
$cuid = $request->get('cuid');
return view('my_cool_second_view', ['id' => $id, 'cuid' => $cuid]);
}
Just then you'll be able to use them in your second view:
# my_cool_second_view.blade.php
<span> ID: { $id } </span>
<span> CUID: { $cuid } </span>

How do I populate a list field in a model from javascript?

I have a Kendo.MVC project. The view has a model with a field of type List<>. I want to populate the List from a Javascript function. I've tried several ways, but can't get it working. Can someone explain what I'm doing wrong?
So here is my model:
public class Dashboard
{
public List<Note> ListNotes { get; set; }
}
I use the ListNotes on the view like this:
foreach (Note note in Model.ListNotes)
{
#Html.Raw(note.NoteText)
}
This works if I populate Model.ListNotes in the controller when the view starts...
public ActionResult DashBoard(string xsr, string vst)
{
var notes = rep.GetNotesByCompanyID(user.ResID, 7, 7);
List<Koorsen.Models.Note> listNotes = new List<Koorsen.Models.Note>();
Dashboard employee = new Dashboard
{
ResID = intUser,
Type = intType,
FirstName = user.FirstName,
LastName = user.LastName,
ListNotes = listNotes
};
return View(employee);
}
... but I need to populate ListNotes in a Javascript after a user action.
Here is my javascript to make an ajax call to populate ListNotes:
function getReminders(e)
{
var userID = '#ViewBag.CurrUser';
$.ajax({
url: "/api/WoApi/GetReminders/" + userID,
dataType: "json",
type: "GET",
success: function (notes)
{
// Need to assign notes to Model.ListNotes here
}
});
}
Here's the method it calls with the ajax call. I've confirmed ListNotes does have the values I want; it is not empty.
public List<Koorsen.Models.Note> GetReminders(int id)
{
var notes = rep.GetNotesByCompanyID(id, 7, 7);
List<Koorsen.Models.Note> listNotes = new List<Koorsen.Models.Note>();
foreach (Koorsen.OpenAccess.Note note in notes)
{
Koorsen.Models.Note newNote = new Koorsen.Models.Note()
{
NoteID = note.NoteID,
CompanyID = note.CompanyID,
LocationID = note.LocationID,
NoteText = note.NoteText,
NoteType = note.NoteType,
InternalNote = note.InternalNote,
NoteDate = note.NoteDate,
Active = note.Active,
AddBy = note.AddBy,
AddDate = note.AddDate,
ModBy = note.ModBy,
ModDate = note.ModDate
};
listNotes.Add(newNote);
}
return listNotes;
}
If ListNotes was a string, I would have added a hidden field and populated it in Javascript. But that didn't work for ListNotes. I didn't get an error, but the text on the screen didn't change.
#Html.HiddenFor(x => x.ListNotes)
...
...
$("#ListNotes").val(notes);
I also tried
#Model.ListNotes = notes; // This threw an unterminated template literal error
document.getElementById('ListNotes').value = notes;
I've even tried refreshing the page after assigning the value:
window.location.reload();
and refreshing the panel bar the code is in
var panelBar = $("#IntroPanelBar").data("kendoPanelBar");
panelBar.reload();
Can someone explain how to get this to work?
I don't know if this will cloud the issue, but the reason I need to populate the model in javascript with an ajax call is because Model.ListNotes is being used in a Kendo Panel Bar control and I don't want Model.ListNotes to have a value until the user expands the panel bar.
Here's the code for the panel bar:
#{
#(Html.Kendo().PanelBar().Name("IntroPanelBar")
.Items(items =>
{
items
.Add()
.Text("View Important Notes and Messages")
.Expanded(false)
.Content(
#<text>
#RenderReminders()
</text>
);
}
)
.Events(e => e
.Expand("getReminders")
)
)
}
Here's the helper than renders the contents:
#helper RenderReminders()
{
if (Model.ListNotes.Count <= 0)
{
#Html.Raw("No Current Messages");
}
else
{
foreach (Note note in Model.ListNotes)
{
#Html.Raw(note.NoteText)
<br />
}
}
}
The panel bar and the helpers work fine if I populate Model.ListNotes in the controller and pass Model to the view. I just can't get it to populate in the javascript after the user expands the panel bar.
Perhaps this will do it for you. I will provide a small working example I believe you can easily extend to meet your needs. I would recommend writing the html by hand instead of using the helper methods such as #html.raw since #html.raw is just a tool to generate html in the end anyways. You can write html manually accomplish what the helper methods do anyway and I think it will be easier for you in this situation. If you write the html correctly it should bind to the model correctly (which means it won't be empty on your post request model) So if you modify that html using javascript correctly, it will bind to your model correctly as well.
Take a look at some of these examples to get a better idea of what I am talking about:
http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
So to answer your question...
You could build a hidden container to hold your list values like this (make sure this container is inside the form):
<div id="ListValues" style="display:none">
</div>
Then put the results your ajax post into a javascript variable (not shown).
Then in javascript do something like this:
$('form').off('submit'); //i do this to prevent duplicate bindings depending on how this page may be rendered futuristically as a safety precaution.
$('form').on('submit', function (e) { //on submit, modify the form data to include the information you want inside of your ListNotes
var data = getAjaxResults(); //data represents your ajax results. You can acquire and format that how you'd like I will use the following as an example format for how you could save the results as JSON data: [{NoteID ="1",CompanyID ="2"}]
let listLength = data.length;
for (let i = 0; i < listLength; i++) {
$('#ListValues').append('<input type="text" name="ListNotes['+i+'].NoteID " value="' + data.NoteID +'" />')
$('#ListValues').append('<input type="text" name="ListNotes['+i+'].CompanyID " value="' + data.CompanyID +'" />')
//for your ajax results, do this for each field on the note object
}
})
That should do it! After you submit your form, it should automatically model bind to you ListNotes! You will be able to inpsect this in your debugger on your post controller action.

pass ViewBag to js function

I am having a dropdown list in which I call a js function, on change event.
In View:
#Html.DropDownList("RaceId", ViewData["Races"] as List<SelectListItem>, new { #onchange = "CallChangefunc(this.value)", #class="form-control" })
and my js:
<script>
function CallChangefunc(val)
{
//called in Index page when dropdown list changes
window.location.href = "/Index/" + val;
}
</script>
What I want is to add a new argument to my js function where I pass a ViewBag value, sth like:
#Html.DropDownList("RaceId", ViewData["Races"] as List<SelectListItem>, new { #onchange = "CallChangefunc(this.value,ViewBag.id)", #class="form-control" })
The above does not work and I am not sure which is the correct syntax, if any.
First, use unobtrusive javascript instead of onchange attribute. If you have your javascript inside your view, you can access ViewBag too, using '#ViewBag':
$('#RaceId').on('change', function()
{
var value = $(this).val();
var id = '#ViewBag.id'
}
);
Or if you're running your javascript on a different file, you can use a Hidden input and get this value in your script:
#Html.Hidden("Id", ViewBag.id)
and in you script:
$('#RaceId').on('change', function()
{
var value = $(this).val();
var id = $("Id").val();
}
);
Although Stephen's comment is 100% correct, i would just like to know if this solves your problem:
#{
var htmlAttr = new Dictionary<string, object>();
htmlAttr.Add("onchange", string.Format("{0}{1})", "CallChangefunc(this.value", #ViewBag.id));
htmlAttr.Add("class", "form-control");
}
#Html.DropDownList("RaceId", ViewData["Races"] as List<SelectListItem>, #htmlAttr)

http 404 error when trying to call web api controller action method from .js file

I am getting Http 404 error on button click when i inspect element in browser.
There is a wallpost.js file in Scripts folder containing logic for knockout, client side view model and data- binding etc.
In this file, reference to the WallPost Api controller is given like this---
var postApiUrl = '/api/WallPost/', commentApiUrl = '/api/Comment/';
and on my view page, there is a container for posting and commenting something like this--
<div class="publishContainer">
<textarea class="msgTextArea" id="txtMessage" data-bind="value: newMessage, jqAutoresize: {}" style="height:3em;" placeholder="what's on your mind?"></textarea>
<input type="button" data-url="/Wall/SavePost" value="Share" id="btnShare" data-bind="click: addPost"/>
now, references to script folder js files are given like this---
#section scripts{
<script src="~/Scripts/jquery.autosize.min.js"></script>
<script src="~/Scripts/knockout-3.3.0.js"></script>
<script src="~/Scripts/wallpost.js"></script>
}
First thing i want to clear that autosize.js is working fine on textarea so, i think path to wallpost.js file is correct as it is similar to autosize.js file.
Now, the problem is i am unable to post the message on button click. I have put the breakpoint at the controller's action method which should be hit on this button click, but thats not get hitted.
From what i am understanding, i think i am unable to use wallpost.js file in the Scripts folder or the route to call controller's action method is wrong So,there is a problem in reference i think.
The button click should hit the action method but it's not.
PLzz suggest me what should i try.I can provide more code if required.
I was following this article.http://techbrij.com/facebook-wall-posts-comments-knockout-aspnet-webapi
My web-api controller action method is like this----
namespace WebApp.Controllers
{
public class WallPostController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();
public HttpResponseMessage PostPost(Post post)
{
// post.PostedBy = WebSecurity.CurrentUserId;
post.PostedBy = User.Identity.GetUserId<int>();
post.PostedDate = DateTime.UtcNow;
// post.UserProfile.UserId = WebSecurity.CurrentUserId;
ModelState.Remove("post.PostedBy");
ModelState.Remove("post.PostedDate");
// ModelState.Remove("post.UserProfile.UserId");
if (ModelState.IsValid)
{
db.Posts.Add(post);
db.SaveChanges();
// var usr = db.UserProfile.FirstOrDefault(x => x.UserId == post.PostedBy);
var usr = db.Users.FirstOrDefault(x => x.Id == post.PostedBy);
var ret = new
{
Message = post.Message,
PostedBy = post.PostedBy,
PostedByName = usr.UserName,
//PostedByAvatar = imgFolder + (String.IsNullOrEmpty(usr.AvatarExt) ? defaultAvatar : post.PostedBy + "." + post.UserProfile.AvatarExt),
PostedByAvatar = db.Users.Include(s => s.Files).SingleOrDefault(s => s.Id == post.PostedBy),
PostedDate = post.PostedDate,
PostId = post.PostId
// UserId = usr.UserId
};
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, ret);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = post.PostId }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
I don't know why its not working. it was working fine when i was using simple membership.now, i want to use it with aspnet identity.

Categories