So I got to create a search query based on an written javascript file (below) and I also have to use this URL to create the search query. At the end of the URL, you can add any search term you like. For example, we will search about food : https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=food
Can anyone tell me what to do to create it?
$(document).bind('pageinit', function(ev){
$('#search').on('keyup', function(e){
if(e.keyCode == 13){
$.get('search.php', {"q": $('#search').val()}, function(data){
var json = JSON.parse(data);
console.log(json);
$('#results').listview('refresh');
});
}
});
First:
You can access this api direct with javascript (jquery).
If you try it with the normal url https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=food you get an error because of the "Access-Control-Allow-Origin" Settings.
If you append "&callback=?" you will get proper data returned
Now you have to append the returned data to your listview.
The important thing to know is: what is returned. In your code the value of data or the value of var json Since you dont provide any of your php. i can only do it direct with the jquery getJSON Call.
$(document).bind('pageinit', function(ev) {
$('#search').on('keyup', function(e) {
if (e.keyCode == 13) {
// The Base URL
var baseUrl = 'https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=';
// The question from the inputfield
var q = $('#search').val();
// putting the url togehter and append &callback=?
var url = baseUrl + q + "&callback=?";
console.log(url);
// Call The API for a JSON
$.getJSON(url, function() {
console.log("success");
}).done(function(data) {
console.log("second success");
console.log(data.responseData.results);
// create a var for the results and append a header
var results = '<li data-role="list-divider">Results</li>';
$.each(data.responseData.results, function(index, item) {
results += '<li>';
results += item.title;
results += '</li>';
});
// clear the results . append the results .refresh the listview
$('#results').empty().append(results).listview('refresh');
}).fail(function() {
console.log("error");
}).always(function() {
console.log("always");
});
}
});
});
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- jQuery Mobile -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<!-- page1 -->
<div data-role="page" id="page1" data-title="page1">
<!-- Header -->
<div data-role="header" data-position="fixed">
<h1>Page 1</h1>
</div>
<!-- /Header -->
<!-- Content -->
<div role="main" class="ui-content">
<label for="search">Search Input:</label>
<input name="search" id="search" value="" placeholder="palceholder" type="search">
<ul data-role="listview" id="results" data-inset="true">
</ul>
<script>
</script>
</div>
<!-- /Content -->
</div>
<!-- /page1 -->
$(document).bind('pageinit', function(ev) {
$('#search').on('keyup', function(e) {
if (e.keyCode == 13) {
// The Base URL
var baseUrl = 'https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=';
// The question from the inputfield
var q = $('#search').val();
// putting the url togehter and append &callback=?
var url = baseUrl + q + "&callback=?";
console.log(url);
// Call The API for a JSON
$.getJSON(url, function() {
console.log("success");
}).done(function(data) {
console.log("second success");
console.log(data.responseData.results);
// create a var for the results and append a header
var results = '<li data-role="list-divider">Results</li>';
$.each(data.responseData.results, function(index, item) {
results += '<li>';
results += item.title;
results += '</li>';
});
// clear the results . append the results .refresh the listview
$('#results').empty().append(results).listview('refresh');
}).fail(function() {
console.log("error");
}).always(function() {
console.log("always");
});
}
});
});
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- jQuery Mobile -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<!-- page1 -->
<div data-role="page" id="page1" data-title="page1">
<!-- Header -->
<div data-role="header" data-position="fixed">
<h1>Page 1</h1>
</div>
<!-- /Header -->
<!-- Content -->
<div role="main" class="ui-content">
<label for="search">Search Input:</label>
<input name="search" id="search" value="" placeholder="palceholder" type="search">
<ul data-role="listview" id="results" data-inset="true">
</ul>
<script>
</script>
</div>
<!-- /Content -->
</div>
<!-- /page1 -->
Related
I've a problem with TinyMCE.
When I load the TinyMCE textarea content (with jQuery) into my database, and then I see the result on a php page, I see html tag...in the picture you can find an example.
HTML
<div class="container pt">
<!-- +++++ Posts Lists +++++ -->
<div class="row mt">
<div class="col-lg-6 col-lg-offset-3 centered">
<h3>MY BLOG</h3>
<hr>
</div>
</div>
<div id="white">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2" id="menublog">
</div>
</div><!-- /row -->
</div> <!-- /container -->
</div><!-- /white -->
</div>
JQuery
$(document).ready(function() {
$("#Insert").click(function(){
event.preventDefault();
var user = "2", titolo = $('#titolo').val(), articolo = tinyMCE.activeEditor.getContent({format : 'raw'});
var id_immagine = $('#menuimmagini').val();
alert(id_immagine);
object = JSON.stringify({r: 'InsertPost', u: user, t: titolo, a: articolo, i:id_immagine});
$.post("server.php", { js_object: object },
function(msg){
console.log(msg);
if(msg)
{
alert("Post inserito con successo!");
location.reload();
}
});
});
});
OUTPUT JQUERY
$(document).ready(function() {
event.preventDefault();
object = JSON.stringify({r: 'InitializeBlog'});
$.post("servo.php", { js_object: object },
function(response)
{
var obj = jQuery.parseJSON(response);
$.each( obj, function( index ) {
$('#menublog').append("<p><img class=\"img-circle\" src=\"assets/img/user.png\" width=\"50px\" height=\"50px\"> <ba>Salvo Bertoncini</ba></p> <p><bd>Posted on "+obj[index].date+"</bd></p> <h4>"+obj[index].title+"</h4> <p><img class=\"img-responsive\" src=\"show.php?id="+obj[index].idimmagine+"\"></p> "+obj[index].articles+" <p>Continue Reading...</p><hr>");
});
}
);
});
All editor WYSWYG convert the content to html entities. you should use this library for example:
http://www.strictly-software.com/htmlencode
Below is my javascript in nextPage.js. When I click on it, it must pass category_id to the reportlist.html page. Please help me.
var base_url = "http://dev.edfutura.com/nithin/jps/edfuturaMob/";
$(document).on("pageinit", "#catlist", function() {
var submitUrl = base_url+"categorylist/get_categorylist";
$.ajax({
url: submitUrl,
dataType: 'json',
type: 'POST',
success: function(response) {
var categoryList = $('#category');
var category;
for(var i = 0, len = response.length; i < len; i++) {
category = response[i];
var a = $('<a>').attr('href', 'reportlist.html').html(category.category_name);
categoryList.append($('<li>').attr('id', category.category_id).append(a));
}
},
error: function() {
alert("error");
}
});
My first page is nextPage.html and my category_names are stored in a list as links through JS.
<body id="category_id">
<div data-role="page" id="catlist">
<div id="loading"></div>
<div data-role="header" data-position="fixed" data-theme="b">
<h1>category</h1>
</div>
<div data-role="main" class="ui-content">
<form id="nextForm" >
<ul data-role="listview" data-inset="true" id="category">
<li id="catid"></li>
</ul>
</form>
</div>
</div>
</body>
If you want to pass some data when you change the page, you must use request parameters
When you want to pass data in href link, you should use GET request like this:
reportlist.html?category_id=12
Then you can read your data similarly to this https://stackoverflow.com/a/979995/4772988
I'm trying to submit multiple forms at once when a single button is clicked. These forms are all generated automatically. They all have different action urls but the same id's. That's how the system (SaaS) works.
The problem is that I'm having issues getting the correct selectbox values and then send the forms. I'm not getting any error but I think it has something to do with identifiers. I'm working on this one for a few days now and I can't figure this one out.
So for every set/product there's some empty html, like so:
HTML
<div id="sets" class="clearfix">
// first set
<div class="set" data-handle="url" >
<div class="right">
<div class="products">
<div class="close"></div>
<div class="product">
/// in here comes the product data from json ///
</div>
<div class="set-bestellen">
<div class="link">
<a title="add" class="trigger"><span>add to cart</span></a>
</div>
</div>
</div><!-- .products -->
</div><!-- .right -->
<div class="image"></div>
</div>
// second set
<div class="set" data-handle="url" >
<div class="right">
<div class="products">
<div class="close"></div>
<div class="product">
/// in here comes the product data from json ///
</div>
<div class="set-bestellen">
<div class="link">
<a title="add" class="trigger"><span>add to cart</span></a>
</div>
</div>
</div><!-- .products -->
</div><!-- .right -->
<div class="image"></div>
</div>
// etc... can be as much as 10 sets
</div><!-- .#sets -->
Inside the above HTML .product there comes an automatically generated form. This form is generated like so:
Jquery
$('#sets .set').each( function(){
$(this).click(function(){
if($(this).hasClass('open')){
$('.close').click(function(){
$('#sets .product').fadeOut();
$('.products',this).animate({
width: 'toggle'},500, function() {
.......
});
});
} else {
.....
}
var url = $(this).data('handle')+'?format=json';
$.getJSON(url, function (data){
var product = data.product;
var $container = $('.products .product');
var productsHtml = [];
var fullurl = 'http://www.shop.com';
var variants = '';
$.each(product.related, function(index, rel){
var url = ''+fullurl+''+rel.url+'?format=json';
...... etc ...
var productHtml = '<div id="'+rel.id+'" class="p"><form method="post" id="product_configure_form" action="http://www.shop.com/cart/add/'+rel.vid+'/" name="formsub"><div class="foto"><img class="rollover" src="'+image+'" hover="'+image2+'" alt="'+rel.fulltitle+'"/></div><div class="prijs" data-price="'+rel.price.price_incl+'">€'+rel.price.price_incl+'</div><div class="varianten_'+rel.id+'">';
$.getJSON(url, function (data){
var rel = data.product;
var wqsSelectVariants = $('<div class="product-configure-variants tui" />');
var select = $('<select id="product_configure_variants"/>');
$.each(rel.variants, function (index, variant){
select.append('<option value=' + variant.id + '>' + variant.title + '</option>');
wqsSelectVariants.append(select);
});
$('.varianten_'+rel.id).html(wqsSelectVariants);
});
var price = rel.price.price_incl;
sum += price;
productHtml = productHtml + '</div></form></div>';
productsHtml.push(productHtml);
});
$('.total').text('€'+sum.toFixed(2));
productsHtml = productsHtml.join('')
$container.html(productsHtml);
});
}
});
});
etc....
<script type="text/javascript">
$(document).ready(function(){
$(".trigger").on("click", function(e){
e.preventDefault();
$('form[name="formsub"]').each(function(){
var variant = $('#product_configure_variants').val();
var $form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action')+variant+'/?quantity=1',
data: $form.serialize(),
success: function(data, status){
if(status == 'success'){
}else if(status == 'error'){
}
}
});
});
});
});
</script>
Does anyone know what's going wrong or give me some directions on how to fix that?
Try using $('form[name="formsub"]:visible') as your selector. That should give you just the visible forms instead of all the ones on the page.
Background
I'm building up a website that lists organisations in my local area. The site is powered by an API and stores it's data in an instance of MongoDB.
I'm fetching JSON from the API and dynamically building the content in Javascript.
Now to test against XSS attacks I deliberately added some code to inject a Javascript alert into my page.
But it's not working? Which obviously I'm happy about but I'm more confused as to why not.
The JSON
{
"_created": "Tue, 11 Mar 2014 19:27:30 GMT",
"_etag": "fd8102613204000414cceff538771453b984a2c6",
"_id": "531f63a246e29300025291ba",
"_updated": "Tue, 11 Mar 2014 19:27:30 GMT",
"description": "<script>alert('hello');</script>",
"tags": [
"Antiques"
],
"title": "HTML Injection",
"url": "www.link.com"
}
the injected code
<script>alert('hello');</script>
The code to retrieve the JSON and render it
function S_GET(id) {
var a = new RegExp(id+'=([^&#=]*)');
return decodeURIComponent(a.exec(window.location.search)[1]);
}
// retrieves languages and adds them to a list
var organisationId = S_GET('organisationId');
var url = 'http://damp-island-8192.herokuapp.com/organisations/' + organisationId;
var dataRequest = new XMLHttpRequest();
dataRequest.open('GET',url, false);
dataRequest.onreadystatechange = processJSON;
dataRequest.send();
function processJSON() {
if ( dataRequest.readyState == 4 && dataRequest.status == 200 ) {
showJSON(dataRequest.responseText);
}
}
function showJSON(input) {
//dom elements
var list = document.createElement('ul');
list.setAttribute('id', 'organisation-details-list');
var organisation = JSON.parse(input);
// list organisation details
// title
var title = document.createElement('li');
title.setAttribute('class', 'organisation-title');
title.innerHTML = organisation.title;
list.appendChild(title);
// description
var desc = document.createElement('li');
desc.setAttribute('class', 'organisation-desc');
desc.innerHTML = organisation.description;
list.appendChild(desc);
// link
var link = document.createElement('li');
link.setAttribute('class', 'organisation-link');
var a = document.createElement('a');
a.setAttribute('href', organisation.url);
a.innerHTML = organisation.url;
link.appendChild(a);
list.appendChild(link);
document.getElementsByClassName('organisation')[0].appendChild(list);
};
The HTML
<!DOCTYPE html>
<head>
<title>Moving To Leicester</title>
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="container">
<div class="header">
<ul class="nav nav-pills dropdown-menu-right">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
<div class="row padding-top-5">
<div class="col-md-2">
<!--Sidebar content-->
</div>
<div class="col-md-10">
<!--Body content-->
<div class="organisation"></div>
</div>
</div>
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/organisation-details-page.js"></script>
</body>
</html>
Question
Why doesn't the page trigger an alert when I'm viewing it?
To my knowledge inserting executable Javascript via AJAX is somewhat limited.
You cannot just get code via AJAX, put it in a LI's innerHTML an have it executed.
This is what you do:
var organisation=JSON.parse(input);
var title=document.createElement('li');
title.setAttribute('class','organisation-title');
title.innerHTML=organisation.title;
list.appendChild(title);
However, one work-around could be if you change your injection into this:
<iframe src='/' width='1' height='1' onload='window.alert("boo");'></iframe>
I think that would inject itself.
This web page is currently displaying data from an "all" category from an rss feed once the page is loaded. My question is there are several categories which I would like the user to select and display. There are a total of 10 categories, and each correspond to a separate rss feed. Can anyone explain how I handle this event? Also, if one of the categories is selected, will it automatically override the current data being displayed? I will elaborate any unclear parts if needed. Thank you!
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'GET',
url: '/example',
dataType: 'xml',
success: function (xml) {
$(xml).find("item").each(function () {
var title = $(this).find("title").text();
var description = $(this).find("description").text();
var linkUrl = $(this).find("link").text();
//var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>";
var displaytitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
$('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+description+'</p>');
});
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<!-- /field panel -->
<div data-role="panel" id="fieldpanel" data-position="left" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<fieldset data-role="controlgroup">
<legend>Categories</legend>
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
<input type="checkbox" name="checkbox-eleP" id="checkbox-eleP">
<label for="checkbox-eleP">Electrical/Power</label>
<input type="checkbox" name="checkbox-eleD" id="checkbox-eleD">
<label for="checkbox-eleD">Electronics/Design</label>
<input type="checkbox" name="checkbox-nano" id="checkbox-nano">
<label for="checkbox-nano">NanoEngineering</label>
<input type="checkbox" name="checkbox-opt" id="checkbox-opt">
<label for="checkbox-opt">Optics/Display</label>
<input type="checkbox" name="checkbox-semi" id="checkbox-semi">
<label for="checkbox-semi">Semiconductors</label>
</fieldset>
</ul>
</div><!-- /field panel -->
<!-- /settings panel -->
<div data-role="panel" id="settingspanel" data-position="right" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<li>Join IEEE</li>
<li> subscription services</li>
</ul>
</div><!-- /settings panel -->
<div data-role="header" data-theme="b">
Menu
Settings
<h1>MOBILE</h1>
</div>
<div data-role="content">
<div id="feedContainer"></div>
<h3></h3>
<p></p>
</div>
<div data-role="footer">
<h4>Advertisements</h4>
</div>
</div>
</body>
</html>
I will assume you want to get the basic information about this code!
Ok, the first thing to handle is the type of the data to be shown.
<input type="checkbox" id="1" />
<input type="checkbox" id="2" />
Lets start with 2 instead of 10! The jQuery code for this would be easy to understand.
$('input[type=checkbox]').click(function () { // click on checkbox
var val = $(this).attr('id'); // get its id as value
if(val == '2') {
$('someelement).html('2 was selected');
$('#1').prop('checked', false); // unselect the other one
}
}
So, this is the basic code which will execute when a click event occurs on a checkbox. Now in your code you'll be using something like ajax then add the ajax request code before the .html() thing and write the response there.
To update the content being displayed you will be needed to use only one element as the basic clipboard for your app. Why? Because everytime you will get the data, you will be needed to replace the current content with that one and this way you will get only the current data; the selected data.
Lets try one checkbox from your code:
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
Now lets handle the jQuery
$('input[type="checkbox"]').click(function () {
// and all others will be here just as they are.. to check the id
// your ajax request is perfect, just copy paste that here..:)
});
But just need to make a change there, instead of sending the same request try to add one more thing there,
$.ajax({
// url and datatype here,
data: value
// success function goes here
});
Note that the value was the variable that we took from the checkbox. Which will be sent with the request so that you can process only the necessary part of the RSS and leave all other, just like an if else block.
Here is a working fiddle for this http://jsfiddle.net/afzaal_ahmad_zeeshan/KU9JT/.
But I am sorry, I didnot include the if else block to make the code work as it was meant to be. But you'll understand how to manipulate this.