Load Bootstrap nav nav-tabs via GET URL - javascript

I have set up Bootstraps nav-tabs via an index page. Each tab loads a seperate PHP file via AJAX:
<div class="container">
<ul class="nav nav-tabs" id="indextabs">
<li>NOTES</li>
<li>WHOIS</li>
<li>DIG</li>
<li>ETS</li>
<li>RESOURCES</li>
</ul>
</div>
JavaScript that takes care of the AJAX queries:
window.onload = function() {
$('[data-toggle="tabchange"]').click(function(e) {
var $this = $(this),
loadurl = $this.attr('href'),
targ = $this.attr('data-target');
$.get(loadurl, function(data) {
$(targ).html(data);
});
$this.tab('show');
return false;
});
}
This itself works fine. In some of the tabs, however, there is an input that requires a domain name which then needs to be submitted via a GET request so that the URL can be something like:
http://domain.com/?domain=google.com&record=mx
With this in mind, I have two problems:
How do I load a particular tab using a GET method URL?
How do I submit form data via AJAX using the GET method and have it change the URL AND load the content in the tab-panel divs?

Please consider the following more like a comment because I'm uncertain what's optimal (and also works) in your case. Anyway I think you need to pass query parameters in your $get method call, either in form of a object, key value pairs { domain: 'google.com', record: 'mx'} or as string. Below an object/key value pairs are used.
window.onload = function() {
$('[data-toggle="tabchange"]').click(function(e) {
var $this = $(this),
loadurl = $this.attr('href'),
targ = $this.attr('data-target');
//optional method call below, uncomment if needed
//loadurl = getDomainURL() + "/" + loadurl
$.get(loadurl, {
domain: 'google.com',
record: 'mx'
},
function(data) {
$(targ).html(data);
});
$this.tab('show');
return false;
});
}
//returns domain name: www.example.com in form of http://example.com
// or domain name: http://example.com is returned as it is, unchanged http://example.com
function getDomainURL() {
var index = window.location.hostname.indexOf("www.");
if (index === 0)
return "http://" + window.location.hostname.substr((index + 4));
else
return "http://" + window.location.hostname;
}

Related

Django ajax jQuery autocomplete only works on one page

