both jQuery and $ is not a function - javascript

I already imported
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
under the head section. But still I got,
RelatedObjectLookups.js:142 Uncaught TypeError: $ is not a function
at RelatedObjectLookups.js:142
at RelatedObjectLookups.js:175
(anonymous) # RelatedObjectLookups.js:142
(anonymous) # RelatedObjectLookups.js:175
(index):177 Uncaught TypeError: $ is not a function
at (index):177
Relavant html looks like,
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script crossorigin="anonymous" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link crossorigin="anonymous" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" rel="stylesheet">
</head>
<body>
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="/static/admin/js/core.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"> </script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
<script type="text/javascript" src="/static/admin/js/actions.min.js"></script>
<script type="text/javascript" src="/static/admin/js/calendar.js"></script>
<script type="text/javascript" src="/static/admin/js/admin/DateTimeShortcuts.js"></script>
{{form.media}}
<div class="row">
<div class="col-6">
<form method="post" id="extendTrialForm" class="form">
{% csrf_token %}
{% bootstrap_field form.user %}
{% bootstrap_field form.core_instance %}
{% bootstrap_field form.expiry_datetime %}
{% buttons %}
<button type="submit" class="btn btn-primary">Submit</button>
{% endbuttons %}
</form>
</div>
</div>
<script>
$( document ).ready(function() { // line no 177
Removing the script tags above {{form.media}} won't throw any error related to jquery but it misses the widget functionality. I need that script tags but I don't want Jquery to return $ is not a function. I have tried adding $.noconflict, jQuery(document).ready but nothing works.
RelatedObjectsLookups.js
/*global SelectBox, interpolate*/
// Handles related-objects functionality: lookup link for raw_id_fields
// and Add Another links.
(function($) {
'use strict';
// IE doesn't accept periods or dashes in the window name, but the element IDs
// we use to generate popup window names may contain them, therefore we map them
// to allowed characters in a reversible way so that we can locate the correct
// element when the popup window is dismissed.
function id_to_windowname(text) {
text = text.replace(/\./g, '__dot__');
text = text.replace(/\-/g, '__dash__');
return text;
}
function windowname_to_id(text) {
text = text.replace(/__dot__/g, '.');
text = text.replace(/__dash__/g, '-');
return text;
}
function showAdminPopup(triggeringLink, name_regexp, add_popup) {
var name = triggeringLink.id.replace(name_regexp, '');
name = id_to_windowname(name);
var href = triggeringLink.href;
if (add_popup) {
if (href.indexOf('?') === -1) {
href += '?_popup=1';
} else {
href += '&_popup=1';
}
}
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
function showRelatedObjectLookupPopup(triggeringLink) {
return showAdminPopup(triggeringLink, /^lookup_/, true);
}
function dismissRelatedLookupPopup(win, chosenId) {
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem.className.indexOf('vManyToManyRawIdAdminField') !== -1 && elem.value) {
elem.value += ',' + chosenId;
} else {
document.getElementById(name).value = chosenId;
}
win.close();
}
function showRelatedObjectPopup(triggeringLink) {
return showAdminPopup(triggeringLink, /^(change|add|delete)_/, false);
}
function updateRelatedObjectLinks(triggeringLink) {
var $this = $(triggeringLink);
var siblings = $this.nextAll('.change-related, .delete-related');
if (!siblings.length) {
return;
}
var value = $this.val();
if (value) {
siblings.each(function() {
var elm = $(this);
elm.attr('href', elm.attr('data-href-template').replace('__fk__', value));
});
} else {
siblings.removeAttr('href');
}
}
function dismissAddRelatedObjectPopup(win, newId, newRepr) {
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
var elemName = elem.nodeName.toUpperCase();
if (elemName === 'SELECT') {
elem.options[elem.options.length] = new Option(newRepr, newId, true, true);
} else if (elemName === 'INPUT') {
if (elem.className.indexOf('vManyToManyRawIdAdminField') !== -1 && elem.value) {
elem.value += ',' + newId;
} else {
elem.value = newId;
}
}
// Trigger a change event to update related links if required.
$(elem).trigger('change');
} else {
var toId = name + "_to";
var o = new Option(newRepr, newId);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
win.close();
}
function dismissChangeRelatedObjectPopup(win, objId, newRepr, newId) {
var id = windowname_to_id(win.name).replace(/^edit_/, '');
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]);
var selects = $(selectsSelector);
selects.find('option').each(function() {
if (this.value === objId) {
this.textContent = newRepr;
this.value = newId;
}
});
win.close();
}
function dismissDeleteRelatedObjectPopup(win, objId) {
var id = windowname_to_id(win.name).replace(/^delete_/, '');
var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]);
var selects = $(selectsSelector);
selects.find('option').each(function() {
if (this.value === objId) {
$(this).remove();
}
}).trigger('change');
win.close();
}
// Global for testing purposes
window.id_to_windowname = id_to_windowname;
window.windowname_to_id = windowname_to_id;
window.showRelatedObjectLookupPopup = showRelatedObjectLookupPopup;
window.dismissRelatedLookupPopup = dismissRelatedLookupPopup;
window.showRelatedObjectPopup = showRelatedObjectPopup;
window.updateRelatedObjectLinks = updateRelatedObjectLinks;
window.dismissAddRelatedObjectPopup = dismissAddRelatedObjectPopup;
window.dismissChangeRelatedObjectPopup = dismissChangeRelatedObjectPopup;
window.dismissDeleteRelatedObjectPopup = dismissDeleteRelatedObjectPopup;
// Kept for backward compatibility
window.showAddAnotherPopup = showRelatedObjectPopup;
window.dismissAddAnotherPopup = dismissAddRelatedObjectPopup;
$(document).ready(function() {
$("a[data-popup-opener]").click(function(event) {
event.preventDefault();
opener.dismissRelatedLookupPopup(window, $(this).data("popup-opener"));
});
$('body').on('click', '.related-widget-wrapper-link', function(e) {
e.preventDefault();
if (this.href) {
var event = $.Event('django:show-related', {href: this.href});
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
showRelatedObjectPopup(this);
}
}
});
$('body').on('change', '.related-widget-wrapper select', function(e) {
var event = $.Event('django:update-related');
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
updateRelatedObjectLinks(this);
}
});
$('.related-widget-wrapper select').trigger('change');
$('body').on('click', '.related-lookup', function(e) {
e.preventDefault();
var event = $.Event('django:lookup-related');
$(this).trigger(event);
if (!event.isDefaultPrevented()) {
showRelatedObjectLookupPopup(this);
}
});
});
})(django.jQuery);

