possible to make ajax call for 2 links with one function - javascript

When I click fetch, I need the data to be fetched but not displayed in the form, but when I click feeling lucky, i want to display the list and fill up the form.
I got the logic working well for fetch link, Do I have to repeat the same for feeling lucky link? is there a optimized way to do it.
$post-item-# click event is inside success call data each loop, is that the right place to do it?
Here's a mirror of the snippet below: JSFiddle
Data
{
tag: "urlfoodchannel,chocolate,dessert",
searchedTags: "urlfoodchannel,chocolate,dessert|urlfoodchannel,chocolate,dessert|urlfoodchannel,chocolate,dessert",
tagPage: "/food/urlfoodchannel,chocolate,dessert-recipes/",
page: "2",
pages: "2",
total: "20",
posts: [{
postId: "21122896",
postUrl: "/article/2014/12/30/chocolate-oreo-ice-cream/21122896/",
postTitle: "Chocolate Oreo Ice Cream",
postExcerpt: "This creamy chocolate ice cream with chunks of Oreo cookie is perfect and surprisingly easy to make!",
postAuthor: "Marin Mama Cooks",
postPubdate: "2014-12-30T20:49:00",
postPubdateUnix: "1419990540",
postImage: "http://urlcdn.com/hss/storage/midas/201316424/chocolate-oreo-ice-cream-11.jpg"
} {
postId: "21122797",
postUrl: "/article/2014/12/30/sheet-pan-smores/21122797/",
postTitle: "Sheet Pan S'mores",
postExcerpt: "You've never had s'mores quite like this! Try this decadent and delicious recipe for sheet pan s'mores.",
postAuthor: "Oh, Bite It",
postPubdate: "2014-12-30T15:26:00",
postPubdateUnix: "1419971160",
postImage: "http://urlcdn.com/hss/storage/midas/201315673/spsbet.jpg"
}]
}
Script
$(document).ready(function () {
$("#fetch").on("click", function () {
tags = $("#tags").val();
count = $("#count").val() ? $("#count").val() : "10";
page = $("#page").val() ? $("#page").val() : "1";
apiurl = "http://urlblog.url.com/api/tags-v1/" + tags + "?pageSize=" + count + "&page=" + page;
$.ajax({
type: 'GET',
url: apiurl,
data: {
get_param: 'value'
},
success: function (data) {
$("#tag").text(data.tagPage);
$.each(data.posts, function (i) {
$("#posts").append('<li class="post-item-' + i + '"><p class="post-title">' + data.posts[i].postTitle + ' <img class="add-row" src="/portalcms/_tool/media/add.png">+</p><p class="post-thumb"><img src="' + data.posts[i].postImage + '" width="150px" class="post-image"/></p><p class="post-url">' + data.posts[i].postUrl + '</p></li>');
$(".post-item-" + i).bind("click", function () {
k = i + 1;
tval = $(this).find(".post-title").text();
ival = $(this).find(".post-image").attr("src");
uval = $(this).find(".post-url").text();
$("#input-link" + k + "\\.alt").val(tval);
$("#input-link" + k + "\\.href").val(uval);
$("#input-link" + k + "\\.credit").val(ival);
});
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<fieldset class="visible">Tags for tomorrow:
<input type="text" name="futuretags" id="future-tags" />
</fieldset>
<fieldset class="visible">Tags:
<input type="text" name="tags" id="tags" value="" />Count:
<input type="text" name="count" id="count" value="10" />Page:
<input type="text" name="page" id="page" value="1" /> Fetch
Feeling Lucky
<ul id="posts"></ul>
</fieldset>
<fieldset>
<legend>Link 1:</legend>
<ul class="inputs">
<li class="compact quickFormField-file ">
<label for="input-link1.src._action">Image:</label>
<br />
<select id="input-link1.src._action" name="link1.src._action">
<option value="no">No File</option>
<option value="upload">Upload a New File:</option>
<option value="url">Use File at Asset URL:</option>
</select> <span class="upload" style="display: none;"><input type="file" name="link1.src._upload" /></span>
<span class="url" style="display: none;"><input type="text" name="link1.src._url" value="" /> <small>(e.g. /path/to/file.jpg)</small></span>
</li>
<li class="">
<label for="input-link1.alt">Alt Text:</label>
<input id="input-link1.alt" type="text" name="link1.alt" value="" />
</li>
<li class="">
<label for="input-link1.credit">Credit:</label>
<input id="input-link1.credit" type="text" name="link1.credit" value="" />
</li>
<li class="">
<label for="input-link1.href">Href (URL):</label>
<input id="input-link1.href" type="text" name="link1.href" value="" />
</li>
</ul>
<div class="advancedgrp">
<div class="hdr">Show Advanced Options</div>
<fieldset class="cnt">
<legend>Advanced Options:</legend>
<ul class="inputs">
<li class="">
<label for="input-link1.target">Target:</label>
<select id="input-link1.target" name="link1.target">
<option value="">Same Window</option>
<option value="_blank">New Window</option>
</select>
</li>
<li class="">
<label for="input-link1.onclick">Onclick:</label>
<input id="input-link1.onclick" type="text" name="link1.onclick" value="" />
</li>
<li class="">
<label for="input-link1.otherAtts">Other Attributes:</label>
<input id="input-link1.otherAtts" type="text" name="link1.otherAtts" value="" />
</li>
<li class="">
<label for="input-link1.trackKey">Tracking Key:</label>
<select id="input-link1.trackKey" name="link1.trackKey">
<option value="icid" selected="selected">icid</option>
<option value="ncid">ncid</option>
</select>
</li>
<li class="">
<label for="input-link1.trackVal">Tracking Value:</label>
<input id="input-link1.trackVal" type="text" name="link1.trackVal" value="" />
</li>
</ul>
</fieldset>
</div>
<ul class="inputs"></ul>
</fieldset>
<fieldset>
<legend>Link 2:</legend>
<ul class="inputs">
<li class="compact quickFormField-file ">
<label for="input-link2.src._action">Image:</label>
<br />
<select id="input-link2.src._action" name="link2.src._action">
<option value="no">No File</option>
<option value="upload">Upload a New File:</option>
<option value="url">Use File at Asset URL:</option>
</select> <span class="upload" style="display: none;"><input type="file" name="link2.src._upload" /></span>
<span class="url" style="display: none;"><input type="text" name="link2.src._url" value="" /> <small>(e.g. /path/to/file.jpg)</small></span>
</li>
<li class="">
<label for="input-link2.alt">Alt Text:</label>
<input id="input-link2.alt" type="text" name="link2.alt" value="" />
</li>
<li class="">
<label for="input-link2.credit">Credit:</label>
<input id="input-link2.credit" type="text" name="link2.credit" value="" />
</li>
<li class="">
<label for="input-link2.href">Href (URL):</label>
<input id="input-link2.href" type="text" name="link2.href" value="" />
</li>
</ul>
<div class="advancedgrp">
<div class="hdr">Show Advanced Options</div>
<fieldset class="cnt">
<legend>Advanced Options:</legend>
<ul class="inputs">
<li class="">
<label for="input-link2.target">Target:</label>
<select id="input-link2.target" name="link2.target">
<option value="">Same Window</option>
<option value="_blank">New Window</option>
</select>
</li>
<li class="">
<label for="input-link2.onclick">Onclick:</label>
<input id="input-link2.onclick" type="text" name="link2.onclick" value="" />
</li>
<li class="">
<label for="input-link2.otherAtts">Other Attributes:</label>
<input id="input-link2.otherAtts" type="text" name="link2.otherAtts" value="" />
</li>
<li class="">
<label for="input-link2.trackKey">Tracking Key:</label>
<select id="input-link2.trackKey" name="link2.trackKey">
<option value="icid" selected="selected">icid</option>
<option value="ncid">ncid</option>
</select>
</li>
<li class="">
<label for="input-link2.trackVal">Tracking Value:</label>
<input id="input-link2.trackVal" type="text" name="link2.trackVal" value="" />
</li>
</ul>
</fieldset>
</div>
<ul class="inputs"></ul>
</fieldset>
<fieldset>
<legend>Link 3:</legend>
<ul class="inputs">
<li class="compact quickFormField-file ">
<label for="input-link3.src._action">Image:</label>
<br />
<select id="input-link3.src._action" name="link3.src._action">
<option value="no">No File</option>
<option value="upload">Upload a New File:</option>
<option value="url">Use File at Asset URL:</option>
</select> <span class="upload" style="display: none;"><input type="file" name="link3.src._upload" /></span>
<span class="url" style="display: none;"><input type="text" name="link3.src._url" value="" /> <small>(e.g. /path/to/file.jpg)</small></span>
</li>
<li class="">
<label for="input-link3.alt">Alt Text:</label>
<input id="input-link3.alt" type="text" name="link3.alt" value="" />
</li>
<li class="">
<label for="input-link3.credit">Credit:</label>
<input id="input-link3.credit" type="text" name="link3.credit" value="" />
</li>
<li class="">
<label for="input-link3.href">Href (URL):</label>
<input id="input-link3.href" type="text" name="link3.href" value="" />
</li>
</ul>
<div class="advancedgrp">
<div class="hdr">Show Advanced Options</div>
<fieldset class="cnt">
<legend>Advanced Options:</legend>
<ul class="inputs">
<li class="">
<label for="input-link3.target">Target:</label>
<select id="input-link3.target" name="link3.target">
<option value="">Same Window</option>
<option value="_blank">New Window</option>
</select>
</li>
<li class="">
<label for="input-link3.onclick">Onclick:</label>
<input id="input-link3.onclick" type="text" name="link3.onclick" value="" />
</li>
<li class="">
<label for="input-link3.otherAtts">Other Attributes:</label>
<input id="input-link3.otherAtts" type="text" name="link3.otherAtts" value="" />
</li>
<li class="">
<label for="input-link3.trackKey">Tracking Key:</label>
<select id="input-link3.trackKey" name="link3.trackKey">
<option value="icid" selected="selected">icid</option>
<option value="ncid">ncid</option>
</select>
</li>
<li class="">
<label for="input-link3.trackVal">Tracking Value:</label>
<input id="input-link3.trackVal" type="text" name="link3.trackVal" value="" />
</li>
</ul>
</fieldset>
</div>
<ul class="inputs"></ul>
</fieldset> <span id="tag"></span>

What you can do is just write the javascript function like this:
$(function(){
var searchmethods = {
fetched : false,
data : "",
fetch : function(callback) {
$.ajax({
success: function(data) {
fetched = false;
searchmethods.data = data;
if($.isFunction(showResults)) showResults();
}
});
},
lucky : function() {
if(searchmethods.fetched) {
searchmethods.showResults();
} else {
searchmethods.fetch(searchmethods.showResults);
}
},
showResults : function() {
// show results
}
};
$(".link").click(function(){
var action = $(this).data("action");
searchmethods[action].apply(this);
});
});
i like this way because you have all the code that you are going to need into an object
called searchmethods and it has the methods. Here is how does this work:
searchmethods.fetch() is called when you click on the fetch link, and retrieves the
data with the jQuery $.ajax() method.
searchmethods.lucky() is called when you click on the lucky link, checks if the data has been
retrieved, if not then it calls the searchmethods.fetch() method an it passes the function searchmethods.lucky() by parameter so it can be called after the $.ajax() retrieves the data
and the HTML like this:
<a data-action="fetch" class="link">fetch</a>
<a data-action="lucky" class="link">lucky</a>
but it is up to you, that's just an easy way
EDIT: answer it's already updated, sorry about my weird english

Related

Trigger autocomplete for the field of the modal that is active

The scenario here is that on the several pages I am having modals that have a autocomplete search field. so instead of giving several different IDs to each field, and then triggering them, I used a common class and tried to trigger autocomplete() on the field that resides in modal with .activeModal class.
function customerSearch() {
$(".activeModal .customerSearch").autocomplete({
minLength: 1,
focus: function(event, ui) {
event.preventDefault();
$(".activeModal .customerSearch").val(ui.item.label);
},
source: function(request, response) {
$.ajax({
url: "/operations.php",
dataType: "json",
type: "post",
data: {
"req": "searchCustomer",
"query": $(".activeModal .customerSearch").val(),
},
success: function(data) {
response($.map(data, function(item) {
return {
id: item.id,
label: item.label,
value: item.value
}
}));
}
})
},
select: function(event, ui) {
event.preventDefault();
$(".activeModal .customerSearch").val(ui.item.label);
$(".activeModal .customer_id").val(ui.item.value);
}
})
}
$(document).ready(function() {
customerSearch();
});
However this is not working; it's not showing any results. Neither is it giving any errors when I checked the browser console.
What have I done wrong? I am new to jQueryUI so please spare me for silly mistakes.
EDIT : The question seems to be confusing many people, so; for example, here are 3 modals that have fields with same purpose on the same page:
<div class="modal" id="newGiftcard">
<div class="head">
<span class="modalTitle">
Issue new giftcard
</span>
<span class="controller">
<span class="close lnr lnr-cross"></span>
</span>
</div>
<div class="main">
<form id="newGiftCardForm">
<input type="text" name="customer" placeholder="Search customer" class="ui-widget customerSearch" id="customerSearch" />
<input type="hidden" class="customer_id" id="customer_id"/>
<input type="checkbox" id="walkinGC" class="walkin" /><label for="walkinGC"> Walk in</label>
<input type="text" id="cardNumber" placeholder="Gift card number" />
<input type="text" id="balance" placeholder="Balance" />
<select id="payMethod">
<option value="">Select a payment mode</option>
<option value="cash">cash</option>
<option value="card">card</option>
<option value="cheque">cheque</option>
</select>
<button type="button" id="IssueGC">Issue</button>
<button type="reset" class="grey">Reset</button>
</form>
</div>
</div>
<div class="modal" id="addBalance">
<div class="head">
<span class="modalTitle">
add balance
</span>
<span class="controller">
<span class="close lnr lnr-cross"></span>
</span>
</div>
<div class="main">
<p>please enter the amount:</p>
<form>
<input type="hidden" id="card" />
<input type="text" placeholder="amount" id="amount" />
<select id="payMethod">
<option value="">Select a payment mode</option>
<option value="cash">cash</option>
<option value="card">card</option>
<option value="cheque">cheque</option>
</select>
<button type="button" id="addBal">Add balance</button>
</form>
</div>
</div>
<div class="modal" id="changeOwner">
<div class="head">
<span class="modalTitle">
add balance
</span>
<span class="controller">
<span class="close lnr lnr-cross"></span>
</span>
</div>
<div class="main">
<p>please enter the amount:</p>
<form>
<input type="hidden" id="card" />
<input type="text" name="customer" placeholder="Search customer" class="ui-widget customerSearch"/>
<input type="hidden" class="customer_id"/>
<input type="checkbox" id="walkinGC" class="walkin" /><label for="walkinGC"> Walk in</label>
<button type="button" id="changeOW">Add balance</button>
</form>
</div>
</div>

How to make my ng-if stop showing after function success

I want my ng-if="AddEmp" to go false after my ng-click function has succeeded so the content in the ng-if doesn't show any longer, but I can't seem to make it happen.
I use the ng-if since I want the content in the form not to show the next time the form is visible. I always want it to be blank from the start.
How do I make the ng-if="AddEmp" disappear after this function has succeeded?
UserRegistration = function (Role, Id, Gender, Firstnamn, Lastnamn, DateOfBirth, phone, ClassId)
Here is my code:
Entire pages :
angular.module('App')
.controller('SchoolAdminController',
['$scope', '$http', '$location', 'getAllRolesFactory', 'checkUserRolesFactory', 'userRegistrationFactory', 'getAllClassesFactory',
function ($scope, $http, $location, getAllRolesFactory, checkUserRolesFactory, userRegistrationFactory, getAllClassesFactory)
{
var vm = this;
vm.allRoles;
vm.userWithRoles;
vm.userWithoutRoles;
vm.noUsersFound;
vm.allClasses;
getAllRolesFactory.get().then(function (response) {
vm.allRoles = JSON.parse('[' + response.data + ']');
});
vm.AddUser = function ()
{
$location.path('/Register');
}
vm.EditEmployee = function () {
$location.path('/SchoolAdmin/EditEmployee');
}
vm.UserWithoutRoles = function () {
checkUserRolesFactory.get(0).then(function (response) {
vm.userWithoutRoles = JSON.parse('[' + response.data + ']');
if (vm.userWithoutRoles.length < 1) {
vm.noUsersFound = 'Inga användare finns att hantera';
}
});
vm.GetAllClasses();
}
vm.UserWithRoles = function () {
checkUserRolesFactory.get(1).then(function (response) {
vm.userWithRoles = JSON.parse('[' + response.data + ']');
console.log(vm.userWithRoles);
});
}
vm.UserRegistration = function (Role, Id, Gender, Firstnamn, Lastnamn, DateOfBirth, phone, ClassId) {
vm.registerUserInfo = [];
vm.roleInfo = [];
vm.registerUserInfo.push({
Firstname: Firstnamn,
Lastname: Lastnamn,
DateOfBirth: DateOfBirth,
Gender: Gender,
UserId: Id,
ClassId: ClassId,
})
vm.roleInfo.push({
Role : Role,
})
console.log(vm.registerUserInfo);
userRegistrationFactory.register(vm.registerUserInfo, Role).then(function (response) {
$scope.AddEmp = false;
console.log(vm.AddEmp);
console.log("Hello my name is linsey lohan");
});
}
vm.GetAllClasses = function () {
getAllClassesFactory.get().then(function (response) {
console.log(vm.allClasses);
vm.allClasses = JSON.parse('[' + response.data + ']');
console.log(vm.allClasses);
})
}
}]);
#{
ViewBag.Title = "EditEmployee";
}
<div ng-controller="SchoolAdminController as SchoolAdmCtrl">
<div class="col-md-8 gradeSelect" ng-click="SchoolAdmCtrl.UserWithRoles(); editEmp = ! editEmp; AddEmp = false" id="editEmp">
<a><h1>Klicka här redigera Anställd:</h1></a>
</div>
<div class="col-md-8 gradeSelect" ng-if="editEmp">
<div>
#*TODO: Fixa, ta bort Gradeselect på hela formuläret.
En admin ska inte redigera sigsjälv på samma sätt som andra users i systemet.
*#
<form name="EditEmpForm">
<fieldset>
<legend>Välj anställd för hantering</legend>
<ol>
<li>
<label>
Välj roll att tilldela användare<br />
<select ng-model="SelectRole" name="SelectRole_field" ng-options="role as role for role in SchoolAdmCtrl.allRoles" required></select>
<span style="color:red" ng-show="EditEmpForm.SelectRole_field.$error.required">Välj roll</span>
</label>
</li>
<li>
<label>
Välj anställd
<select ng-model="selectUserWith" name="SelectUserWith_field"
ng-options=" user as user.Email for user in SchoolAdmCtrl.userWithRoles | filter : {Role : SelectRole}" required></select>
<span style="color:red" ng-show="EditEmpForm.SelectUserWith_field.$error.required">Välj användare</span>
</label>
</li>
<li>
<label>
Sök på person<br />
<input ng-model="Sokperson" type="text" />
</label>
</li>
</ol>
</fieldset>
<fieldset>
<legend>Redigera anställd</legend>
<ol>
<li>
<label>
Kön<br />
<select ng-model="Kon" name="Kon_field" required>
<option>Female</option>
<option>Male</option>
</select>
<span style="color:red" ng-show="EditEmpForm.Kon_field.$error.required">Välj kön</span>
</label>
</li>
<li>
<label>
Förnamn<br />
<input ng-model="Fornamn" name="Fornamn_field" type="text" required ng-minlength="2" ng-maxlength="20" ng-pattern="/^[a-z ,.'-]+$/i" />
<span style="color:red" ng-show="EditEmpForm.Fornamn_field.$error.minlength">För kort!</span>
<span style="color:red" ng-show="EditEmpForm.Fornamn_field.$error.maxlength">För långt!</span>
<span style="color:red" ng-show="EditEmpForm.Fornamn_field.$error.pattern"> A-Z -'!</span>
</label>
</li>
<li>
<label>
Efternamn<br />
<input ng-model="Efternamn" name="Efternamn_field" type="text" required ng-minlength="2" ng-maxlength="20" ng-pattern="/^[a-z ,.'-]+$/i" />
<span style="color:red" ng-show="EditEmpForm.Efternamn_field.$error.minlength">För kort!</span>
<span style="color:red" ng-show="EditEmpForm.Efternamn_field.$error.maxlength">För långt!</span>
<span style="color:red" ng-show="EditEmpForm.Efternamn_field.$error.pattern"> A-Z -'!</span>
</label>
</li>
<li>
<label>
Personnummer<br />
<input ng-model="Personnummer" name="Personnummer_field" type="text" placeholder="ÅÅÅÅ-MM-DD" ng-minlength="10" ng-maxlength="10" ng-pattern="/^((\d{4})-(\d{2})-(\d{2})|(\d{2})\/(\d{2})\/(\d{4}))$/" required />
<span style="color:red" ng-show="EditEmpForm.Personnummer_field.$error.pattern">Följ "ÅÅÅÅ-MM-DD".</span>
</label>
</li>
<li>
<label>
Telefonnummer<br />
<input ng-model="Telefon" name="Telefon_field" type="text" required ng-minlength="9" ng-maxlength="15" ng-pattern="/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/" />
<span style="color:red" ng-show="EditEmpForm.Telefon_field.$error.pattern">Felaktigt telefonformat.</span>
</label>
</li>
</ol>
</fieldset>
<fieldset ng-if="SelectRole=='Guardian'">
<legend>Redigera arbetsuppgifter</legend>
<ol>
<li>
<label>Välj Barn</label>
<select ng-model="selectedItem"></select>
</li> #* lägga till knapp för att kunna lägga till flera barn*#
<li>
<label>Sök barn</label>
<input type="text" requried />
</li>
</ol>
</fieldset>
<fieldset ng-if="SelectRole=='Student'">
<legend>Redigera arbetsuppgifter</legend>
<ol>
<li>
<label>Välj klass</label>
<select ng-model="selectedItem"></select>
</li>
<li>
<label>Sök på klassnamn</label>
<input type="text" required />
</li>
<li>
<label>
Förmyndare 1
<input type="text" required />
</label>
</li>
<li>
<label>
Förmyndare 2
<input type="text" required />
</label>
</li>
</ol>
</fieldset>
<fieldset ng-if="SelectRole=='Teacher'">
<legend>Redigera arbetsuppgifter</legend>
<ol>
<li>
<label>Välj klass</label>
<select ng-model="selectedItem"></select>
</li>
<li>
<label>Sök på klassnamn</label>
<input type="text" required />
</li>
<li>
<label>Aktuella klasser för anställd</label>
<ul>
<li>
<label>klass 1 test</label>
<input type="checkbox" />
</li>
<li>
<label>klass 2 test</label>
<input type="checkbox" />
</li>
</ul>
</li>
<li>
<label> Välj Kurs</label>
<select ng-model="selectedItem"></select>
</li>
<li>
<label>Sök på kursnamn</label>
<input type="text" required />
</li>
<li>
<label>Aktuella kurser för anställd</label>
<ul>
<li>
<label>kurs 1 test</label>
<input type="checkbox" />
</li>
<li>
<label>kurs 2 test</label>
<input type="checkbox" />
</li>
</ul>
</li>
<li>
</ol>
</fieldset>
<fieldset>
<button type=submit>Spara ändringar</button>
</fieldset>
</form>
</div>
</div>
<div class="col-md-8 gradeSelect" ng-click="SchoolAdmCtrl.UserWithoutRoles(); SchoolAdmCtrl.GetAllClasses(); AddEmp = ! AddEmp; editEmp = false" id="AddEmp">
<a><h1>Klicka här för att hantera anställda som ännu inte har roller i systemet</h1></a>
</div>
{{AddEmp}}
<div class="col-md-8 gradeSelect" ng-if="AddEmp">
<div>
<h1 style="color:red">{{SchoolAdmCtrl.noUsersFound}}</h1>
<form name="AddEmpForm" ng-if="SchoolAdmCtrl.noUsersFound !=''">
<fieldset>
<legend>Välj anställd för hantering</legend>
<ol>
<li>
<label>
Välj roll att tilldela användare<br />
<select ng-model="SelectRole2" name="SelectRole2_field" ng-options="role as role for role in SchoolAdmCtrl.allRoles" required></select>
<span style="color:red" ng-show="AddEmpForm.SelectRole2_field.$error.required">Välj roll</span>
</label>
</li>
<li>
<label>
Hantera anställda som ännu inte har roller i systemet<br />
<select ng-model="selectUserWithout2" name="SelectUserWithout2_field"
ng-options="user as user.Email for user in SchoolAdmCtrl.userWithoutRoles | filter : Sokperson2"
required></select>
<span style="color:red" ng-show="AddEmpForm.SelectUserWithout2_field.$error.required">Välj användare</span>
</label>
</li>
<li>
<label>
Sök på person<br />
<input ng-model="Sokperson2" type="text" />
</label>
</li>
</ol>
</fieldset>
<fieldset>
<legend>Redigera anställd</legend>
<ol>
<li>
<label>
Kön<br />
<select ng-model="Kon2" name="Kon2_field" required>
<option>Female</option>
<option>Male</option>
</select>
<span style="color:red" ng-show="AddEmpForm.Kon2_field.$error.required">Välj kön</span>
</label>
</li>
<li>
<label>
Förnamn<br />
<input ng-model="Fornamn2" name="Fornamn2_field" type="text" required ng-minlength="2" ng-maxlength="20" ng-pattern="/^[a-z ,.'-]+$/i" />
<span style="color:red" ng-show="AddEmpForm.Fornamn2_field.$error.minlength">För kort!</span>
<span style="color:red" ng-show="AddEmpForm.Fornamn2_field.$error.maxlength">För långt!</span>
<span style="color:red" ng-show="AddEmpForm.Fornamn2_field.$error.pattern"> A-Z -'!</span>
</label>
</li>
<li>
<label>
Efternamn<br />
<input ng-model="Efternamn2" name="Efternamn2_field" type="text" required ng-minlength="2" ng-maxlength="20" ng-pattern="/^[a-z ,.'-]+$/i" />
<span style="color:red" ng-show="AddEmpForm.Efternamn2_field.$error.minlength">För kort!</span>
<span style="color:red" ng-show="AddEmpForm.Efternamn2_field.$error.maxlength">För långt!</span>
<span style="color:red" ng-show="AddEmpForm.Efternamn2_field.$error.pattern"> A-Z -'!</span>
</label>
</li>
<li>
<label>
Personnummer<br />
<input ng-model="Personnummer2" name="Personnummer2_field" type="text" placeholder="ÅÅÅÅ-MM-DD" ng-minlength="10" ng-maxlength="10" ng-pattern="/^((\d{4})-(\d{2})-(\d{2})|(\d{2})\/(\d{2})\/(\d{4}))$/" required />
<span style="color:red" ng-show="AddEmpForm.Personnummer2_field.$error.pattern">Följ "ÅÅÅÅ-MM-DD".</span>
</label>
</li>
<li>
<label>
Telefonnummer<br />
<input ng-model="Telefon2" name="Telefon2_field" type="text" required ng-minlength="9" ng-maxlength="15" ng-pattern="/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/" />
<span style="color:red" ng-show="AddEmpForm.Telefon2_field.$error.pattern">Felaktigt telefonformat.</span>
</label>
</li>
</ol>
</fieldset>
<fieldset ng-if="SelectRole2=='Student'">
<ol>
<li>
<label>
Välj klass för elev<br />
<select ng-model="$parent.selectClass2" name="selectClass2_field" ng-options="klass as klass.Name for klass in SchoolAdmCtrl.allClasses" required></select>
<span style="color:red" ng-show="AddEmpForm.selectRole2_field.$error.required">Välj roll</span>
</label>
</li>
<li>
<label>
Sök på klass<br />
<input ng-model="Sokklass2" type="text" />
</label>
</li>
</ol>
</fieldset>
<button type="submit"
ng-disabled="
AddEmpForm.SelectRole2_field.$error.required ||
AddEmpForm.SelectUserWithout2_field.$error.required ||
AddEmpForm.Kon2_field.$error.required ||
AddEmpForm.Fornamn2_field.$error.minlength || AddEmpForm.Fornamn2_field.$error.maxlength || AddEmpForm.Fornamn2_field.$error.pattern || AddEmpForm.Fornamn2_field.$error.required ||
AddEmpForm.Efternamn2_field.$error.minlength || AddEmpForm.Efternamn2_field.$error.maxlength || AddEmpForm.Efternamn2_field.$error.pattern && AddEmpForm.Efternamn2_field.$error.required ||
AddEmpForm.Personnummer2_field.$error.pattern || AddEmpForm.Personnummer2_field.$error.required ||
AddEmpForm.Telefon2_field.$error.pattern || AddEmpForm.Telefon2_field.$error.required"
ng-click="SchoolAdmCtrl.UserRegistration(SelectRole2, selectUserWithout2.Id, Kon2, Fornamn2, Efternamn2, Personnummer2, Telefon2, selectClass2.Id)">
Spara ändringar
</button>
</form>
</div>
</div>
</div>
There are 2 things wrong that stand out.
You're making direct calls to class methods like so: SchoolAdmCtrl.UserWithRoles(). You should really be assigning those methods to your scope in your controller, like this:
$scope.UserWithRoles = function(){ ... }
Then you'll just need to call UserWithRoles(); like this:
ng-click="UserWithRoles();"
You're storing all of your data on that class. This might work just for this example, but like Guido Bouman said above, you should be storing it all on $scope. You're very likely to get undesired behavior if you have another instance of this controller I'd bet. Also, when you do this, you'll need to change all of your vm.blah references to just be blah since it'll be in your scope.

Jquery onclick not working or responsive

I would like to get the a user's details when a user's name is clicked through jquery, I have the following script:
$(document).ready(function(){
$('.employee_identification').keyup(function() {
var employee_identification = $('.employee_identification').val();
html = '';
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>admin_profile/get_employee_names/" + employee_identification,
dataType: "json",
success: function(response) {
employee_name_results = $('#employee_name_results').empty();
$.each(response, function(i, response) {
var f_name = response.f_name;
var s_name = response.s_name;
var other_name = response.other_name;
var identification_no = response.identification_no;
var str = f_name + s_name + other_name;
var employee_id = response.employee_id;
employee_name_results.append('<label class="form-label-top">Employee Name : </label> <a id="employee_name_searched" class="employee_name_searched btn btn-success" href="#add_user_window" value="' + str + '">' + str + '</a></br> <label class="form-label-top"> Identification Number: </label><span>' + identification_no + '</span><input type="hidden" value="' + employee_id + '" class="employee_searched_id" id="employee_searched_id"/></br>');
});
},
error: function(data) {
alert(data);
}
});
});
$('.employee_name_searched').click(function() {
alert('clicked');
var employee_id = $('.employee_searched_id').val();
$.ajax({
type: "GET",
url: "<?php echo base_url(); ?>admin_profile/get_employee_name_clicked/" + employee_id,
dataType: "json",
success: function(response) {
$.each(response, function(i, response) {
var f_name = response.f_name;
var s_name = response.s_name;
var other_name = response.other_name;
var is_active = response.is_active;
var employee_id = response.employee_id;
$('#add_f_name').val(f_name);
$('#add_s_name').val(s_name);
$('#add_other_name').val(other_name);
$('#add_is_active').val(is_active);
$('#add_employee_id').val(employee_id);
});
},
error: function(data) {
alert(data);
}
});
});
});
//HTML
<div> <a class="add_zone btn btn-success" id="add_user" href="#employee_search_window">
<i class="icon-plus-sign icon-white"></i>
Add User
</a> </div>
<!-- Employee User name search begins here -->
<div id="employee_search_window" class="employee_search_window" style="display: none !important;">
<form>
<div class="form-all">
<ul class="form-section">
<li id="cid_30" class="form-input-wide">
<label>Employee's Identification Number : <span class="form-required">*</span> </label>
</li>
<li>
<p class="red important">
Please provide employees Identification number :
</p>
<input type="text" class="employee_identification" id="employee_identification"/>
</li>
</ul>
</div>
<div id="employee_name_results" class="employee_name_results">
<label class="form-label-top">Employee Name : </label>
</div>
</form>
</div>
<!-- Add User Details Begins from here -->
<div id="add_user_window" style="display:none !important;">
<form class="add_user_form" id="add_user_form" method="post" >
<div class="form-all">
<ul class="form-section">
<li id="cid_30" class="form-input-wide">
<div class="form-header-group">
<h2 id="header_30" class="form-header">
User Information
</h2>
</div>
</li>
<li class="form-line" id="id_5">
<label class="form-label-top" id="label_5" for="user_name">
User Name<span class="form-required">*</span>
</label>
<div id="cid_5" class="form-input-wide">
<input type="text" class="form-number-input user_name form-textbox validate[required, Numeric]" id="user_name" name="add_user_name" style="width:204px" size="23" maxlength="8" data-type="input-number" />
</div>
</li>
<li class="form-line form-line-column" id="id_6">
<label class="form-label-top" id="label_6" for="f_name">
First Name<span class="form-required">*</span>
</label>
<div id="cid_6" class="form-input-wide">
<input type="text" class=" form-textbox f_name validate[required]" id="f_name" name="add_f_name" size="30" />
</div>
</li>
<li class="form-line form-line-column" id="id_6">
<label class="form-label-top" id="label_6" for="s_name">
Sur Name<span class="form-required">*</span>
</label>
<div id="cid_6" class="form-input-wide">
<input type="text" class=" form-textbox zone_rate validate[required]" id="s_name" name="add_s_name" size="30" />
</div>
</li>
<li class="form-line form-line-column" id="id_6">
<label class="form-label-top" id="label_6" for="other_name">
Other Name<span class="form-required">*</span>
</label>
<div id="cid_6" class="form-input-wide">
<input type="text" class=" form-textbox zone_rate validate[required]" id="other_name" name="add_other_name" size="30" />
</div>
</li>
<li class="form-line form-line-column" id="id_6">
<label class="form-label-top" id="label_6" for="employee_type">
Employee Type<span class="form-required">*</span>
</label>
<div id="cid_6" class="form-input-wide">
<select name="add_employee_type">
<?php ?>
<option>Select Employee Type</option>
<option value="Administrator">Administrator</option>
<option value="Director">Director</option>
<option value="Manager">Manager</option>
<option value="Accounts">Accounts</option>
</select>
</div>
</li>
<li class="form-line form-line-column" id="id_36">
<label class="form-label-top" id="label_36" for="is_active">
Is Active ?<span class="form-required">*</span>
</label>
<div id="cid_36" class="form-input-wide">
<select name="add_is_active">
<option value="Yes" >Yes</option>
<option value="No">No</option>
</select>
</div>
</li>
<li>
<input id="add_employee_id" class="add_employee_id" type="text"/>
</li>
<li class="form-line" id="id_27">
<div id="cid_27" class="form-input-wide">
<div style="text-align:left" class="form-buttons-wrapper">
<input type="submit" id="add_user_button" class="add_user_button" value="Add New User Details" />
</div>
</div>
</li>
</ul>
</div>
</form>
<p class="center">
</p>
<div class="clearfix"></div>
</div>
<!-- End of Add Employee Details -->
When the employee_name_searched is clicked, the second function which is a click should run to fetch the user's details but there's no response at all from the click. What have I done wrong? I keep getting the following error : TypeError: e._impala is undefined
You create the element after adding the event listener. Either you need to use .on() or you need to bind the event to each element upon its creation.
Move your click() function inside of your keyup() function after where you create your employee_name_searched element.
The reason you must do this is because you are binding your on click function to a non-existent element on page load because you have it inside of your on ready function. You have not yet made a key movement so your element has yet to be created.
Try this:
$('.employee_identification').keyup(function() {
// ajax request and append your new element
// bind your on click function to the element
$('.employee_name_searched').click(function() {
});
});

Order forms field calculation

I am building a order form for buying Bitcoins via JotForm.Maybe someone could give me a head start here. My order form has a a few fields I have a field with current Bitcoin price which is retrieved with PHP via JSON. What I would like to do is when a user enters a amount of bitcoins he would like to order the field of TOTAL SUM would refresh automatically based on amount he entered like "2xcurent price". Any help is like really appreciated!
This is how it looks visually:
http://oi60.tinypic.com/2k4fgw.jpg
Part of my form code is here:
<h2 id="header_13" class="form-header">
Order form
</h2>
</div>
</li>
<li class="form-line" id="id_15">
<div id="cid_15" class="form-input-wide">
<div id="text_15" class="form-html">
<p>
<strong>
Bitcoin price USD:<?php echo $usd; ?>
</strong>
</p>
</div>
</div>
</li>
<li class="form-line" id="id_18">
<div id="cid_18" class="form-input-wide">
<div id="text_18" class="form-html">
<p>
<strong>
Total Sum :
</strong>
</p>
</div>
</div>
</li>
<li class="form-line" id="id_3">
<label class="form-label-top" id="label_3" for="input_3"> Email: </label>
<div id="cid_3" class="form-input-wide">
<input type="email" class=" form-textbox validate[Email]" id="input_3" name="q3_elPastas" size="25" value="" maxlength="38" />
</div>
</li>
<li class="form-line" id="id_9">
<label class="form-label-top" id="label_9" for="input_9"> Bitcoin amount: </label>
<div id="cid_9" class="form-input-wide">
<input type="text" class=" form-textbox validate[Numeric]" data-type="input-textbox" id="input_9" name="q9_pasirinktosValiutos9" size="25" value="" />
</div>
</li>
<li class="form-line" id="id_10">
<label class="form-label-top" id="label_10" for="input_10"> Bitcoin address: </label>
<div id="cid_10" class="form-input-wide">
<input type="text" class=" form-textbox validate[AlphaNumeric]" data-type="input-textbox" id="input_10" name="q10_bitcoinAdresas10" size="25" value="" maxlength="37" />
</div>
</li>
<li class="form-line" id="id_14">
<label class="form-label-top" id="label_14" for="input_14"> </label>
<div id="cid_14" class="form-input-wide">
<div class="form-single-column"><span class="form-checkbox-item" style="clear:left;"><input type="checkbox" class="form-checkbox" id="input_14_0" name="q14_input14[]" value="I Agree to receive newsletter" />
<label for="input_14_0">I Agree to receive news letter </label></span><span class="clearfix"></span>
</div>
</div>
</li>
<li class="form-line" id="id_12">
<div id="cid_12" class="form-input-wide">
<div style="width:100%; text-align:Left;">
<script id="jcf_custom_field" type="text/javascript" src="http://js.jotform.com/WidgetsServer.min.js"></script>
<iframe onload="widgetFrameLoaded(12)" frameborder="0" scrolling="no" class="custom-field-frame" id="customFieldFrame_12" src="" style="border:none;width:400px; height: 45px">
</iframe>
<div>
<input id="input_12" class="form-hidden widget-required form-widget" type="hidden" name="q12_clickTo" value="">
</div>
</div>
</div>
</li>
<li class="form-line" id="id_2">
<div id="cid_2" class="form-input-wide">
<div style="text-align:center" class="form-buttons-wrapper">
<button id="input_2" type="submit" class="form-submit-button">
ORDER!
</button>
</div>
</div>
</li>
<li style="display:none">
Should be Empty:
<input type="text" name="website" value="" />
</li>
</ul>
I solved this by simply using an array of objects. So for example, I am accepting registrations. So to get the total price I go about it like this:
var registrants = [];
registrants.push({ price: 30 });
registrants.push({ price: 10 });
registrants.push({ price: 20 });
var totalPrice = 0;
for(var x = 0; x < registrants.length; x++){
totalPrice += registrants[x]["price"];
}
and you would just update the price property of the corresponding registrant when appropriate.

PHP form with javascript button - not working

I'm having some problems with a PHP form which should email values entered by a user to a specific email address. I've got a very similar form on my website which uses the same JS and PHP and works fine. I have copied the JS/PHP/HTML but just can't get it singing and dancing. I don't get any error messages, so I'm not even sure where the process is falling over.
I have used and abused Stackoverflow many times, but I just can't get my head around this one.
Form:
<h2 class="module-title">Application Form</h2>
<div class="content"><p>*Denotes required fields.</p></div>
<form action="/wp-content/themes/default/php/form.apply.php" method="post" name="application" id="application">
<div class="module-field-list">
<ul>
<li class="field-375">
<div class="field">
<label for="apply-surname" class="field-label">Surname</label>
<input name="apply-surname" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-firstname" class="field-label">First Name</label>
<input name="apply-firstname" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-previousnames" class="field-label">Previous Names</label>
<input name="apply-previousnames" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-agesept1st" class="field-label">Age at 1st September</label>
<input name="apply-agesept1st" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-dob" class="field-label">Date of Birth</label>
<input name="apply-dob" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-address" class="field-label">Address</label>
<input name="apply-address" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-postcode" class="field-label">Postcode</label>
<input name="apply-postcode" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-hometel" class="field-label">Home Telephone</label>
<input name="apply-hometel" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-mobile" class="field-label">Mobile Telephone</label>
<input name="apply-mobile" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-email" class="field-label">Email Address</label>
<input name="apply-email" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-gender" class="field-label">Gender</label>
<input name="apply-gender" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-nationality" class="field-label">Nationality</label>
<input name="apply-nationality" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-outsideeea" class="field-label">Have you ever lived outside the EEA?</label>
<input name="apply-outsideeea" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-outsideeeadates" class="field-label">Dates lived outside the EEA</label>
<input name="apply-outsideeeadates" type="text" placeholder="">
</div>
</li>
<li class="field-750">
<div class="field">
<label for="apply-medical" class="field-label">XYZ is committed to supporting all of our students. If you have a disability, medical condition or learning difficulty (such as dyslexia, Asperger's, etc) please state</label>
<input name="apply-medical" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-sen" class="field-label">Do you have a SEN statement or S139a?</label>
<input name="apply-sen" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-ethnic" class="field-label">What is your Ethnic background?</label>
<input name="apply-ethnic" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-predictedgrades" class="field-label">What are your predicted grades?</label>
<input name="apply-predictedgrades" type="text" placeholder="">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-coursechoice" class="field-label">At this stage, are you fairly sure which course you wish to take at XYZ?</label>
<input name="apply-coursechoice" type="text" placeholder="">
</div>
</li>
<li class="field-750">
<div class="field">
<label for="apply-asa2" class="field-label">AS/A2 levels</label>
<input name="apply-asa2" type="text" placeholder="In order of preference, please list a minimum of four subjects you are considering taking">
</div>
</li>
<li class="field-750">
<div class="field">
<label for="apply-voc" class="field-label">Vocational</label>
<input name="apply-voc" type="text" placeholder="Please state the exact title as it appears in the prospectus, for example Travel and Tourism BTEC Level 1 Diploma">
</div>
</li>
<li class="field-375">
<div class="field">
<label for="apply-nocourse" class="field-label">If you have answered no, please list the courses below you may be considering</label>
<input name="apply-nocourse" type="text" placeholder="">
</div>
</li>
<li class="field-750">
<div class="field">
<label for="apply-career" class="field-label">Do you have any career ideas? If so, what are they?</label>
<input name="apply-career" type="text" placeholder="">
</div>
</li>
<li class="field-750">
<div class="field">
<label for="apply-other" class="field-label">Other relevant information that you feel may assist us with helping you make the right course decision</label>
<input name="apply-other" type="text" placeholder="i.e work experience, part-time employment, voluntary work">
</div>
</li>
</ul>
</div>
<div class="loader"></div>
<div class="module-messages">
<ul id="contact-messages">
</ul>
</div>
<div class="module-button"><a id="apply-submit">Apply</a></div>
</form>
</div>
PHP:
<?php
// Receiving variables
#$surname = htmlspecialchars($_POST['apply-surname']);
#$firstname = htmlspecialchars($_POST['apply-firstname']);
#$previousnames = htmlspecialchars($_POST['apply-previousnames']);
#$agesept1st = htmlspecialchars($_POST['apply-agesept1st']);
#$dob = htmlspecialchars($_POST['apply-dob']);
#$homeaddress = htmlspecialchars($_POST['apply-address']);
#$postcode = htmlspecialchars($_POST['apply-postcode']);
#$hometel = htmlspecialchars($_POST['apply-hometel']);
#$mobile = htmlspecialchars($_POST['apply-mobile']);
#$email = htmlspecialchars($_POST['apply-email']);
#$gender = htmlspecialchars($_POST['apply-gender']);
#$uln = htmlspecialchars($_POST['apply-uln']);
#$nationality = htmlspecialchars($_POST['apply-nationality']);
#$oustideeea = htmlspecialchars($_POST['apply-outsideeea']);
#$outsideeeadates = htmlspecialchars($_POST['apply-outsideeeadates']);
#$secondaryschools = htmlspecialchars($_POST['apply-secondaryschools']);
#$medical = htmlspecialchars($_POST['apply-medical']);
#$sen = htmlspecialchars($_POST['apply-sen']);
#$ethnic = htmlspecialchars($_POST['apply-ethnic']);
#$predictedgrades = htmlspecialchars($_POST['apply-predictedgrades']);
#$coursechoice = htmlspecialchars($_POST['apply-coursechoice']);
#$asa2 = htmlspecialchars($_POST['apply-asa2']);
#$voc = htmlspecialchars($_POST['apply-voc']);
#$nocourse = htmlspecialchars($_POST['apply-nocourse']);
#$career = htmlspecialchars($_POST['apply-career']);
#$other = htmlspecialchars($_POST['apply-other']);
//Sending Email to form owner
# Email to Owner
$pfw_header = "From: $email";
$pfw_subject = "Application Form";
$pfw_email_to = "XXX#example.com";
$pfw_message = "Surname: $surname\n"
. "First Name: $firstname\n"
. "Previous Name: $previousnames\n"
. "Age at 1st Sept: $age1stsept\n"
. "Date of Birth: $dob\n"
. "Home Address: $address\n"
. "Postcode: $postcode\n"
. "Home Telephone: $hometel\n"
. "Mobile no: $mobile\n"
. "Email address: $email\n"
. "Gender: $gender\n"
. "ULN: $uln\n"
. "Nationality: $nationality\n"
. "Lived outside EEA: $outsideeea\n"
. "Dates lived outside EEA: $outsideeeadates\n"
. "Secondary school: $secondaryschools\n"
. "Medical issues: $medical\n"
. "SEN: $SEN\n"
. "Ethnic: $ethnic\n"
. "Predicted Grades: $predictedgrades\n"
. "Course choice: $coursechoice\n"
. "AS/A2 choice: $asa2\n"
. "Vocational choice: $voc\n"
. "No course choice: $postcode\n"
. "Career: $career\n"
. "Other info: $other\n"
;
#mail($pfw_email_to, $pfw_subject ,$pfw_message ,$pfw_header ) ;
echo('<li class="message-success">Your Application form has been received</li>');
?>
JavaScript:
// Application form submit
$("#apply-submit").click(function () {
$('form[name=application]').submit();
$("#application").find('.loader').fadeIn();
});
$('form[name=application]').submit(function () {
wcFormAction = $("#application").attr('action');
$.post(wcFormAction, $('form[name=application]').serialize(), function (data) {
$("#application").find('.loader').fadeOut();
});
return false;
});
Edit: I didn't create the original code, i'm just experimenting with this code as a template for a form. I've not had to look at submitting forms before, sorry if my question is off the mark slightly, if I can provide any more information please ask!
PHP code seems alright even with those unneccessary #'s.
And Javascript code you are using should work just fine, tried and worked on jsfiddle.
You must address what causing the problem, to do this, write down every step and tool you are using and check them, even the most basic ones. Like;
Are you sure,
you are including jQuery properly?
your ajax request is handled properly? (check if you are getting any responses)
and so on...

Categories