Changing url using javascript and jquery - javascript

Hello there
I am developing a jQuery plugin that loads files through ajax. When user clicks on a button which is:
<button class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
When user clicks on button it generates following url:
http://localhost//plugins/ajaxLoad/index.html#ajax/Login
I want to change it to
http://localhost//plugins/ajaxLoad/index.html/ajax/Login
My javascript is:
(function ($) {
$.fn.ajaxLoad = function (options) {
var settings = $.extend({
fileUrl : 'null',
loadOn : '.em'
}, options);
$('[data-load="ajax"]').each(function(index, el) {
$(this).click(function () {
var file = $(this).attr('data-file');
var loadOn = $(this).attr('data-load-on');
var permission = $(this).attr("data-ask-permission");
settings.fileUrl = file;
settings.loadOn = loadOn;
if (permission == 'yes') {
var ask = confirm("Do you want to load file");
if (ask == true) {
$.fn.loadFile();
}
}else {
$.fn.loadFile();
}
});
});
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.split(".");
location.hash = a[0];
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}
}(jQuery))
Can anyone tell me how to change url in jquery and Javascript.

You need to use history.pushstate() to do this.
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
Have a look at this article on MDN for more details
https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method
This article gives some nice jQuery examples.
https://rosspenman.com/pushstate-jquery

Added another attribute title to button
<button data-title="login" class='btn btn-info' data-load="ajax" data-file="ajax/login.html" >Login</button>
In Js (after $(this).click line):
var title = $(this).attr('data-title');
settings.title = title
Just replace
location.hash = a[0];
With
history.pushState('','',"?"+settings.title);

Change
location.hash = a[0];
to:
location.pathname += '/' + a[0];

Just replace the hash with a blank using .replace()
Example .
settings.fileUrl.replace('.' , ' ');
Updated above also
UPDATE :
Don't hash the URL
Example :
$.fn.loadFile = function () {
// setting location;
var a = settings.fileUrl.replace("." , "/");
location.href = a;
$.post(settings.fileUrl, function(response) {
$(settings.loadOn).html(response);
});
}
}

Related

Trying to get a correct url output

I am kinda new to asp.net mvc website with jquery, razor, javascript and html. Right now my actionlink has a problem where I cannot insert the filter part, into ..page/?sortMethod=StartDate
filters?=pending generates from a button (pending is just 1 of the many status)
?sortMethod=StartDate generates from actionlink.
I am trying to make them work together to get:
..page/?filters?=pending&sortMethod=StartDate
I tried to do a script that tries to replace the
This is the initial code, sortMethod is a string.
<script>
$(function () {
$("#filterUidClear").click(function () {
$("#filterUid").val('');
});
$('#filterPending').checkboxradio();
$('#filterDirect').checkboxradio();
$('#ApplyFilter').click(function () {
var params = "";
if ($('#filterPending')[0].checked) {
params = "filters=pending";
}
if ($('#filterDirect')[0].checked) {
if (params !== "") {
params = params + "&";
}
params = params + "filters=direct";
}
$("#param").val("?" + params);
window.location.href = "?" + params;
});
});
</script>
#Html.ActionLink("Leave Date", "Index", new { sortMethod = ViewBag.StartDate })
This is the new modified one
#Html.ActionLink("Leave Date", "Index", new { sortMethod = ViewBag.StartDate }, new { id = action })
<script>
$(function() {
$('#action').click(function() {
var filterparam = $("#param").val();
this.href = this.href + '?filters=' + encodeURIComponent(filterparam) + '&sortMethod=' + #ViewBag.StartDate;
});
</script>
I am trying to make them work together to get:
..page/?filters=pending&sortMethod=StartDate but to no avail.
The table will display filtered with pending results and sorted by date
Right now it displays ..page/?action&sortingMethod=StartDate
the table shows sorted by date but no filter and action is not being replaced by filter type e.g. ?filters=pending

How get specific html from a jQuery object

I am fetching html from a website. I want to get specific html from that page not all how to get that? I have tried following;
before appending data to target below
container.html(data);
I want to do like data.find('.site-header').html(); and then do container.html(data);
How can I achieve that?
DEMO
HTML
<div id="target"></div>
Script
$(function () {
var container = $('#target');
var url = 'http://aamirshahzad.net';
$.getJSON("http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(url) +
"%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var data = filterData(data.results[0]);
container.html(data);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg).focus().effect('highlight', {
color: '#c00'
}, 1000);
}
});
});
function filterData(data) {
// filter all the nasties out
// no body tags
data = data.replace(/<?\/body[^>]*>/g, '');
// no linebreaks
data = data.replace(/[\r|\n]+/g, '');
// no comments
data = data.replace(/<--[\S\s]*?-->/g, '');
// no noscript blocks
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
// no script blocks
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
// no self closing scripts
data = data.replace(/<script.*\/>/, '');
// [... add as needed ...]
return data;
}
Quite simply;
container.html($(data).find('.site-header'));
Add this line after container.html(data);:
container.html(container.find(".site-header"));
Here is your updated JSFiddle

Function Not Defined OEmbed Vimeo API

