Laravel 5.5 autocomplete method returns a 500 error in one place not another - jquery-ui

I have a simple form to get an autocomplete of an author's name from a table of several thousand.
In my simple form I have:
<form>
<div class="ui-widget">
<label for="authors">authors: </label>
<input id="authors" value="">
</div>
</form>
The javascript is:
<script>
$(function()
{
$( "#authors" ).autocomplete({
source: "autocompleteAuthors",
minLength: 3,
select: function(event, ui) {
$('#q').val(ui.item.value);
}
});
});
</script>
I have a route pointing to a controller:
Route::get('autocompleteAuthors','AutoCompleteController#authors')->name('autocompleteAuthors');
and a function in the controller:
public function authors()
{
$term = Input::get('term');
$results = array();
$queries = DB::table('author')
->where('name', 'LIKE', '%'.$term.'%')
->take(5)->get();
foreach ($queries as $query)
{
$results[] = [ 'id' => $query->id, 'value' => $query->name];
}
return Response::json($results);
}
This works fine.
In a form to edit a quote (part of the edit could be the author) I have the following:
<div class="ui-widget">
<label for="author" style="width:10%">author:</label>
<input id="author" name="author" value="{{ $author[0]->name }}" style="width:50%">
</div>
and the javascript is:
<script>
$(function()
{
$( "#author" ).autocomplete({
source: "autocompleteAuthors",
minLength: 3,
select: function(event, ui) {
$('#q').val(ui.item.value);
}
});
});
</script>
So they are both sending "term" to the same route yet in the second case I get a 500 error.
Can't see any reason for this!

I managed to sort it out. If you set the value in
<input id="author" name="author" value="{{ $author[0]->name }}" style="width:50%">
everything fails.
The answer is very simple: set it after the ui is called.
So my form includes:
<div class="ui-widget">
<label for="author" style="width:10%">author:</label>
<input id="author" name="author" style="width:50%">
</div>
and I invoke the ui with
$(function() {
$( "#author" ).autocomplete({
source: "{{ route('autocompleteAuthors') }}",
minLength: 3,
select: function(event, ui) {
$('#q').val('ui.item.value');
}
});
});
and then I add the initial value:
$( "#author" ).val("{{ $author[0]['name'] }}");

Related

Recaptcha image challenge always occurs in Microsoft Edge after form submission (Invisible recaptcha)

I've just implemented invisible recaptcha into a web form. Everything works fine with Chrome. But with Microsoft Edge, the image challenge always occurs with every form submission. Which is embarrassing for the users of the website. An idea?
Thanks a lot for your insights and advice :o)
Laurent
Javascript code:
window.onScriptLoad = function () {
var htmlEl = document.querySelector('.g-recaptcha');
var captchaOptions = {
'sitekey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'size': 'invisible',
'badge': 'inline',
callback: window.onUserVerified
};
var inheritFromDataAttr = true;
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};
window.onUserVerified = function (token) {
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data : {
'lastname' : $("#lastnameField").val(),
'firstname' : $("#firstnameField").val(),
'city' : $("#cityField").val(),
'postalCode' : $("#postalcodeField").val(),
'g-recaptcha-response' : token
},
success:function(data) {
// informs user that form has been submitted
// and processed
},
error: function(xhr, textStatus, error){
// informs user that there was a problem
// processing form on server side
}
});
};
function onSubmitBtnClick () {
window.grecaptcha.execute;
}
HTML code:
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoad" async defer></script>
<script type="text/javascript" src="js/petition.js"></script>
...
</head>
<body>
<form id="petitionForm" onsubmit="return false;">
<input id="lastnameField" type="text" name="lastname" placeholder="Lastname" required value="Doe">
<input id="firstnameField" type="text" name="firstname" placeholder="Firstname" required value="John">
<input id="postalcodeField" type="text" name="postalCode" placeholder="Postal Code" required value="ABCDEF">
<input id="cityField" type="text" name="city" placeholder="City" value="Oslo">
....
<input type="submit" name="login" class="g-2" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxx" id="signButton" data-callback='' value="Signer" onclick="onSubmitBtnClick();">
<div class="g-recaptcha" id="recaptchaElement" style="align-content: center"></div>
</form>
...
</body>
</html>

How to get text box value in ember.js

