How to show autocomplete search result as a link - jquery-ui

I have successfully implemented autocomplete search option in my laravel project "book shop managing". Again from my homepage if I click on the name of a book then it would show the specific book. But how can I add link to my search result, so that if I click on a book from the result then it would take me to the page that contains the book details.
my index.blade.php
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#books" ).autocomplete({
source: 'auto_complete'
});
});
</script>
<div class="ui-widget">
<label for="books">Books: </label>
<input id="books">
</div>
controller
public function search(){
$search = Input::get('term');
$books = Book::where('title','like','%'.$search.'%')->get();
foreach ($books as $book) {
$data[] = $book->title;
}
// return $books;
return $data;
}
route
Route::get('auto_complete', 'BooksController#search');

CONTROLLER
public function search(){
$search = Input::get('term');
// return $search or dd($search) check if request get the value please
$books = Book::where('title','like','%'.$search.'%')->get();
// return $books or dd($books) check if request get the values please
$results = array();
foreach($books as $key => $v){
$results[]=['id' => $v->id];
}
// return a json object
return response()->json([
'suggestions'=>$results]);
}
JS
$(function() {
$( "#books" ).autocomplete({
source: 'auto_complete',
onSelect: function (data) {
location.href = "www.yourwebsite.com+data.suggestions.id" // this redirect for example book id:1 to www.yourwebsite.com/1
// Or use jquery to redirect: window.location.replace("http://stackoverflow.com");
}
});
});
Use the same route, let me know if there is some error in network or console!
I supposed that you integrated the jquery library and autocomplete library js :)

Related

Customizing Linkedin Login Button

