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);
}
});
Related
I'm have some serious problems getting any response data through from the mediawiki api.
I'm trying to do the freecodecamp wikipedia viewer challenge and I'm coding it here:
https://codepen.io/dceaser334/pen/zpQXOJ
All i'm trying to do so far is GET the data and print it to the console using the following request:
$('.search-button').on('click', function() {
var searchInput = $('.search-input').val();
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + searchInput + '&format=json&callback=?', function(data) {
console.log(data);
});
});
All i'm trying to do so far is GET the data and print it to the console using the that request.
I'm getting this error in firefox:
Loading failed for the with source
“https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=jordan&format=json&callback=jQuery32105036538970753343_1518470620925&_=1518470620926”.
index.html:1
Nothing loads to the console and it seems like the request is blocked.
I've tried using origin=* which also makes no difference.
I'm a bit lost because this project has similar code for the GET request and works perfectly:
https://codepen.io/luckyguy73/pen/GqPzZO?editors=1010
$("#searchWiki").click(function(){
var q = document.getElementById("searchid").value;
$('#results').html('');
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=15&generator=search&origin=*&gsrsearch=" + q, function(data){
$('#results').append('<h2>Top 15 Wiki Search Results for "' + q + '"</h2>');
$.each(data.query.pages, function (i) {
$('#results').append("<p><a href='https://en.wikipedia.org/?curid=" + data.query.pages[i].pageid +
"' target='_blank'>" + data.query.pages[i].title + "</a></p>");
});
});
});
Any ideas on what I'm doing wrong here?
Thanks
I did it like this. Maybe you will be inspired by analyzing my code?
( function ( $ ) {
"use strict";
$(document).ready(function(){
function loadData() {
$(".information").text(""); // Reset data before new search.
$(function whiteFirst() {
const query = $(".wiki_query").val();
const myFirstWikiUrl = "https://en.wikipedia.org/w/api.php?action=opensearch&search=";
const mySecondWikiUrl = "&format=json&callback=wikiCallback";
const wikiUrl = myFirstWikiUrl + query + mySecondWikiUrl;
// MY WIKIPEDIA AJAX GOES HERE - TOP
const wikiRequestTimeout = setTimeout(function() {
$(".small-information").html("An error occurred! Application couldn't get Wikipedia resources!");
}, 5000); // This is 5 seconds!
$.ajax({
url: wikiUrl,
dataType: "jsonp",
type: "GET",
}).done(function(result) {
const itemsOne = [];
const itemsTwo = [];
const itemsThree = [];
$(result[1]).each(function(index, value) {
itemsOne.push(value);
});
$(result[2]).each(function(index, value) {
itemsTwo.push(value);
});
$(result[3]).each(function(index, value) {
itemsThree.push(value);
});
$(".information").hide();
$(".results").hide();
for (let i = 0; i < itemsOne.length; i++) {
$(".information").append("<a class='title' href=" + itemsThree[i] + " target='_blank'><div class='result'><p class='title' id='boldTitle'>" + itemsOne[i] + "</p><p>" + itemsTwo[i] + "</p></div></a>");
}
if (itemsOne.length === 0) {
$(".information").html("Nothing found!");
}
$(".results").show();
$("body,html").animate({
'scrollTop': $(".results").offset().top
}, 2000);
$(".information").fadeIn("slow");
clearTimeout(wikiRequestTimeout); // This will prevent timeout from happening!
});
// MY WIKIPEDIA AJAX GOES HERE - BOTTOM
});
return false;
};
$(".whiteButton").click(loadData);
$(".results").hide();
$(function() {
const offset = -50; // Optional offset
$(".back").click(function() {
$("html, body").animate({
scrollTop: $(".cover").offset().top + offset
}, 750);
});
});
});
} ( jQuery ) );
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);
});
}
}
Trying to display the cover art with the results. Something in the img src tag is causing the app not to load. If I just point the img to data.tracks[i].album.name (obviously not a real url, but enough to test if it's working) it pastes it in just fine, but the moment I change it to paste the url in place, it makes the whole app stop working.
$('#findTracks').click(function (e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.length > 0) {
var tracksLength = data.tracks.length, html = '';
for (var i=0; i<tracksLength; i++) {
var href = '';
if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1) { // data.tracks[i].href
href = data.tracks[i].href;
href = 'makeReq(\''+data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+'\')';
html += '<li>' +data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+ ' <img src="' +data.tracks[i].album.images[0].url+ '" />';html += '</li>';
html += '</li>';
}
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
This is my first time ever coding in javascript so please go easy on me! lol
EDIT:
This seems to be running well! However, many of the songs do nothing when I click on them
For example, type "Don't Stop" and only "The Black Eyed Peas - Don’t Stop The Party" works out of the first ten...anybody know why?
also, anybody known why "if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1)" is in there? If I take it out this all stops working...I am not in G.B.
If you look in the console you are getting the error
Uncaught TypeError: Cannot read property '0' of undefined
looking at the data the query returns we notice that data.tracks[i].album returns
{
"released": "2006",
"href": "spotify:album:2knAf4wg8Gff8q1bXiXCTz",
"name": "The Dutchess",
"availability": {
"territories": "MX"
}
}
there is no property images so when you call
data.tracks[i].album.images[0]
you get the undefined error, causing the script to halt execution.
I'm unfamiliar with the spootify api but taking a quick glance at the api theres the endpoint for get-album. Heres what I was able to come up with to get the album art
$.get("http://ws.spotify.com/search/1/track.json?q=Fergie",function(data){
var albumId = data.tracks[97].album.href.split(":")[2];
$.get("https://api.spotify.com/v1/albums/" + albumId,function(albumResponse){
var firstImage = albumResponse.images[0];
$('body').append($('<img/>',{
src : firstImage.url,
width : firstImage.width,
height : firstImage.height
}));
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>
You should research more into how to get the album art since I'm unsure if this is the optimal solution.
The search endpoint you mentioned is different from the one your using.
One your using
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
One you linked to
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
Heres your solution with the change in endpoint
$('#findTracks').click(function(e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
//url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.items.length > 0) {
data.tracks = data.tracks.items
data.artists = data.artists.items
var tracksLength = data.tracks.length,
html = '';
for (var i = 0; i < tracksLength; i++) {
var href = '';
href = data.tracks[i].href;
href = 'makeReq(\'' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + '\')';
html += '<li>' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + ' <img src="' + data.tracks[i].album.images[0].url + '" />';
html += '</li>';
html += '</li>';
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Artist:
<input type="text" id="artist" />
<button id="findTracks">Find Tracks</button>
<div id="recommendations"></div>
Edit (rephrasing): the website is loaded within an iframe, but there is 1 link inside the iframe which I would like to take the user out of the iframe when they click it, back into the main window that underlays the iframe.
I've found
top.location.href = 'page.htm';
, but I wouldn't know how to enter it into this 'complex' code.
This is the file I believe it should be in:
{literal}
$(document).ready( function() {
$('#payment_paypal_express_checkout').click(function() {
$('#paypal_payment_form').submit();
return false;
});
$('#paypal_payment_form').live('submit', function() {
var nb = $('#quantity_wanted').val();
var id = $('#idCombination').val();
$('#paypal_payment_form input[name=quantity]').val(nb);
$('#paypal_payment_form input[name=id_p_attr]').val(id);
});
function displayExpressCheckoutShortcut() {
var id_product = $('input[name="id_product"]').val();
var id_product_attribute = $('input[name="id_product_attribute"]').val();
$.ajax({
type: "GET",
url: baseDir+'/modules/paypal/express_checkout/ajax.php',
data: { get_qty: "1", id_product: id_product, id_product_attribute: id_product_attribute },
cache: false,
success: function(result) {
if (result == '1') {
$('#container_express_checkout').slideDown();
} else {
$('#container_express_checkout').slideUp();
}
return true;
}
});
}
$('select[name^="group_"]').change(function () {
displayExpressCheckoutShortcut();
});
$('.color_pick').click(function () {
displayExpressCheckoutShortcut();
});
{/literal}
{if isset($paypal_authorization)}
{literal}
/* 1.5 One page checkout*/
var qty = $('.qty-field.cart_quantity_input').val();
$('.qty-field.cart_quantity_input').after(qty);
$('.qty-field.cart_quantity_input, .cart_total_bar, .cart_quantity_delete, #cart_voucher *').remove();
var br = $('.cart > a').prev();
br.prev().remove();
br.remove();
$('.cart.ui-content > a').remove();
var gift_fieldset = $('#gift_div').prev();
var gift_title = gift_fieldset.prev();
$('#gift_div, #gift_mobile_div').remove();
gift_fieldset.remove();
gift_title.remove();
{/literal}
{/if}
{if isset($paypal_confirmation)}
{literal}
$('#container_express_checkout').hide();
$('#cgv').live('click', function() {
if ($('#cgv:checked').length != 0)
$(location).attr('href', '{/literal}{$paypal_confirmation}{literal}');
});
// old jQuery compatibility
$('#cgv').click(function() {
if ($('#cgv:checked').length != 0)
$(location).attr('href', '{/literal}{$paypal_confirmation}{literal}');
});
{/literal}
{else if isset($paypal_order_opc)}
{literal}
$('#cgv').live('click', function() {
if ($('#cgv:checked').length != 0)
checkOrder();
});
// old jQuery compatibility
$('#cgv').click(function() {
if ($('#cgv:checked').length != 0)
checkOrder();
});
{/literal}
{/if}
{literal}
var modulePath = 'modules/paypal';
var subFolder = '/integral_evolution';
var fullPath = baseDir + modulePath + subFolder;
var confirmTimer = false;
if ($('form[target="hss_iframe"]').length == 0) {
if ($('select[name^="group_"]').length > 0)
displayExpressCheckoutShortcut();
return false;
} else {
checkOrder();
}
function checkOrder() {
confirmTimer = setInterval(getOrdersCount, 1000);
}
{/literal}{if isset($id_cart)}{literal}
function getOrdersCount() {
$.get(
fullPath + '/confirm.php',
{ id_cart: '{/literal}{$id_cart}{literal}' },
function (data) {
if ((typeof(data) != 'undefined') && (data > 0)) {
clearInterval(confirmTimer);
window.location.replace(fullPath + '/submit.php?id_cart={/literal}{$id_cart}{literal}');
$('p.payment_module, p.cart_navigation').hide();
}
}
);
}
{/literal}{/if}{literal}
});
{/literal}
Edit: found some part of the HTML as well, figured it'd be easy to do there, but it doesnt actually seem to work. Perhaps because of the void(0)?
<a href="javascript:void(0)" target="_top" onclick="$('#paypal_payment_form').submit();" id="paypal_process_payment" mod='paypal'}">
Perhaps someone here can help me out. Thanks in advance!
Best,
Dave
This is some JavaScript that will redirect the user out of the iframe to the website if the website is being 'iframed':
<script>if (top !== self) top.location.href = self.location.href;</script>
I do not see a portion of the code for your form, but since you are using submit() you can set the target of the form to _top:
<form target="_top" action="yoururl.php" id="paypal_payment_form">
Then once you use submit, it will break the frames and continue to the new page.
<a href="#" onclick="$('#paypal_payment_form').submit();" id="paypal_process_payment" mod='paypal'>
I'm trying to do something like a dictionary. The idea is there is a DB online. Someone can search for term and get the description from the db.
How it works:
1) whole terms from the db will be downloaded and compared with searchterm. each term has its specific ID. If the searchterm is the DB the ID will be saved.
2) The ID will be sent to the server with the DB and than it should receive the description
URL to get all Terms
http://s288617660.mialojamiento.es/api.php?rquest=terms
Url to get description
http://s288617660.mialojamiento.es/api.php?rquest=answers¶m1=ID
Now this is my search function
<script>
getAllTerms();
function getAllTerms(){
var url = "http://s288617660.mialojamiento.es/api.php?rquest=terms";
$.get(url, function(data) {
localStorage.setItem("terms", JSON.stringify(data));
//alert(JSON.stringify(data));
}).done(function() { /*alert(localStorage.getItem("terms"));*/ })
.fail(function() { alert("error"); })
.always(function() { /*alert("finished");*/ });
}
function findTerm(){
var content = $("#SearchTerm").val();
//alert(content);
var id = 0;
var data = JSON.parse(localStorage.getItem("terms"));
$.each(data, function(index, term) {
//alert("My content " + content + ", term " + term.name);
if(content == term.name){
id = term.id_term;
}
});
//--------------my try to request the description
var url_answers = "http://s288617660.mialojamiento.es/api.php?rquest=answers¶m1="+id;
//alert(url_answers);
var answer = "";
$.get(url_answers, function(data2) {
localStorage.setItem("answer", JSON.stringify(data2));
$.each(data2, function(index, object) {
answer = object.description+object.id_answer;
});
//-----------------end of my try
//alert(id);
var htmlStr = "";
if(parseInt(id) > 0){
//i found the term
localStorage.setItem("idterm",id);
htmlStr = "<li>" + content + "- id: " + id + answer + "</li>"
}else{
//not found
htmlStr = "<li>Term not found</li>"
}
$('#SearchList').empty();
$('#SearchList').append(htmlStr);
$('#SearchList').listview("refresh");
}
</script>
The ID request just works fine but not the description request. Why?
By the way: it's a android phonegap project