search function in laravel wont work - javascript

I have this search bar inside navigation file and it's an enter submit input tag.
I include this file in many pages. but when I enter(submit) it doesn't go to searchResults.blade.php
MY HTML
<input class="searchkey" id="searchkey" type="search" required onkeydown="search(this)">
My JS
$('.searchkey').keydown(function(event) {
var getKeyword = document.getElementById("searchkey").value;
if (event.keyCode == 13) {
$.ajax({
url: "search",
type: "POST",
data:{
getKeyword : getKeyword
},
success: function() {}
});
}
});
MY CONTROLLER
public function multiSearch()
{
$searchKey = Input::get('getKeyword');
$getResults = array();
$getResults = DB::select("SELECT title FROM books WHERE title LIKE '%$searchKey%'");
return View::make('content.searchResults',array('getResults'=>$getResults));
}
MY ROUTES
Route::post('search', 'UserController#multiSearch');

First of all in your ajax callback you should put the view results in some container on the page, i.e.: <div id="search-result"></div> by adding this callback function:
success: function(data) {
$('#search-reasult').html(data);
}
You also have to render the view in your controller like this:
return View::make('content.searchResults',array('getResults'=>$getResults))
->render();

Related

How to dynamically load views and toggle between them without losing url and url history in asp.net mvc?

I have a nav bar with two buttons. Each button renders a view. I am using Jquery to dynamically load those views in one View which then gets rendered on the layout page. That means I am rendering all my views dynamically in one index page.
However, I end up losing the url history and it's not possible to link to those pages because they all get rendered using the one index action and controller that they're being rendered on.
I have tried setting the url from jquery using history.replacestate which works fine, however one issue remains: I do not know how to use the url:s to render a specific view on refresh or when linking to a specific view using the urls I created in replacestate. Is my approcach to dynamic loading wrong or is there a solution that can work with this current implementation?
[HttpGet]
[Route("/{controller}")]
public ActionResult Index()
{
return this.View();
}
The page argument passes in a URL that I create. Each view needs it's own URL.
function urlHistory(page) {
history.replaceState(currentState, '', page);
document.title = `${page}`;
}
I append each page to the main view and on clicking the nav bar the user can toogle between views.
function appendPage(href, page) {
$.get(href, {page: page}, function (data) {
$("#render-tables").html(data);
}).fail(function () {
$("#render-tables").empty();
});
urlHistory(page);
}
Rendering both views on the first index action(index.cshtml) that get's hit when logging in i.e the home page razor view.
<div id="render-tables"></div>
Which then in turn gets rendered using RenderBody on the Layout view.
For your requirement,I think you could store your current page in cookie or session,
I tried with partial view as below :
public IActionResult Partial(string page)
{
var formerpage=HttpContext.Session.GetString("PartialPage");
string pagename;
if (page == null&& formerpage==null)
{
pagename = "Partial1";
}
else
{
pagename = page== null ?formerpage : page;
}
HttpContext.Session.SetString("PartialPage", pagename);
return PartialView(pagename);
}
public IActionResult AnotherPartial(string anotherpage)
{
var formerpage = HttpContext.Session.GetString("AnotherPartialPage");
string pagename;
if (anotherpage == null && formerpage == null)
{
pagename = "AnotherPartial1";
}
else
{
pagename = anotherpage == null ? formerpage : anotherpage;
}
HttpContext.Session.SetString("AnotherPartialPage", pagename);
return PartialView(pagename);
}
Index page:
<button id="subBtn1" type="submit">NavBarPartial</button>
<button id="subBtn2" type="submit">Partial</button>
<br />
<button id="subBtn3" type="submit">NavBarAnotherPartial</button>
<button id="subBtn4" type="submit">AnotherPartial</button>
<div id="CrTab">
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$("#subBtn1").click(function () {
$.ajax({
url: "/Home/Partial",
type: "get",
success: function (datas) {
console.log(datas);
$("#CrTab").html(datas);
}
})
});
$("#subBtn2").click(function () {
$.ajax({
url: "/Home/Partial?page=Partial2",
type: "get",
success: function (datas) {
console.log(datas);
$("#CrTab").html(datas);
}
})
});
$("#subBtn3").click(function () {
$.ajax({
url: "/Home/AnotherPartial",
type: "get",
success: function (datas) {
console.log(datas);
$("#CrTab").html(datas);
}
})
});
$("#subBtn4").click(function () {
$.ajax({
url: "/Home/AnotherPartial?anotherpage=AnotherPartial2",
type: "get",
success: function (datas) {
console.log(datas);
$("#CrTab").html(datas);
}
})
});
</script>
in View Partial1:
<a>Partial1</a>
....
The result:

Including javascript file along with ajax response