I've added a working search field to a navigation bar that use jQuery autocomplete. The problem is it only works on the main page. On the other pages it tries to add the source url to the end of the page url.
For instance, on the home page it points to ajax_call/search, but on a company page (it's app that gathers internal data on companies) it points to company/847/ajax_call/search and obviously fails.
What do I need to do so the jQuery autocomplete functionality works across the entire site (without rewriting it in every template)?
Template
$(function() {
$("#tags").autocomplete({
minLength:2,
source: "ajax_call/search/",
select: function(event, ui){
window.location.href = ui.item.href;
}
});
});
URL
url(r'^ajax_call/search/$', views.ajax_company_search, name='search-field'),
View
def ajax_company_search(request):
if request.is_ajax():
query = request.GET.get('term', '')
company_names = Company.objects.filter(company_name__icontains=query).values('company_name', 'pk')
results = []
for name in company_names:
name_json = dict()
name_json['label'] = name['company_name']
name_json['value'] = name['company_name']
name_json['href'] = "company/" + str(name['pk']) + "/"
results.append(name_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
You specified a relative URL in your JavaScript function. That's why it changes when you visit another page (with a different URL). In this case you want to use an absolute URL, like this: /ajax_call/search/.
Also, it is best practice to not hard-code your URLs in templates but to use reverse resolution:
$(function() {
$("#tags").autocomplete({
minLength:2,
source: {% url 'search-field' %},
select: function(event, ui){
window.location.href = ui.item.href;
}
});
});

Assigning javascript variable to java variable

I know I can't use javascript variable inside java code so can anyone explain me what I can do instead?
function init(srcc) {
<%if (session.getAttribute("status") != null && session.getAttribute("status").equals("member")) {%>
alert(srcc + " ");
<%application.setAttribute(session.getAttribute("currentuser"), srcc);%>
<%}%>
in this line:
<%application.setAttribute(session.getAttribute("currentuser"), srcc);%>
I can't read the srcc variable as it's assigned in javascript, this function called when I press a button in jquery, code:
var $lightbox = $("<div class='lightbox'></div>");
var $img = $("<img>");
var $caption = $("<p class='caption'></p>");
var $btn = $("<div align='center'> <INPUT TYPE='BUTTON' VALUE='Add to cart'></div>");
$lightbox.append($img).append($caption).append($btn);
$('body').append($lightbox);
$('.gallery li').click(function(e) {
e.preventDefault();
var src = $(this).children('img').attr("src");
var cap = $(this).children('img').attr("alt");
$btn.off('click').on('click', function(da) {
$(document).ready(function() {
init(src);
});
});
$img.attr('src', src);
$caption.text(cap);
$lightbox.fadeIn('fast');
$lightbox.click(function() {
$lightbox.fadeOut('fast');
});
});
I use it in an "add to cart" button, I want the server to keep data of whom added it to the cart and what he added. (srcc equals what he added and session.getAttribute("currentuser") is whom added).
Thanks guys.
You can send that JavaScript variable to Java using an AJAX request
You would have to have a serverside route set up to handle this request coming in and process the sent data.
Since I already see jQuery being used in your code, I'll use this AJAX function in my example code. You can send an HTTP request without your browser reloading the page in this way:
$.get("/urlOfCartHandler/?parameterName=" + javaScriptVariableContainingDataYouWantToSend, function(data) {
//Request was a success
}).fail(function() {
//Request failed
});

problems displaying page, deleting contents and repopulating - could this be multiple binding?

I have a mobile app.
It consists of 2 screens. The first is for capturing user
credentials and the 2nd is for displaying data.
The idea is to collect the credentials on screen 1.
Then make an ajax call with the credentials to get data and present it on
screen 2 as a series of links.
Then allow the user to touch a link on screen 2. This will return the link data to the javascript and pass it to the ajax call and get more data - THEN delete all the data on screen 2 and repopulate it with the new data.
First thing I want to find out: is showing a page with mobile.changePage(), populating it, deleting the contents and then repopulating it (without another call to mobile.changePage()) a reasonable thing to do?
I'm having a problem and I think its related to how I'm using onclick in the <a>
Each time I display the most recently received data, I want to display it in an <a>. I write each onclick to call the getData routine passing it information to determine the next ajax AND whatever is being displayed in the <a>. The only way I could figure out to access that was in onclick.
Is there a better way?
I'm able to display the results of the first ajax call just fine. But things get weird with the 2nd, 3rd etc.
Sometimes I'll touch a link and I'll progress thru the screens as I expect.
Sometimes I'll touch an <a> on the 1st result screen, the 2nd result screen will display and then (without me selecting data from the 2nd screen) the 3rd screen will display.
I've looked at the logs and the getData() routine is being executed.
What could be causing this? Am I somehow not destroying all the <a> properly? Am I using onclick in a fashion its not designed for? Should I be using buttons styled to look like links instead of <a>
Here's my code:
"use strict";
var app = {
onDeviceReady: function() {
$('#startButton').click(function(){
app.getDeptsForUser();
});
},
getDeptsForUser: function(){
var parms = new Object();
parms.userName = assignedUser;
app.getData(JSON.stringify(parms),"ENDPOINT1", "Departments");
$.mobile.changePage("#index", { transition: 'slide' });
},
getData: function(paramStr, endpoint, displayHeader){
var paramStrObj = JSON.parse(paramStr);
var serverName = server + ":" + port;
var encoded = Base64().encode(paramStrObj.userName + ':' + pass);
var authType = 'Basic ' + encoded;
var option = endpoint+"?action=start&params=" + paramStr;
var URL = serverName + "/rest/bpm/wle/v1/service/"+option;
$.ajax({
url: URL,
type: "POST",
crossDomain: true,
jsonp: "callback",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", authType);
},
success: function (result) {
console.log("MobileMockUp getData() ajax success result="+JSON.stringify(result));
if (endpoint === "ENDPOINT1"){
app.displayData(paramStr, endpoint,"Departments", result.data.data.depts.items);
}
else if (endpoint === "ENDPOINT2"){
app.displayData(paramStr, endpoint,displayHeader, result.data.data.checklists.items);
}
else if (endpoint === "ENDPOINT3"){
app.displayData(paramStr, endpoint,displayHeader, result.data.data.checks.items);
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Unable to retrieve '+displayHeader);
},
});
},
displayData: function(currParms,currEndPt, headerText, list){
var nextEndpt;
var nextHeaderText;
var currParmsObj = JSON.parse(currParms);
if (currEndPt === "MD#getDeptsForUser"){
nextEndpt = "MD#getCheckLists";
nextHeaderText = "Check Lists";
}
else if (currEndPt === "MD#getCheckLists"){
nextEndpt = "MD#getChecks";
}
var htmlListString="";
var parmObj;
var newLink;
$('#headerText').text(headerText);
for (var i = 0; i < list.length; i++){
parmObj = new Object();
if (currEndPt === "ENDPOINT1"){
parmObj.userName=currParmsObj.userName;
parmObj.dept=list[i];
}
else if (currEndPt === "ENDPOINT2"){
parmObj.userName=currParmsObj.userName;
parmObj.dept=currParmsObj.dept;
parmObj.checklist=list[i];
}
else if (currEndPt === "ENDPOINT3"){
nextHeaderText = list[i];
}
var str = JSON.stringify(parmObj);
str = str.toString().replace(/"/g, '\\"');
newLink = "<a style='background:#ffffff;padding-top:5%;border-top: thin solid black; display:block;font-size:12px;font-weight:normal;color:#000000;text-decoration: none;' href='#' onclick='app.getData(\""+str+"\",\""+nextEndpt+"\",\""+nextHeaderText+"\")'><pre>" + list[i] + " </pre></a><br>";
htmlListString=htmlListString+newLink;
}
$('#taskListUL').empty();
$('#taskListUL').append(htmlListString);
}
};
Could this be multiple binding?
i figured out it was multiple bindings

jQuery cookie plugin - save and call parsetInt() values

I'm new to JS. I have a script which should count clicks and store clicks number value in cookie. The problem is I can't correctly save and call clicks number(generated by parseInt) value from cookies.
Here is the code http://jsfiddle.net/csTpG/99/ (using jquery.cookie plugin)
$('#counter').click(function() {
var productID = $(this).attr('name');
var $this = $(this);
$.get('/', {
item_id: productID
}, function(response) {
if (response) {
if (response == 'empty')
$this.text('Count');
else
$this.text('Count (' + parseInt(response) + ')');
$.cookie('clicked-counter', 'true');
}
});
return false;
});
if ($.cookie('clicked-counter') == 'true') {
var cookie = $.cookie('clicked-counter');
$('#counter a').text('Count (' + cookie + ')');
};
#counter{background-color:white}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="counter">Counter</button>
Yup parseInt() shows NaN.
I updated your script to make it work (i included jQuery.cookie plugin for example) , look here http://jsfiddle.net/nicolapeluchetti/csTpG/100/ but there are still some issues. You get NaN when you do a parseInt because you are trying to parse an html page that returns from your ajax call. What are you trying to do?

How to check if page exists using JavaScript

I have a link: Hello.
When someone clicks the link I'd like to check via JavaScript if the page the href-attribute points to exists or not. If the page exists the browser redirects to that page ("www.example.com" in this example) but if the page doesn't exist the browser should redirect to another URL.
It depends on whether the page exists on the same domain or not. If you're trying to determine if a page on an external domain exists, it won't work – browser security prevents cross-domain calls (the same-origin policy).
If it is on the same domain however, you can use jQuery like Buh Buh suggested. Although I'd recommend doing a HEAD-request instead of the GET-request the default $.ajax() method does – the $.ajax() method will download the entire page. Doing a HEAD request will only return the headers and indicate whether the page exists (response codes 200 - 299) or not (response codes 400 - 499). Example:
$.ajax({
type: 'HEAD',
url: 'http://yoursite.com/page.html',
success: function() {
// page exists
},
error: function() {
// page does not exist
}
});
See also: http://api.jquery.com/jQuery.ajax/
A pretty good work around is to proxy. If you don't have access to a server side you can use YQL. Visit: http://developer.yahoo.com/yql/console/
From there you can do something like: select * from htmlstring where url="http://google.com". You can use the "REST query" they have on that page as a starting point for your code.
Here's some code that would accept a full URL and use YQL to detect if that page exists:
function isURLReal(fullyQualifiedURL) {
var URL = encodeURIComponent(fullyQualifiedURL),
dfd = $.Deferred(),
checkURLPromise = $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D%22' + URL + '%22&format=json');
checkURLPromise
.done(function(response) {
// results should be null if the page 404s or the domain doesn't work
if (response.query.results) {
dfd.resolve(true);
} else {
dfd.reject(false);
}
})
.fail(function() {
dfd.reject('failed');
});
return dfd.promise();
}
// usage
isURLReal('http://google.com')
.done(function(result) {
// yes, or request succeded
})
.fail(function(result) {
// no, or request failed
});
Update August 2nd, 2017
It looks like Yahoo deprecated "select * from html", although "select * from htmlstring" does work.
Based on the documentation for XMLHttpRequest:
function returnStatus(req, status) {
//console.log(req);
if(status == 200) {
console.log("The url is available");
// send an event
}
else {
console.log("The url returned status code " + status);
// send a different event
}
}
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this, this.status);
}
client.open("HEAD", address);
client.send();
}
fetchStatus("/");
This will however only work for URLs within the same domain as the current URL. Do you want to be able to ping external services? If so, you could create a simple script on the server which does your job for you, and use javascript to call it.
If it is in the same domain, you can make a head request with the xmlhttprequest object [ajax] and check the status code.
If it is in another domain, make an xmlhttprequest to the server and have it make the call to see if it is up.
why not just create a custom 404 handler on the web server? this is probably the more "good-bear" way to do this.
$.ajax({
url: "http://something/whatever.docx",
method: "HEAD",
statusCode: {
404: function () {
alert('not found');
},
200: function() {
alert("foundfile exists");
}
}
});
If you are happy to use jQuery you could do something like this.
When the page loads make an ajax call for each link. Then just replace the href of all the links which fail.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
<!--
$.fn.checkPageExists = function(defaultUrl){
$.each(this, function(){
var $link = $(this);
$.ajax({
url: $link.attr("href"),
error: function(){
$link.attr("href", defaultUrl);
}
});
});
};
$(document).ready(function(){
$("a").checkPageExists("default.html");
});
//-->
</script>
You won't be able to use an ajax call to ping the website because of same-origin policy.
The best way to do it is to use an image and if you know the website you are calling has a favicon or some sort of icon to grab, you can just use an html image tag and use the onerror event.
Example:
function pingImgOnWebsite(url) {
var img = document.createElement('img');
img.style.visibility = 'hidden';
img.style.position = 'fixed';
img.src = url;
img.onerror = continueBtn; // What to do on error function
document.body.appendChild(img);
}
Another way to do this is is with PHP.
You could add
<?php
if (file_exists('/index.php'))
{
$url = '/index.php';
} else {
$url = '/notindex.php';
}
?>
And then
<a href="<?php echo $url; ?>Link</a>

Categories