Started messing around with Vimeo API in an attempt to create a clickable gallery like this (http://www.aideffectiveness.org/busanhlf4/vimeo/php-example.php). However, when I moved some of the code into a "script.js" file as a way to organize my code from the other parts of the site, the json callback keeps saying that the 'embedVideo' function is not defined. Any ideas?
The "script.js" file is placed at the bottom of the page and has the following:
var NS = NS || NS;
NS = {
videoInit: function() {
var oEmbedUrl = 'http://vimeo.com/api/oembed.json';
var oEmbedCallback = 'embedVideo';
var videoid = "";
if(videoid == '' ){
videoid = '23515961';
}
function embedVideo( video ) {
var videoEmbedCode = video.html;
document.getElementById('embed').innerHTML = unescape(videoEmbedCode);
}
function init() {
loadScript(oEmbedUrl + '?url=http://vimeo.com/' + videoid + '&height=380&width=700&callback=' + oEmbedCallback);
}
function loadScript( url ) {
var js = document.createElement('script');
js.setAttribute('src', url);
document.getElementsByTagName('head').item(0).appendChild(js);
}
init();
}
}
$(function() {
NS.videoInit();
});
The HTML:
<div id="wrapper">
<div id="embed"></div>
</div>
embedVideo is a local (private) function inside of the init method. Nothing outside it can see it. That's why your AJAX callback is throwing that error.
You can fix this by making embedVideo a proper method of NS, so that's it's visible to your ajax callback
NS = {
embedVideo: function( video ) {
var videoEmbedCode = video.html;
document.getElementById('embed').innerHTML = unescape(videoEmbedCode);
},
videoInit: function() {
var oEmbedUrl = 'http://vimeo.com/api/oembed.json';
var oEmbedCallback = 'embedVideo';
var videoid = "";
if(videoid == '' ){
videoid = '23515961';
}

Loading dynamically generated content and URL after page reload

I have a Google Instant style search script written in jQuery. When a user searches, a URL is created which is something like #search/QUERY/3/. 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?
Here is my jQuery code:
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var query=encodeURIComponent(search);
var page=1;
var yt_url='search.php?q='+query+'&category=web&d='+page+'';
window.location.hash='search/'+query+'/'+page+'/';
document.title=$(this).val()+" - My Search Script";
if(search==''){
window.location.hash='';
document.title='My Search Script';
}
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
if(response !=""){
$("#result").html(response);
} else {
$("#result").html("Your search did not return any results");
}
}
});
});
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
});
I think it could be something to do with these lines of code:
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
You need to write a function for the search so you can specify the page number.
$(document).ready(function(){
var search = function (query, page) {
page = page ? page : 1;
query = encodeURIComponent(query),
var yt_url = 'search.php?q=' + query + '&category=web&d=' + page + '';
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
} else {
window.location.hash = 'search/' + query + '/' + page + '/';
document.title = $(this).val() + " - My Search Script";
}
$.ajax({ ... });
};
$("#search").keyup(function(){ search(this.value); });
if (window.location.hash.indexOf('#search/') == 0) {
var query = window.location.hash.replace('#search/', ''),
page = query.replace(/.+?\/(\d+)\//, '$1');
query = query.replace(/\/\d+\//, '');
search(decodeURIComponent(query), page);
}
});

jquery and data-attr not working in ie8

This concerns a table where I show 5 rows at a time.
The follow code is working 100 percent perfect in firefox. But in ie8,
only the top row can be clicked for the editdiv to show. Whereas, in firefox
I can click on any of the five rows and the editdiv loads as expected.
Line in php file that calls the function:
echo "<td><a id=\"editjq\" href=\"#\" vid='".$vid."' t1='".$db->hscadd($t1)."' page='".$page."' flag='1')\"> [edit ] </a></td>";
The function:
$(document).ready(function() {
$('a#editjq').click(function() {
var petid = $(this).attr('vid');
var t1 = $(this).attr('t1');
var page = $(this).attr('page');
var flag = $(this).attr('flag');
$("#petdiv").hide();
$.post("edit_lookup.php", {
petid : petid,
t1 : t1,
page : page
}, function(data){
if (data.length>0){
$("#editdiv").html(data);
}
});
$(this).unbind();
return false;
});
});
Are you producing five rows which each have an anchor with the same id attribute? If so, that's your problem. It is syntactically illegal to have more than one element with the same id. Instead of id="editjq" use class="editjq" and $('a.editjq').click(...).
You could put this piece of jquery plugin code in your page script (just make sure that it comes after the jquery.min.js script tag);
(function($){
var store = {};
$.fn.extend({
collection : function(action, name, value) {
var $this = this;
var generate = function(){
return "COLLECTION" + parseInt((Math.random() * 100000), 16);
}
var item_id;
var methods = {
put: function(){
item_id = $this.attr("id");
if(store[item_id]){
store[item_id][name] = value;
} else {
while(store[item_id] && $(item_id).length > 0){
item_id = generate();
}
$this.attr("id", item_id);
store[item_id] = {};
store[item_id][name] = value;
}
return $this;
},
get: function(){
item_id = $this.attr("id");
if(store[item_id] && store[item_id][name]){
return store[item_id][name];
}
else{
return null;
}
},
remove: function(){
item_id = $this.attr("id");
if(store[item_id]){
store[item_id][name] = null;
}
return $this;
}
}
if(methods[action]){
return methods[action]();
} else{
return alert(store.text.length);
}
return $this;
}
});
})(jQuery);
It can be used as follows:
store a data value
$(*selector*).collection("put", *DataName*, *DataValue*);
retreive a data value
var referencing_variable = $(*selector*).collection("get", *DataName*);
delete a data value
$(*selector*).collection("remove", *DataName*);
This is a cross browser solution. Though i have only tested it with Jquery 1.5.1

Categories