I've got a dropdown that runs AJAX each time an option is selected. The ajax call returns HTML markup (buttons and text boxes) and a script tag, which the HTML(buttons) uses to submit to a database via ajax.
<html>
<head>........</head>
<body>........</body>
<select class="chooseOption">
...
...
</select>
<div class="ajaxResult">
<!-- after successful ajax -->
<!-- HTML Markup here -->
<!-- I'm having to include main.js here again so that HTML matkup can use AJAX -->
</div>
....
....
....
<footer> //include main.js </footer>
This arrangement seems to work fine only that, there's an exponential call to main.js each time an option is selected.
Doing something like this(below) doesn't seem to work, I'm guessing because AJAX is injected into the page and isn't aware of what scripts that are already available on the page?
<script>
var len = $('script').filter(function () {
return ($(this).attr('src') == 'main.js');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
var url = "main.js";
$.getScript(url);
}
</script>
Is there a simple way around this? To make sure that main.js works across all AJAX requests without having to include it with each request?
Sample main.js content.
Ajax snippet that populates the HTML Markup (buttons and textboxes)
$("#students").on("change", function (e) {
e.preventDefault();
var supervise = this.value;
var faculty = $("#faculty").val();
$.ajax({
method: "POST",
url: 'URL',
dataType: 'html',
data:
{
selectValue: supervise,
faculty: faculty
},
success: function (result) {
$("#ajaxResult").html(result);
}
})
});
When #statement_button from HTML markup returned from select dropdown is clicked
$('#statement_button').click(function (e) {
var student_statement = $("#student_statement").val();
if (student_statement == '') {
alert('Please enter your statement');
return false;
}
var student = $("#student").val();
var statement_button = $(this).attr("value");
$.ajax({
type: "POST",
url: formsUrl,
dataType: 'text',
data:
{
student_statement: student_statement,
student: studentusername,
statement_button: statement_button
},
success: function (result) {
$("#result").text(result);
$("textarea#student_statement").val('');
}
})
});
From the code you posted it looks like you can just delegate the button handling to the .ajaxResult element which is always present in the html (from the initial load).
So just changing how you bind your button handlers should be enough
$("#students").on("change", function (e) {
to
$('.ajaxResult').on('change', '#students', function (e) {
$('#statement_button').click(function (e) {
to
$('.ajaxResult').on('click', '#statement_button', function (e) {
etc..
So the script with the above code is run once in the initial load of the page (in a $(document).ready(..))

Passing parameters between html pages using jquery

I have one html page which contains a jquery function.
<script>
function loadCustomers() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getCustomers',
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td><a href="clientSiteInfo.html?client=">'+id+'</td><td>'+value+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadCustomers;
</script>
I have linked another html page for each row. When each rows populated, the id values has to be passed to the clientSiteInfo.html page.
In the clientSiteInfo.html page i have another jquery function similar to above.
<script>
function loadSites() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getSite?clientName='+${param.client},
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadSites;
</script>
in the GET url I try to read client parameter. But it is not passing from my initial page.
What Im doing wrong here? I look for simple solution
jQuery doesn't have a native way to read the url parameters. However, javascript works just fine:
function getParameterByName(name) {
const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' ') );
}
In your code you would just call it as getParameterByName('client')

How to use jQuery to reload Partial with new parameter

I have a partial view that I load in a page passing in a parameter. When the page loads, I setup two parameters helpMember and helpAnonymous.
{
var helpMember = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(0);
var helpAnonymous = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(1);
}
<div id="contextual-help-partial" >
#Html.Partial("ContextualHelp", helpMember)
</div>
With jQuery, how can I reload the Partial and pass helpAnonymous to it?
You have to create one method in controller and call that action using this. Suppose created action as loadhtml. return partialview from that action.
Controller action as
public ActionResult loadhtml(string helpMember){
ViewBag.helpMember = helpMember;
return PartialView("ContextualHelp");
}
jquery code as
$.ajax({
type: 'GET',
url: "/loadhtml?helpMember=#helpMember",
datatype:"html",
success: function (data) {
$("#contextual-help-partial").empty().html(data);
},
error: function (err) {
}
});

Url.Content for javascript

I currently use this approach to obtain the correct relative URI (independent of the deployment situation). Razor code (asp.net mvc 3):
#section JavaScript
{
<script type="text/javascript">
var _getUrl = "#Url.Content("~/bla/di/bla")";
</script>
}
Separate js file:
$.ajax({
url: _getUrl,
Do you reckon there is a better approach?
Personally I prefer using HTML5 data-* attributes or including the URL as part of some DOM element that I unobtrusively AJAXify.
The thing is that you never write $.ajax calls flying around like that. You write them to correspond to some DOM events. Like for example clicking of an anchor. In this case it's trivial, you just use an HTML helper to generate this anchor:
#Html.ActionLink("click me", "someAction", "somecontroller", new { id = "123" }, new { #class = "link" })
and then:
$('.link').click(function() {
$.ajax({
url: this.href,
type: 'GET',
success: function(result) {
...
}
});
return false;
});
or maybe you are AJAXifying a form:
#using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post, new { id = "myForm" }))
{
...
}
and then:
$('#myForm').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
...
}
});
return false;
});
Another example would be to use HTML5 data-* attributes when an appropriate url is not available on the corresponding DOM element. Suppose that you want to invoke a controller action with AJAX when the selection of a dropdown changes. Think for example cascading ddls.
Here's how your dropdown might look like:
#Html.DropDownListFor(x => x.SelectedValue, Model.Values, new { id = "myDdl", data_url = Url.Action("SomeAction") })
and then:
$('#myDdl').change(function() {
var url = $(this).data('url');
var selectedValue = $(this).val();
$.getJSON(url, { id: selectedValue }, function(result) {
...
});
});
So as you can see you don't really need this _getUrl global javascript variable that you declared in your view.
I would do the following:
Razor C# script before Javascript
#{
var myUrlString = Url.Action("ActionName", new { controller="ControllerName" });
}
JavaScript
$.ajax('#myUrlString',{
// options
});
You could also use Url.RouteUrl or Url.HttpRouteUrl.
EDIT - showing example with separated JS file
Razor
#{
var myServerGeneratedValue = Url.Action("ActionName", new{controller="ControllerName"});
}
<script type="text/javascript">
var myHelperObject = new MyHelperObject();
myHelperObject.Init('#myServerGeneratedValue');
</script>
JS file
var MyHelperObject = function(){
this.Init = function(serverGeneratedValue){
// do something with serverGeneratedValue
};
};

Categories