I’m pretty sure your whole problem is that the very end of your RelatedObjectsLookups.js JS file says django.jQuery, which doesn’t exist (or at least, the googleapis jQuery file you’re loading in isn’t going to define that). Change it to window.jQuery and things should work for you.
EDIT based on your reply
Since you can’t change the line that says django.jQuery, then let’s define that.
Right after you include your jQuery file, add the following tag.
<script>
django = django || {};
django.jQuery = django.jQuery || jQuery;
</script>
This will set django.jQuery to jQuery (which is included by your googleapis file), if it’s not been set yet. Now it will exist for your later scripts to use.

Related

How to load search data on load?

I received this code from another user in this forum.
Issue: As seen in the below screenshot, the search results (or data) starts to appear when you click or start typing in the search box or else only the search box loads without the data.
Requirement: I want to display the results (or data) as the page loads.
The code is given below
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
   
<style>
.nav-link {
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<ul class="nav nav-tabs">
<li class="nav-item">
<div class="nav-link"id="search-link">Search</div>
</li>
</ul>
<div id="app"></div>
<!-- Content here -->
</div>
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script>
var data;
function loadView(options){
var id = typeof options.id === "undefined" ? "app" : options.id;
var cb = typeof options.callback === "undefined" ? function(){} : options.callback;
google.script.run.withSuccessHandler(function(html){
document.getElementById("app").innerHTML = html;
typeof options.params === "undefined" ? cb() : cb(options.params);
})[options.func]();
}
function setDataForSearch(){
google.script.run.withSuccessHandler(function(dataReturned){
data = dataReturned.slice();
}).getDataForSearch();
}
function search(){
var searchinput = document.getElementById("searchinput").value.toString().toLowerCase().trim();
var searchWords = searchinput.split(/\s+/);
var searchColumns = [0,1,2,3,4,5,6,7];
// and or
var resultsArray = data.filter(function(r){
return searchWords.every(function(word){
return searchColumns.some(function(colIndex){
return r[colIndex].toString().toLowerCase().indexOf(word) !== -1
});
});
});
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function(r){
var tr = template.cloneNode(true);
var hinmokuColumn = tr.querySelector(".hinmoku");
var buhinCodeuColumn = tr.querySelector(".buhinCode");
var buhinNameColumn = tr.querySelector(".buhinName");
var hitsuyoColumn = tr.querySelector(".hitsuyo");
var genkaColumn = tr.querySelector(".genka");
var kobaiColumn = tr.querySelector(".kobai");
var sagakuColumn = tr.querySelector(".sagaku");
var kenshoColumn = tr.querySelector(".kensho");
hinmokuColumn.textContent = r[0];
buhinCodeuColumn.textContent = r[1];
buhinNameColumn.textContent = r[2];
hitsuyoColumn.textContent = r[3];
genkaColumn.textContent = r[4];
kobaiColumn.textContent = r[5];
sagakuColumn.textContent = r[6];
kenshoColumn.textContent = r[7];
searchResultsBox.appendChild(tr);
});
}
function loadSearchView(){
loadView({func:"loadSearchView", callback: setDataForSearch});
}
window.addEventListener("load", loadSearchView);
function inputEventHandler(e){
if (e.target.matches("#searchinput")){
search();
}
}
document.getElementById("app").addEventListener("input",inputEventHandler);
document.getElementById("app").addEventListener("click",inputEventHandler);
</script>
</body>
</html>
server-side code
function getDataForSearch(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("TableData");
return ws.getRange(2, 1, ws.getLastRow(),8).getValues();
}
I need to know what modification needs to be done in the code?
I tried document.getElementById("app").addEventListener("load",inputEventHandler);
but it didn't work.
is there any other event listeners available that will load the search results (or data) (without taking any action on the site, i mean without clicking or typing in the search box)?
Thanks in advance.
Edit: loadsearchview function file code
function loadSearchView(){
return loadPartialHTML_("search");
}
You could use addEventListener with DOMContentLoaded to call a function when all the HTML is loaded and the DOM tree is built. For your particular situation, here's how I managed:
First I need to load data into data variable and call the loadSearchView() function when the page loads:
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", function () {
google.script.run.withSuccessHandler(function (r) {
data = r;
loadSearchView();
}).getDataForSearch();
});
} else {
google.script.run.withSuccessHandler(function (r) {
data = r;
loadSearchView();
}).getDataForSearch();
}
Then I need to load the search view, but instead of calling setDataForSearch, I implemented another function to call functions after this view is loaded. This might be useful if you want to call more than one function after the searchView loads. So basically the code would be like this:
function loadSearchView() {
loadView({ func: "loadSearchView", callback: afterSearchViewLoads });
}
function afterSearchViewLoads(){
loadDataWhenPageLoads();
}
function loadDataWhenPageLoads(){
var resultArray = data;
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function (r) {
var tr = template.cloneNode(true);
var hinmokuColumn = tr.querySelector(".hinmoku");
var buhinCodeuColumn = tr.querySelector(".buhinCode");
var buhinNameColumn = tr.querySelector(".buhinName");
var hitsuyoColumn = tr.querySelector(".hitsuyo");
var genkaColumn = tr.querySelector(".genka");
var kobaiColumn = tr.querySelector(".kobai");
var sagakuColumn = tr.querySelector(".sagaku");
var kenshoColumn = tr.querySelector(".kensho");
hinmokuColumn.textContent = r[0];
buhinCodeuColumn.textContent = r[1];
buhinNameColumn.textContent = r[2];
hitsuyoColumn.textContent = r[3];
genkaColumn.textContent = r[4];
kobaiColumn.textContent = r[5];
sagakuColumn.textContent = r[6];
kenshoColumn.textContent = r[7];
searchResultsBox.appendChild(tr);
});
}
Hope this can solve your problem!
AddEventListener when you click enter key in keyboard will help you. Link: EventListener Enter Key
Also addEventListener "change" will help you.
edit
If you want your data to load when page is loaded use one of those ways:
window.onload = function() {
Search();
} // way one
window.onload = Search(); //way two
<body onclick="Search()"> // way three