i have started to work on ember.js just day before.
i don't know how to get text box value while submitting. i have tried like this
this is html
<script type="text/x-handlebars" data-template-name="index">
<div >
<p>{{view Ember.TextField valueBinding="fname"}}</p>
</div>
<div>
<p>{{view Ember.TextField valueBinding="lname"}}</p>
</div>
<button {{action save}}>submit</button>
</script>
this is my ember.js file
App = Ember.Application.create();
App.IndexController = Ember.ObjectController.extend({
save:function()
{
var fname=this.get('fname');
var lname=this.get('lname');
alert(fname+','+lname);
}
});
whenever i am clicking on submit button, i am getting undefined in alert.so how to get value? i hope anyone will help me for to continue in ember.js
in js like this
App.WebFormController = Ember.Controller.extend({
fname: null,
lname: null,
save: function () {
var fname = this.get('fname');
var lname = this.get('lname');
alert(fname + ',' + lname);
}
});
without need a model
in template like this
<script type="text/x-handlebars" data-template-name="web_form">
<form {{action save on="submit"}}>
<div >
<p>{{input type="text" valueBinding="fname"}}</p>
</div>
<div>
<p>{{input type="text" valueBinding="lname"}}</p>
</div>
<button>submit</button>
</form>
</script>
Your problem is that your form doesn't have a model. You can provide it using model or setupController hook.
App.IndexRoute = Ember.Route.extend({
model: function() {
return {};
},
// or
setupController: function(controller) {
controller.set('model', {});
}
});
In addition some tips:
Use the action name on="submit" in the form, instead of action name in submit button. So you can execute the action when the user press enter key, in input.
And the input type="text" helper is a shortcut for view Ember.TextField
<script type="text/x-handlebars" data-template-name="index">
<form {{action save on="submit"}}>
<div >
<p>{{input type="text" valueBinding="fname"}}</p>
</div>
<div>
<p>{{input type="text" valueBinding="lname"}}</p>
</div>
<button>submit</button>
<form>
</script>
Here a live demo
That is really nice tutorial by mavilein.
We can do it at controller level also.
App.IndexController = Ember.ObjectController.extend({
content:function(){
return {fname:null,lname:null}
}.property(),
save:function()
{
var fname=this.get('fname');
var lname=this.get('lname');
alert(fname+','+lname);
}
});
Or we can do it
App.IndexController = Ember.ObjectController.extend({
fname:null,
lname:null,
save:function()
{
var fname=this.get('fname');
var lname=this.get('lname');
alert(fname+','+lname);
}
});
Below code is working for me:
cshtml: In script on tag specify data-template-name="text"
<script type="text/x-handlebars" data-template-name="text">
{{view Ember.TextField value=view.message}}
{{view Ember.TextField value=view.specy}}
{{textarea value=view.desc id="catdesc" valueBinding="categor" cols="20" rows="6"}}
<button type="submit" {{action "submit" target=view}}>Done</button>
</script>
app.js:
App.TextView = Ember.View.extend({
templateName: 'text',
message:'',
specy: '',
desc:'',
actions: {
submit: function (event) {
var value = this.get('specy');
var spc = this.get('message');
var de = this.get('desc');
}
}
});

jQuery Mobile and Knockout.js templating, styling isnt applied

