Defining default jQuery tab based on URL - javascript

I have a jQuery search script that uses tabs for the user to define the search type they want. A tab is selected as the default by using $('#type_search').click(); however this causes a problem when refreshing a results page. If a different search type is selected and then the page is refreshed, the default tab is automatically selected so it doesn't return the correct results even though the page URL says it is correct.
My question is, how can I define the default tab from the section in the URL if a query is active and if there is no active query use the default tab? I hope you can understand what I'm saying.
My jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
$('#type_search').click();
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
if (window.location.hash.indexOf('#' + type + '/') == 0) {
query = window.location.hash.replace('#' + type + '/', '').replace('/', '');
$('#query').val(decodeURIComponent(query)).keyup();
}
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});

Ah, I had that problem too. It's pretty simple. On page ready you just take the anchor from the URL and simulate a click.
$(document).ready(function() {
url = document.location.href.split('#');
$('#'+url[1]).click();
});

Related

Correct URL in ajax call JavaScript

I have a GET ajax call as follows :
var changeUrl = "changePriority?newValue=" + targetValue + "&justification=" + justification
if (dataInfo == "row") {
changeUrl += "&id=" + id
}
changeUrl += "&executedConfigId=" + executedConfigId + "&currUser=" + currentUser + "&productName=" + productName + "&eventName=" + eventName + "&alertDetails=" + JSON.stringify(alertArray);
//if the selected signal is not null then we show the product names
$.ajax({
url: changeUrl,
type: "GET",
success: function (data) {
for (var index = 0; index < checkedRowList.length; index++) {
var row = checkedRowList[index]
signal.list_utils.change_priority(row, targetValue);
}
$('#change-priority-modal').modal('hide');
if (applicationName == "Signal Management") {
signal.list_utils.set_value(parent_row, 'dueIn', id, signal.list_utils.get_due_in, applicationName);
$(parentField).html(targetValue);
}
location.reload();
},
error: function (exception) {
console.log(exception);
}
});
The value of changeUrl as I get in my browser's developer console is :
http://localhost:8080/signal/singleCaseAlert/changePriority?newValue=Medium&justification=test%20justification%20first.&id=6816&executedConfigId=6704&currUser=15&productName=Wonder%20Product&eventName=1.Pyrexia&alertDetails=[{%22alertId%22:%226816%22,%22event%22:%221.Pyrexia%22,%22currentUser%22:%2215%22}]
But I get a 400 bad request status and a http header parse error in the backend. Can someone help me resolve this?
On your JSON.stringify(alertArray) you'll need to also encodeURI();
encodeURI(JSON.stringify(alertArray));
A better solution would be send your JSON in the body of a POST request if thats feasible within your design

Code is not executing when i pass a parameter

I have the problem that my code is not performing the ajax call when i pass a search parameter. I added several console.log to my code! So that you i hope you can easily comprhened my code:
icd: function(icd,id,search){
if(!(typeof search === 'undefined')){
var urls = "icd?search=" + search;
console.log("1");
}else{
if(icd == 2){
var urls = "/icd/icd2/" + id;
}if(icd == 3){
var urls = "/icd/icd3/" + id;
}
console.log("2");
}
console.log("3");
$.ajax({
dataType: "json",
url: SERVER + urls,
headers: {"X-TOKEN": TOKEN},
success: function(data,status,xhr){
console.log("4");
var array = $.map(data['icd'], function (field, i) {
return '<tr data-link="'+ field.id +'"><td>' + field.nummer + '</td><td>' + field.bezeichnung + '</td></tr>';
});
$('#DiagnosenTable').html(array.join(''));
$('#side-panel2 .breadcrumb').html($('<li/>').html($('<a/>',{href: '#',text: 'Alle',click: function(){Diagnose.start()} })));
if(icd == 2){
$('#side-panel2 .breadcrumb').append($('<li/>', {class: 'active',text: data['icd1'].bezeichnung}));
}
if(icd == 3){
$('#side-panel2 .breadcrumb').append($('<li/>').html($('<a/>',{href: '#',text: data['icd1'].nummer,click: function(){Diagnose.icd(2,data['icd1'].id)} })));
$('#side-panel2 .breadcrumb').append($('<li/>', {class: 'active',text: data['icd2'].bezeichnung}));
}
$('#DiagnosenTable tbody').eq(0).children('tr').each(function(){
$(this).click(function(){
if(icd == 2){
Diagnose.icd('3',$(this).attr('data-link'));
}else{
$('#inputCode').val($(this).children('td')[0].innerHTML);
$('#inputBez').val($(this).children('td')[1].innerHTML);
$('#TextEntry').val($(this).children('td')[0].innerHTML);
}
});
});
},
error: function(xhr, status, error) {
ErrorHandler.connection(xhr,status,error);
console.log("5");
}
});
console.log("6");
}
When i first tried to execute my code, i noticed that when i pass a search parameter, the ajax call isnt performed (because 4 or 5 is not printed to the console)Here is a screenshot from my console:
I cant explain me why this happens! What do i wrong?
One of these URLS is not like the other
var urls = "icd?search=" + search;
var urls = "/icd/icd2/" + id;
var urls = "/icd/icd3/" + id;
Do you see why the search URL does not work? It is different than the others. AKA: It is missing the a leading /.
var urls = "/icd?search=" + search;
^

when fast cliking on like button getting unknown likes