My JS to retrieve querystring params isn't working, any ideas why?

I'm trying to get a simple example of using js to retrieve querystring params working and it's not (even though I said simple).
Here's my code:
I've tried putting alert statements in and debugging the old fashioned way but to be honest I'm used to using VS2017 for c# not js
Here's the code I'm using.
I have 2 html pages, the first just has a link:
try me
The second has the code:
this is some text <br />
<script> getparams2();</script>
this is some more text <br />
<script>
function getUrlParam(parameter, defaultvalue) {
var urlparameter = defaultvalue;
if (window.location.href.indexOf(parameter) > -1) {
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
</script>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
alert(value);
vars[key] = value;
});
return vars;
}
</script>
<script>
function getparams2()
{
var mytext = getUrlVars()["type"];
}
</script>
The result I'm trying to acheive is that the h1.html page can display the type parameter from the url.
Thanks in advance,
Paul.
Your code works. You just need to execute it when the document is ready also you need to return something or update your page to see the results.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<div id="params"> Printing The URL Params here</div>
<script type="text/javascript">
$( document ).ready(function() {
getparams2();
function getUrlParam(parameter, defaultvalue) {
var urlparameter = defaultvalue;
if (window.location.href.indexOf(parameter) > -1) {
urlparameter = getUrlVars()[parameter];
}
return urlparameter;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function
(m, key, value) {
alert(value);
vars[key] = value;
});
return vars;
}
function getparams2()
{
var mytext = getUrlVars()["type"];
//console.log(mytext);
$('#params').text(mytext);
}
});
</script>
</body>
</html>
I would do it the following way:
URL-Param function
function getUrlParam(name){
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) { return ""; }
else { return results[1]; }
};
Call from your getParams2
function getParams2(){
return getUrlParam('type');
};
getParams2 will return the value of the param if it is in the URL.