Ok so this is beginning to drive me insane. I have for several hours now searched and searched, and every single solution doesnt work for me. So yes, this question might be redundant, but i cant for the life of me get solutions to work.
I have a bunch of checkboxes being generated by a jquery template that is databound via knockout.js. However, it turns up unstyled. Afaik, it is something about jquery mobile does the styling before knockout renderes the template, so it ends up unstyled.
I have tried numerous methods to no avail, so i hope someone here can see what i am doing wrong.
(i am using jquery mobile 1.2.0 , jquery 1.8.2 and knockout 2.2.1)
This is the scripts:
<script type="text/javascript">
jQuery.support.cors = true;
var dataFromServer = "";
// create ViewModel with Geography, name, email, frequency and jobtype
var ViewModel = {
email: ko.observable(""),
geographyList: ["Hovedstaden","Sjælland","Fyn + øer","Nordjylland","Midtjylland","Sønderjylland" ],
selectedGeographies: ko.observableArray(dataFromServer.split(",")),
frequencySelection: ko.observable("frequency"),
jobTypes: ["Kontor (administration, sekretær og reception)","Jura","HR, Ledelse, strategi og udvikling","Marketing, kommunikation og PR","Handel og service (butik, service, værtinde og piccoline)","IT","Grafik og design","Lager, chauffør, bud mv.","Økonomi, regnskab og finans","Kundeservice, telefoninterview, salg og telemarketing","Sprog","Øvrige jobtyper"],
selectedJobTypes: ko.observableArray(dataFromServer.split(",")),
workTimes: ["Fulltid","Deltid"],
selectedWorkTimes: ko.observableArray(dataFromServer.split(","))
};
// function for returning checkbox selection as comma separated list
ViewModel.selectedJobTypesDelimited = ko.dependentObservable(function () {
return this.selectedJobTypes().join(",");
}, ViewModel);
var API_URL = "/webapi/api/Subscriptions/";
// function used for parsing json message before sent
function omitKeys(obj, keys) {
var dup = {};
var key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (keys.indexOf(key) === -1) {
dup[key] = obj[key];
}
}
}
return dup;
}
//Function called for inserting new subscription record
function subscribe() {
if($("#jobmailForm").valid()=== true){
//window.alert("add subscriptiooncalled");
var mySubscription = ko.toJS(ViewModel);
//var json = JSON.stringify(mySubscription);
var jsonSmall = JSON.stringify(omitKeys(mySubscription, ['geographyList','jobTypes','selectedJobTypesDelimited','workTimes']));
//window.alert(jsonSmall);
$.ajax({
url: API_URL,
cache: false,
type: 'POST',
contentType: 'application/json',
data: jsonSmall,
success: function (data) {
window.alert("success");
},
error: function (error) {
window.alert("ERROR STATUS: " + error.status + " STATUS TEXT: " + error.statusText);
}
});
}
}
function initializeViewModel() {
// Get the post from the API
var self = this; //Declare observable which will be bind with UI
// Activates knockout.js
ko.applyBindings(ViewModel);
}
// Handle the DOM Ready (Finished Rendering the DOM)
$("#jobmail").live("pageinit", function() {
initializeViewModel();
$('#jobmailDiv').trigger('updatelayout');
});
</script>
<script id="geographyTmpl" type="text/html">
<input type="checkbox" data-role="none" data-bind="attr: { value: $data }, attr: { id: $data }, checked: $root.selectedGeographies" />
<label data-bind="attr: { for: $data }"><span data-bind="text: $data"></span></label>
</script>
<script id="jobTypeTmpl" type="text/html">
<label><input type="checkbox" data-role="none" data-bind="attr: { value: $data }, checked: $root.selectedJobTypes" /><span data-bind="text: $data"></span></label>
</script>
Note, "jobmail" is the surrounding "page" div element, not shown here. And this is the markup:
<div data-role="content">
<umbraco:Item field="bodyText" runat="server"></umbraco:Item>
<form id="jobmailForm" runat="server" data-ajax="false">
<div id="jobmailDiv">
<p>
<label for="email">Email</label>
<input type="text" name="email" id="email" class="required email" data-bind="'value': email" />
</p>
<fieldset data-role="controlgroup" data-mini="true" data-bind="template: { name: 'geographyTmpl', foreach: geographyList, templateOptions: { selections: selectedGeographies } }">
<input type="checkbox" id="lol" />
<label for="lol">fkfkufk</label>
</fieldset>
<fieldset data-role="controlgroup" data-mini="true">
<p data-bind="template: { name: 'jobTypeTmpl', foreach: jobTypes, templateOptions: { selections: selectedJobTypes } }"></p>
</fieldset>
<fieldset data-role="controlgroup" data-mini="true">
<input type="radio" id="frequency5" name="frequency" value="5" data-bind="checked: frequencySelection" /><label for="frequency5">Højst 5 gange om ugen</label>
<input type="radio" id="frequency3" name="frequency" value="3" data-bind="checked: frequencySelection" /><label for="frequency3">Højst 3 gange om ugen</label>
<input type="radio" id="frequency1" name="frequency" value="1" data-bind="checked: frequencySelection" /><label for="frequency1">Højst 1 gang om ugen</label>
</fieldset>
<p>
<input type="button" value="Tilmeld" class="nice small radius action button" onClick="subscribe();">
</p>
Tilbage
</div>
</form>
Alternate method of invoking the restyling (doesnt work either):
$(document).on('pagebeforeshow', '#jobmail', function(){
// Get the post from the API
var self = this; //Declare observable which will be bind with UI
// Activates knockout.js
ko.applyBindings(ViewModel);
});
// Handle the DOM Ready (Finished Rendering the DOM)
$("#jobmail").live("pageinit", function() {
$('#jobmail').trigger('pagecreate');
});
Use a custom binding (Knockout) to trigger jQuery Mobile to enhance the dynamically created content produced by Knockout.
Here is a simple custom binding:
ko.bindingHandlers.jqmEnhance = {
update: function (element, valueAccessor) {
// Get jQuery Mobile to enhance elements within this element
$(element).trigger("create");
}
};
Use the custom binding in your HTML like this, where myValue is the part of your view model that changes, triggering the dynamic content to be inserted into the DOM:
<div data-bind="jqmEnhance: myValue">
<span data-bind="text: someProperty"></span>
My Button
<input type="radio" id="my-id" name="my-name" value="1" data-bind="checked: someOtherProperty" /><label for="my-id">My Label</label>
</div>
In my own case, myValue was part of an expression in an if binding, which would trigger content to be added to the DOM.
<!-- ko if: myValue -->
<span data-bind="jqmEnhance: myValue">
<!-- My content with data-bind attributes -->
</span>
<!-- /ko -->
Every dynamically generated jQuery Mobile content must be manually enhanced.
It can be done in few ways, but most common one can be done through the jQuery Mobile function .trigger( .
Example:
Enhance only page content
$('#page-id').trigger('create');
Enhance full page (header + content + footer):
$('#page-id').trigger('pagecreate');
If you want to find more about this topic take a look my other ARTICLE, to be more transparent it is my personal blog. Or find it HERE.

Disable jQuery Button with AngularJS and Form Validation

I would like to disable my jQuery button based on form validation. According to the docs this is fairly easy with regular buttons using syntax such as:
<button ng-click="save(user)" ng-disabled="form.$invalid">Save</button>
However, when changing to a jQuery UI button this no longer works. I assume that Angular has no real binding between jQuery UI and AngularJS and thus would require a directive to do the following:
$("button" ).button( "option", "disabled" );
Is that the case or are there other alternatives? A jsFiddle of what I'm trying to do is here: http://jsfiddle.net/blakewell/vbMnN/.
My code looks like this:
View
<div ng-app ng-controller="MyCtrl">
<form name="form" novalidate class="my-form">
Name: <input type="text" ng-model="user.name" required /><br/>
Email: <input type="text" ng-model="user.email" required/><br/>
<button ng-click="save(user)" ng-disabled="form.$invalid">Save</button>
</form>
</div>
Controller
function MyCtrl($scope) {
$scope.save = function (user) {
console.log(user.name);
};
$scope.user = {};
};
$(function () {
$("button").button();
});
Well the thing is with angular, you're supposed to be making directives to apply your JQuery plugins.
So here you could to this:
//NOTE: directives default to be attribute based.
app.directive('jqButton', {
link: function(scope, elem, attr) {
//set up your button.
elem.button();
//watch whatever is passed into the jq-button-disabled attribute
// and use that value to toggle the disabled status.
scope.$watch(attr.jqButtonDisabled, function(value) {
$("button" ).button( "option", "disabled", value );
});
}
});
and then in markup
<button jq-button jq-button-disabled="myForm.$invalid" ng-click="doWhatever()">My Button</button>
This worked for me:
app.directive('jqButton', function() {
return function(scope, element, attrs) {
element.button();
scope.$watch(attrs.jqButtonDisabled, function(value) {
element.button("option", "disabled", value);
});
};
});
With this markup:
<input type="button" value="Button" jq-button jq-button-disabled="myForm.$invalid" />

How to edit an array from a textarea in Ember js?

I'm trying to update an array from a textArea, each line of which would be a new item.
Here is what I tried to do, but the textArea doesn't update the array:
Handlebars:
<script type="text/x-handlebars">
{{view Ember.TextArea valueBinding="App.listController.formattedContent"}}
</br>
{{#each App.listController}}
{{this}}
{{/each}}
</script>
JavaScript:
App = Ember.Application.create({});
App.listController = Ember.ArrayController.create({
content: ['some', 'items', 'in', 'an', 'array'],
formattedContent: function() {
return this.get('content').join('\n');
}.property('content')
});
and the jsFiddle
I know it can't be that simple, but I have no idea where to start.
Any idea?
Here you go:
Fiddle: http://jsfiddle.net/Sd3zp
Ember Controller:
App.listController = Ember.ArrayController.create({
content: ['some', 'items', 'in', 'an', 'array'],
init: function() {
var content = this.get('content');
if(content.length > 0){
this.set('rawContent', content.join('\n'));
}
this._super();
},
rawContentDidChange: function(){
var rawContent = this.get('rawContent');
var content = rawContent.split('\n');
this.set('content',content);
}.observes('rawContent'),
});​
Handlebars template:
<script type="text/x-handlebars">
{{view Ember.TextArea valueBinding="App.listController.rawContent" rows="5"}}
<br />
<br />
<strong>Output listController content items:</strong>
{{#each App.listController.content}}
{{this}} <br />
{{/each}}
</script>
The accepted answer doesn't work with ember-1.0.0-rc3.
Computed properties can have setters now so the example in the question would be changed to
JS Bin: http://jsbin.com/iworub/2/
Handlebars:
<script type="text/x-handlebars" data-template-name="application">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
{{view Ember.TextArea valueBinding="formattedContent" rows="7"}}
</br>
{{#each content}}
{{this}}</br>
{{/each}}
</script>
JavaScript:
App = Ember.Application.create({});
App.IndexRoute = Ember.Route.extend({
setupController: function(controller) {
controller.set('content', ['some', 'items', 'in', 'an', 'array']);
}
});
App.IndexController = Ember.ArrayController.extend({
formattedContent: function(key, value) {
//getter
if (arguments.length === 1) {
return this.get('content').join('\n');
//setter
} else {
this.set('content', value.split('\n'));
}
}.property('content')
});

Resources