i am working on project which have like unlike function look like facebook but i am getting stuck when i click multiple time at once on like button or unlike button then its work like firing and if i have 1 or 2 like and i click many time fast fast then my likes gone in -2 -1. how i solve this issue ? if when click many time always get perfect result. below my jquery script
$(document).ready(function () {
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
});
});
});
It is because of the async nature of ajax request.... when you click on the element continuously... the click event will get fired before the response from previous request come back and the link status is updated to next one
Case:
Assume the rel is unlike, then before the response came back again another click happens so the rel is not yet updated so you are sending another unlike request to server instead of a like request
Try below solution(Not Tested)
$(document).ready(function () {
var xhr;
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
}
//abort the previous request since we don't know the response order
if (xhr) {
xhr.abort();
}
xhr = $.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false
}).done(function (html) {
$('.spn' + ID).html(html);
}).always(function () {
xhr = undefined;
});
});
});
Set a variable, we'll call it stop and toggle it.
$(document).ready(function () {
var stop = false;
$(".like").click(function () {
if (!stop)
{
stop = true;
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
}).always(function() { stop = false; });
}
});
});

Seeing span tag when I want to be rendering the text within the span tag

I have some words on a page that display "present" or "absent" that a user can click to toggle between being present or absent.
When the word is set to "absent" I want that text to be red.
The word represents a bool and is updated on screen using the following code:
<script type="text/javascript">
absentText = $.trim('#MyApp.Resources.MyAppResource.Absent_Text').toLowerCase();
presentText = $.trim('#MyApp.Resources.MyAppResource.Present_Text').toLowerCase();
updateAttendanceUrl = '#Url.Action("UpdateAttendance", "Attendance")';
</script>
Where MyAppResource.Absent_Text = absent the page displays fine with the word, "absent" on the page.
When I change MyAppResource.Absent_Text to read "absent" my page literally displays <span style="color:red">absent</span>
Here is a sample of my view source:
<td><span style="color:red">absent</span></td>
So somehow my < and > symbols are getting taken away.
How can I change my code so that when the word on my screen is written as "absent" it is colored red?
Is there a simpler way to just color any text on the screen that matches "absent" red?
For reference, here is the rest of the javascript from my page:
var userId;
var attendanceDay;
var isPresent;
var updateAttendanceUrl;
var absentText;
var presentText;
var courseId;
$(document).ready(function (event) {
$('.attendance').live('click', function () {
userId = $(this).parents('tr').attr('id');
if (userId != '') {
attendanceDay = $(this).attr('id');
isPresent = $.trim($(this).find('span').text().toLowerCase());
courseId = $(this).parents('tbody').attr('id');
$(this).find('span').addClass('currentClass');
if (isPresent == absentText) {
UpdateAttendance(1);
} else {
UpdateAttendance(0);
}
} else {
event.preventDefault();
}
});
});
function UpdateAttendance(present) {
url = updateAttendanceUrl;
$.ajax({
type: "POST",
url: url,
data: "userId=" + userId + "&attendanceDay=" + attendanceDay + "&courseId=" + courseId + "&present=" + present,
success: function (data) {
if (isPresent == absentText) {
$('#' + userId).find('.currentClass').text(presentText).removeAttr('class');
} else {
$('#' + userId).find('.currentClass').text(absentText).removeAttr('class');
}
return true;
}
});
}
What your looking for is called unescape or htmldecode. There are various topics available on SO already. Here is one.

Loading dynamic div content with jQuery from a URL

I have a jQuery search script that uses tabs for the user to define which search type they want to use. When a user searches, a URL is created which is something like #type/query/. However, when you either reload the page, click a result which goes to a different page or return back from a previous page the search results are no longer there. Why could this be and how can I solve this issue? I do not want to use any plug-ins either.
My jQuery code is:
$(document).ready(function () {
$('[id^=type_]').click(function () {
type = this.id.replace('type_', '');
$('[id^=type_]').removeClass('selected');
$('#type_' + type).addClass('selected');
return false;
});
$('#type_search').click();
$('#query').keyup(function () {
var query = $(this).val();
var url = '/' + type + '/' + query + '/';
window.location.hash = '' + type + '/' + query + '/';
document.title = $(this).val() + ' - My Search';
$('#results').show();
if (query == '') {
window.location.hash = '';
document.title = 'My Search';
$('#results').hide();
}
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function (results) {
$('#results').html(results);
}
});
});
var textlength = $('#query').val().length;
if (textlength <= 0) {
$('#query').focus();
} else {
$('#query').blur();
}
});
When you reload the page, the reason that the results are missing is because they aren't in the document source; they've been added to the DOM later.
I reckon you have two choices, the first of which I generally use.
When you execute your search, have either the search criteria or the search results stored at the server so that when the page is next rendered, the results are rendered with it. I use ASP.NET MVC 3 and do this using a PartialView. When I use jQuery to execute the search, it causes the server to render the same PartialView and inserts the resulting HTML fragment into the results div.
Alternatively, you need to fire your jQuery search again when the page is reloaded.
Whether it's better to resubmit the search or to cache the results depends on how expensive the search is and how big the result set is likely to be.
The hash should stay after the reload of the page because it is part of the browser history.
So you can parse document.location.hash to gain knowledge about the selected query type and search.
//$(function() {
if(document.location.hash) {
var hash = document.location.hash;
var split = hash.split('/');
var queryType = hash[1];
var searchTerm = hash[2];
$('#type_'+queryType).addClass('selected');
$('#query').text(searchTerm);
$('#query').keyup();
}
//});
behind your setup routines.

Categories

Resources