Select word next to symbol

I have jquery code on keypress 35 which is # to dropdown div. I need to get the word that is standing next to # e.g.
<textarea></textarea> And I type #Michael I want to store #Michael in var name
After making an ajax request to check if Michael exists in the database and if it does, echo it inside dropdown div. After what I click on some from the list and replace it with name and # before name like if I got result:
Michael Parker and click on this one to replace this one with name value.
I need to select word that is typed with #
[Q] how to select the word that is standing next to #?
Try this:
function getName(){
var t = document.getElementsByTagName('textarea')[0].value;
var name = t.split(' ');
name.forEach(function(str){
if(str[0] === '#') {
return str;
}
});
}
I used this for test
<textarea>asjdaksdjans #hacj asdasd</textarea>
<button onclick="getName()">find</button>
I hope this is what you wanted.
EDIT
function getName(){
var t = document.getElementsByTagName('textarea')[0].value;
if(t[t.length-1]=== ' '){
var name = t.split(' ');
name.forEach(function(str){
if(str[0] === '#') {
console.log(str);
}
});
}
}
For test:
<textarea onkeyup="getName()">asjdaksdjans #hacj asdasd</textarea>
EDIT
jQuery(function($){
$('textarea').on('keyup', function(event){
var text = $(this).val();
if(text[text.length-1]=== ' ') {
var name = text.split(' ');
$.each(name, function(i, str) {
console.log(i, str);
if(str[0] === "#") {
alert('name is:' +str);
}
});
}
});
});
This is working example. Note that you cannot 'getvalue' from event handler. But you can call action from that handler.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var capName = '';
var capStart = false;
$('#txt').keypress(function (e) {
if (e.key == '#') {
capStart = true;
capName = '';
}
if (capStart && /[a-z0-9_#-]/i.test(e.key)) {
capName += e.key;
}
if (capStart && !/[a-z0-9_#-]/i.test(e.key)) {
capStart = false;
doSomething(capName);
}
});
function doSomething(text) {
$('#result').html(capName);
}
});
</script>
</head>
<body>
<textarea id="txt"></textarea><br />
<div id="result"></div>
</body>
</html>

Fetch data from MySQL inside .js file [duplicate]