I'm implementing LinkedIn Login into my web app..
I'm using following script as :
<script type="in/Login"> </script>
to load the LinkedIn Sign In button. This script automatically loads a LinkedIn Sign in button with fix design or image..
but I want to Customize a button with my custom Image of LinkedIn and this button should generate the LinkedIn login event after clicking on it.. that is it should serve above script's purpose
Plz Help
Other way to do this:
Place an image that you like:
<img onclick="liAuth()" src="./img/widget_signin.png">
Create JS function like this:
function liAuth(){
IN.User.authorize(function(){
callback();
});
}
Use LinkedIn user data:
IN.API.Profile("me")
.fields("firstName", "lastName", "headline")
.result(resultFunction);
Yes, it's possible. We're using jQuery, so here is our solution:
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: apikey
onLoad: onLinkedInLoad authorize: true
</script>
<script type="text/javascript">
function onLinkedInLoad() { // Use a larger login icon.
$('a[id*=li_ui_li_gen_]').css({marginBottom:'20px'})
.html('<img src="/images/shared/linkedin-register-large.png" height="31" width="200" border="0" />');
}
</script>
Under the head tag
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: xxxxxxxxx
authorize: true
// onLoad: onLinkedInLoad
//scope: r_basicprofile r_emailaddress
</script>
<a href="javascript:void(0)" class="btn btn-default btn-linkedin" onclick='call_linkedin()'>
<i class="fa fa-linkedin-square" aria-hidden="true"></i> <span>Sign In With LinkedIn</span> </a>
<script type="text/javascript">
function call_linkedin() {
if(IN.User.authorize()){
getProfileData();
}else{ IN.Event.on(IN, "auth", function() {getProfileData();});}
}
// Use the API call wrapper to request the member's profile data
function getProfileData() {
IN.API.Profile( "me" ).fields( "id", "first-name", "last-name", "headline", "location", "picture-url", "public-profile-url", "email-address" ).result( displayProfileData ).error( onError );
}
// Handle the successful return from the API call
function displayProfileData( data ) {
console.log(data)
}
</script>
Please try this and let me know
You can use your own custom html code like this:
<html>
<head>
<title>LinkedIn JavaScript API</title>
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: put_your_api_key_here
</script>
<script type="text/javascript">
function onLinkedInLoad() {
IN.UI.Authorize().place();
IN.Event.on(IN, "auth", function () { onLogin(); });
IN.Event.on(IN, "logout", function () { onLogout(); });
}
function onLogin() {
IN.API.Profile("me").result(displayResult);
}
function displayResult(profiles) {
member = profiles.values[0];
alert(member.id + " Hello " + member.firstName + " " + member.lastName);
}
</script>
</head>
<body>
<input type="button" onclick="onLinkedInLoad()" value="Sign in using LinkedIn account" />
</body>
</html>
method for custom linkedin button
<div onclick="liAuth()">sign in with linkedin</div>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: YOUR_API_KEY_HERE
authorize: true
onLoad: onLinkedInLoad
</script>
<script type="text/javascript">
function liAuth(){
IN.User.authorize(function(){
});
}
// Setup an event listener to make an API call once auth is complete
function onLinkedInLoad() {
IN.Event.on(IN, "auth", getProfileData);
}
// Handle the successful return from the API call
function onSuccess(data) {
console.log(data);
}
// Handle an error response from the API call
function onError(error) {
console.log(error);
}
// Use the API call wrapper to request the member's basic profile data
function getProfileData() {
IN.API.Raw("/people/~").result(onSuccess).error(onError);
}
</script>
**LinkedIn Customize button onclick function you can call linked in login function**
<!-- language: lang-html -->
<script type="text/javascript" src="http://platform.linkedin.com/in.js">
api_key: Your App Key //add your linkedIn aap key here
authorize: true
</script>
//create your customized linkedIn button with css
<div id="wLinkedIn">
// use onLinkedInLoad onclick function in customized button
<a href="#" onclick="onLinkedInLoad();">
<span id="icon-bg"><i class="fa fa-linkedin"></i></span>
<span id="icon-label-bg">Login with LinkedIn</span>
</a>
</div>
<!-- language: lang-js -->
// ----------------------------LinkedIn Sdk---------------------
function onLinkedInLoad() {
IN.UI.Authorize().place();
// call onLinkedInLogin on click of button
IN.Event.on(IN, "auth", function () { onLinkedInLogin(); });
//IN.Event.on(IN, "logout", function () { onLinkedInLogout(); });
}
function onLinkedInLogin() {
//alert('logged in');
//get all user data from linked in plugin
IN.API.Raw("/people/~:(id,firstName,lastName,emailAddress)format=json").result(function (data)
{
console.log(data);
var profileData = data;
LinkedInFName = profileData.firstName;
LinkedInLName = profileData.lastName;
LinkedInEmail = profileData.emailAddress;
LinkedInId = profileData.id;
//alert("LinkedInFName : " + LinkedInFName);
GetLinkedinLoginDetails(LinkedInEmail, LinkedInId)
}).error(function (error) {
console.log('Error : ' + error);
});
}
function onSuccess(data) {
}

How do I target a div when programmatically submitting and MVC Ajax form?

I'm using the MVC4 Ajax helper functions on a form and I'd like to submit the form from script.
The problem is when I call the submit function, it does not load into the proper div. Any thoughts?
#using (Ajax.BeginForm("NewGame", "Home", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "targetDiv" }, new { id = "newGameForm" }))
{
<input type="hidden" name="client_seed" id="client_seed" />
<input type="submit" value="New Game" id="NewGameButton" />
<a class=button onclick="$('#newGameForm').submit();">New Game</a>
}
Clicking the standard submit button load the results of the call into the targetDiv. Clicking on the anchor replaces the current div.
The key is to prevent default browser behavior via .preventDefault() or to return false at the end of the event handlers.
This is how I'd do it:
<div id="targetDiv"></div>
#using(Html.BeginForm("NewGame", "Home", FormMethod.Post,
new { id = "newGameForm" }))
{
<input type="hidden" name="client_seed" id="client_seed" />
<input type="submit" value="New Game" id="NewGameButton" />
}
<script type="text/javascript">
$(document).ready(function () {
$("#newGameForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
type: $(this).attr("method") // "POST"
})
.done(function(result) {
$("#targetDiv").html(result);
})
.fail(function((jqXHR, textStatus, errorThrown) {
// handle error
});
});
});
</script>
If you insist on using an anchor <a>...
New Game
<script type="text/javascript">
$(document).ready(function() {
$("#submit-link").on("click", function(e) {
e.preventDefault();
$("#newGameForm").submit();
});
$("#newGameForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
...
});
});
</script>
Edit There is also an AjaxHelper.ActionLink method. If you're already using the AjaxHelper in other parts of your code you might want to stick with that.
Pseudo Code.
<a class=button onclick="PostAjax();">New Game</a>
function PostAjax(){
$.ajax({
url:"Home/NewGame",
data:$('#newGameForm').serialize(),
DataType:"HTML", // assuming your post method returns HTML
success:function(data){
$("#targetDiv").html(data);
},
error:function(err){
alert(err);
}
})
}