This question already has answers here:
connect AngularJS to mysql using my PHP service?
(2 answers)
Closed 8 years ago.
I am looking for a solution for almost 3 days but i can't figure it out. This is my problem:
I have file called: index.php
<html>
<head>
<title>AngularJS-FlowChart</title>
<!--
LiveReload support.
http://livereload.com/
-->
<script src="http://localhost:35729/livereload.js?snipver=1"></script>
</head>
<body
ng-app="app"
ng-controller="AppCtrl"
mouse-capture
ng-keydown="keyDown($event)"
ng-keyup="keyUp($event)"
>
<div style="width: 100%; overflow: hidden;">
<!--<div style="width: 600px; float: left;">
<textarea
style="width: 100%; height: 100%;"
chart-json-edit
view-model="chartViewModel"
>
</textarea>
</div>-->
<div style="margin-left: 0px;">
<button
ng-click="addNewNode()"
title="Add a new node to the chart"
>
Add Node
</button>
<button
ng-click="addNewInputConnector()"
ng-disabled="chartViewModel.getSelectedNodes().length == 0"
title="Add a new input connector to the selected node"
>
Add Input Connector
</button>
<button
ng-click="addNewOutputConnector()"
ng-disabled="chartViewModel.getSelectedNodes().length == 0"
title="Add a new output connector to the selected node"
>
Add Output Connector
</button>
<button
ng-click="deleteSelected()"
ng-disabled="chartViewModel.getSelectedNodes().length == 0 && chartViewModel.getSelectedConnections().length == 0"
title="Delete selected nodes and connections"
>
Delete Selected
</button>
<!--
This custom element defines the flowchart.
-->
<flow-chart
style="margin: 5px; width: 40%; height: 70%; float: right"
chart="chartViewModel"
>
</flow-chart>
<flow-chart
style="margin: 5px; width: 40%; height: 70%; float: left"
chart="chartViewModel"
>
</flow-chart>
</div>
</div>
<link rel="stylesheet" type="text/css" href="app.css">
<!-- Library code. -->
<script src="lib/jquery-2.0.2.js" type="text/javascript"></script>
<script src="lib/angular.js" type="text/javascript"></script>
<!-- Flowchart code. -->
<script src="debug.js" type="text/javascript"></script>
<script src="flowchart/svg_class.js" type="text/javascript"></script>
<script src="flowchart/mouse_capture_service.js" type="text/javascript"></script>
<script src="flowchart/dragging_service.js" type="text/javascript"></script>
<script src="flowchart/flowchart_viewmodel.js" type="text/javascript"></script>
<script src="flowchart/flowchart_directive.js" type="text/javascript"></script>
<!-- App code. -->
<script src="app.js" type="text/javascript"></script>
</body>
</html>
And I have another file called: app.js
//
// Define the 'app' module.
//
angular.module('app', ['flowChart', ])
//
// Simple service to create a prompt.
//
.factory('prompt', function () {
/* Uncomment the following to test that the prompt service is working as expected.
return function () {
return "Test!";
}
*/
// Return the browsers prompt function.
return prompt;
})
//
// Application controller.
//
.controller('AppCtrl', ['$scope', 'prompt', function AppCtrl ($scope, prompt) {
//
// Code for the delete key.
//
var deleteKeyCode = 46;
//
// Code for control key.
//
var ctrlKeyCode = 65;
//
// Set to true when the ctrl key is down.
//
var ctrlDown = false;
//
// Code for A key.
//
var aKeyCode = 17;
//
// Code for esc key.
//
var escKeyCode = 27;
//
// Selects the next node id.
//
var nextNodeID = 10;
//
// Setup the data-model for the chart.
//
var chartDataModel = {};
//
// Event handler for key-down on the flowchart.
//
$scope.keyDown = function (evt) {
if (evt.keyCode === ctrlKeyCode) {
ctrlDown = true;
evt.stopPropagation();
evt.preventDefault();
}
};
//
// Event handler for key-up on the flowchart.
//
$scope.keyUp = function (evt) {
if (evt.keyCode === deleteKeyCode) {
//
// Delete key.
//
$scope.chartViewModel.deleteSelected();
}
if (evt.keyCode == aKeyCode && ctrlDown) {
//
// Ctrl + A
//
$scope.chartViewModel.selectAll();
}
if (evt.keyCode == escKeyCode) {
// Escape.
$scope.chartViewModel.deselectAll();
}
if (evt.keyCode === ctrlKeyCode) {
ctrlDown = false;
evt.stopPropagation();
evt.preventDefault();
}
};
//
// Add a new node to the chart.
//
$scope.addNewNode = function () {
var nodeName = prompt("Enter new node!", "New node");
if (!nodeName) {
return;
}
//
// Template for a new node.
//
var newNodeDataModel = {
name: nodeName,
id: nextNodeID++,
x: 50,
y: 50
};
$scope.chartViewModel.addNode(newNodeDataModel);
};
//
// Add an input connector to selected nodes.
//
$scope.addNewInputConnector = function () {
var connectorName = prompt("Enter a connector name:");
if (confirm(connectorName)) {
var selectedNodes = $scope.chartViewModel.getSelectedNodes();
for (var i = 0; i < selectedNodes.length; ++i) {
var node = selectedNodes[i];
node.addInputConnector({
name: connectorName
});
}
} else return;
};
//
// Add an output connector to selected nodes.
//
$scope.addNewOutputConnector = function () {
var connectorName = prompt("Enter a connector name:");
if (confirm(connectorName)) {
var selectedNodes = $scope.chartViewModel.getSelectedNodes();
for (var i = 0; i < selectedNodes.length; ++i) {
var node = selectedNodes[i];
node.addOutputConnector({
name: connectorName,
});
}
} else return;
};
//
// Delete selected nodes and connections.
//
$scope.deleteSelected = function () {
$scope.chartViewModel.deleteSelected();
};
//
// Create the view-model for the chart and attach to the scope.
//
$scope.chartViewModel = new flowchart.ChartViewModel(chartDataModel);
}])
;
The thing I want to achieve is to read data from MySQL and use that same data inside app.js file. I'd really need any help please.
I was reading all articles about this thema on first 5 google pages but without any success. I tried all sorts of "tutorials" but i could find the solution.
Use jQuerys AJAX function to send data to a PHP Service:
$.ajax({
type: 'POST',
url: path + '/php/yourService.php',
data: 'var=' + var,
success: function (response) {
// Do smth with the response
}
});
In your PHP Service read out data of the database:
// connect to your database first
$username = $_POST["var"];
$sql="SELECT * FROM users WHERE anything = '$var'";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error());
}
while($row = mysql_fetch_array($result)){
return $row["variable"];
}
Should do the trick. Don´t matter if angular or not. The returned data is accessibly through the response variable in ajax onSuccess function. Hope this helps

Better code for checking Duplicate in String Array

I have following code for checking whether there is duplicate in an array. The code works fine. But it uses a new array named newUniqueArray. Is there a better code for this purpose without using a new array? Is there any optimization possible on this code?
Note: I have used inArray and in keywords from jQuery
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnSave').click(function (e) {
var reportRecipients = "A, a , b,";
reportRecipients = reportRecipients.toLowerCase();
checkDuplicate(reportRecipients);
});
function checkDuplicate(reportRecipients) {
if (reportRecipients.length > 1) {
var recipientsArray = reportRecipients.split(',');
var newUniqueArray = [];
for (a in recipientsArray) {
var email = $.trim(recipientsArray[a]);
if ($.inArray(email, newUniqueArray) == -1) {
newUniqueArray.push(email);
}
}
if (newUniqueArray.length < recipientsArray.length) {
alert('Duplicate Exists');
}
return false;
}
}
});
</script>
</head>
<body>
<input name="txtName" type="text" id="txtName" />
<input type="submit" name="btnSave" value="Save" id="btnSave" />
</body>
</html>
If you just want to test on string arrays, you can use a JavaScript object's property to test. It used a hash-table to look up properties, which is faster than array iteration.
example: http://jsfiddle.net/jmDEZ/8/
function checkDuplicate(reportRecipients) {
var recipientsArray = reportRecipients.split(','),
textHash = {};
for(var i=0; i<recipientsArray.length;i++){
var key = $.trim(recipientsArray[i].toLowerCase());
console.log("lower:" + key);
if(textHash[key]){
alert("duplicated:" + key);
return true;
}else{
textHash[key] = true;
}
}
alert("no duplicate");
return false;
}​
I can't see any reason to use jQuery for this purpose:
checkDuplicate = function (reportRecipients) {
if (reportRecipients.length > 1) {
var recipientsArray = reportRecipients.split(',');
for (a in recipientsArray) {
if(reportRecipients.indexOf(a) != reportRecipients.lastIndexOf(a)){
return true;
}
}
}
return false;
}
$('#btnSave').click(function (e) {
var reportRecipients = "A, a , b,";
reportRecipients = reportRecipients.toLowerCase();
if(checkDuplicate(reportRecipients)) alert('Duplicate Exists');
});

Categories

Resources