asp.net mvc + knockout + ajax partial load + reuse viewodel and load different data within the same page

In a single asp.net MVC page, I've to show 3 reports of same layout/structor. So I created a page that generated a report using Knockout databind and 10 reports are generated by passing some additional parameters.
I tried to load all 3 reports using Ajax partial view and by this way I'm populating those 10 reports in one single page.
Now I happen to see a strange issue, the last report data appears for all the 3 reports though the data for each report is different. Anyone knows how to handle this issue ?
Main Page View, where I call 3 reports via Ajax call.
<div id="RecentlyAddedReport" ></div>
<div id="RecentlyConsultedReport"></div>
<div id="RecentlyPrescribedReport"></div>
<!-- start here -->
<script type="text/javascript">
$(document).ready(function () {
AjaxLoadReport('RecentlyAddedReport', 'Patient/Report?type=RecentlyAdded&name=Recently Added');
AjaxLoadReport('RecentlyConsultedReport', 'Patient/Report?type=RecentlyConsulted&name=Recently Consulted');
AjaxLoadReport('RecentlyPrescribedReport', 'Patient/Report?type=RecentlyPrescribed&name=Recently Prescribed');
});
function AjaxLoadReport(reportType, actionURL) {
var resultDiv = $('#' + reportType);
$.ajax({ type: "GET", url: actionURL, data: {},
success: function (response) {
resultDiv.html('');
resultDiv.html(response);
}
});
}
</script>
Report View - I call this same view for all the 3 reports
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<TryHomeo.Web.UI.Models.UserControlViewData>" %>
<script type="text/javascript" src="../../scripts/jquery-1.7.1.min.js"></script>
<script src="../../Scripts/jquery.timeago.js" type="text/javascript"> </script>
<script src="../../Scripts/knockout-2.1.0.js" type="text/javascript"> </script>
<h1>
<%:Model.ReportName%>
</h1>
<div class='loadingIndicator' title="Loading..."></div>
<ul id="<%=Model.ReportType %>" data-bind="template: { name: 'patient-template', foreach: patients}"></ul>
<script type="text/html" id="patient-template">
<span>
<li>
<div>
<a data-bind="text: PatientName"></a>- (<abbr class='timeago' data-bind="timeago: DatedString"></abbr>)
</div>
</li>
</span>
</script>
<script type="text/javascript">
// ReportViewModel View Model //
function ReportViewModel() {
var self = this;
self.patients = ko.observableArray([]);
}
var objVM = new ReportViewModel();
ko.applyBindings(objVM);
// Using jQuery for Ajax loading indicator
$(".loadingIndicator").ajaxStart(function () { $(this).fadeIn(); }).ajaxComplete(function () { $(this).fadeOut(); });
$(document).ready(function () {
$.ajax({
dataType: 'json',
url: '/Patient/GetPatientReport/?type=' + '<%=Model.ReportType %>' + '&' + '<%=DateTime.Now.ToString() %>',
success: SetData,
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
});
function SetData(data) {
objVM.patients(data);
}
ko.bindingHandlers.timeago = {
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
var $this = $(element);
// Set the title attribute to the new value = timestamp
$this.attr('title', value);
// If timeago has already been applied to this node, don't reapply it -
// since timeago isn't really flexible (it doesn't provide a public
// remove() or refresh() method) we need to do everything by ourselves.
if ($this.data('timeago')) {
var datetime = $.timeago.datetime($this);
var distance = (new Date().getTime() - datetime.getTime());
var inWords = $.timeago.inWords(distance);
// Update cache and displayed text..
$this.data('timeago', { 'datetime': datetime });
$this.text(inWords);
} else {
// timeago hasn't been applied to this node -> we do that now!
$this.timeago();
}
}
};
</script>

Difference between anchor link & window.location?

I have the link below:
<a href='#Url.Action("MyAction","MyController", new SearchCriteriaAffaire { Page=3, PageSize=5 }, null)'>Test1</a>
This links works. I received my search criteria in my action page.
Now, I have the button with javascript below:
<button id="buttonTest2">Test2</button>
<script language="javascript">
$("#buttonTest2").click(function () {
document.location = '#Url.Action("MyAction","MyController", new SearchCriteriaAffaire { Page=3, PageSize=5 }, null)';
});
</script>
This button doest' work. I mean, I didn't receive my search criteria in my action page and I don't know why??
It drives me crazy!
Test1 and Test2 produces exactly the same url (I check in 'view source code' by right clicking on the html page):
/?SortBy=None&Page=3&PageSize=5'
Any help will be greatly appreciated.
try this :
<button id="buttonTest2">Test2</button>
<script language="javascript">
$("#buttonTest2").click(function () {
document.location = '#Html.Raw(Url.Action("MyAction","MyController", new SearchCriteriaAffaire { Page=3, PageSize=5 }, null))';
});
</script>

ASP.NET MVC | Problem about showing modal dialog using jQuery dialog widget

I am very fresh to asp.net mvc and jQuery. After one day trying, I still don't know how to pop up a jQuery dialog using data from a action(return JsonResult) while user click a link.
Any suggest or guideline is appreciate.
Thanks!
Thx for Stuntz & RhinoDevX64 's reply, finally I work it out.
jQuery Code:
<script type="text/javascript">
$(function() {
$('.newsitem').click(function() {
var $thisLink = $(this);
$('#dialog').empty();
$.getJSON($thisLink.attr("href"), function(data) {
$('#dialog').html(data.content);
$("#dialog").dialog({
autoOpen: false,
title: data.title,
bgiframe: true,
modal: true,
height: 450,
width: 540,
buttons: {
'关闭': function() {
$(this).dialog('close');
}
}
});
$('#dialog').dialog('open');
});
return false;
});
});
</script>
ActionLink
<%= Html.ActionLink(item.Title, "GetByJs", "Article", new { id = item.ID }, new { #class = "newsitem" })%>
Action Code
public ActionResult GetByJs(Guid id) {
var item = Article.SingleOrDefault(a => a.ID == id && a.AtFront == true);
var jsonData = new {
title = item.Title, content = item.BodyContent
};
return new JsonResult {
Data = jsonData
};
}
var ph = $("#idOfPlaceHolderInPage");
ph.load(/Controller/SomeActionWhichReturnsPartialView, function() {
// this callback will be called after your partial view loaded into placeholder
ph.dialog({
// pass options here to customize dialog
});
});
1st use jQuery UI follow their documentation for including the css and js files.
<script src="../../Scripts/jquery-1.3.2.js" type="text/javascript" ></script>
<script src="../../Scripts/jquery-ui-1.7.1.custom.min.js" type="text/javascript"></script>
<link href="../../Content/jquery-ui-1.7.1.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function(){
$("#idOfModalPlaceholder").dialog({autoOpen: false, title:"MODAL TITLE"});
});
function OpenModalGetContent(){
$("#idOfModalPlaceHolder").load("/Controller/View");
$("#idOfModalPlaceHolder").dialog('open');
}
</script>
CLICK HERE FOR MODAL
2nd You should really just use a regular ActionResult and a Partial View (*.ascx), if you are just grabbing some content;
if you are calling data I presume you may be loading into an autocomplete which would be completely different than this scenario.

Resources