Is there a more efficient way to write this PHP/jQuery - php

I have this PHP:
<?php
$data = file_get_contents('http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml');
$xml = simplexml_load_string($data);
$data1 = file_get_contents('http://www.skysports.com/rss/0,20514,11661,00.xml');
$xml1 = simplexml_load_string($data1);
$master[0] = $xml;
$master[1] = $xml1;
echo json_encode($master);
?>
And this jQuery:
var myRSS =[];
function rssReader() {
console.log('ran');
$.getJSON('bbc.php', function(data){
console.log(data);
$.each(data[0].channel.item, function(index, item){
// check if item title is stored in the array
if (jQuery.inArray(item.title, myRSS) != -1) {
//do nothing
} else {
// save item title in the array
myRSS.push(item.title);
// publish item
$('.container').prepend("<a target='_BLANK' href='" + item.link + "' class='title' data-date='" + item.pubDate + "'>" + item.title + "</a>");
$("title").text('EMG: ' + item.title);
$('#loader').remove();
}
});
$.each(data[1].channel.item, function(index, item){
// check if item title is stored in the array
if (jQuery.inArray(item.title, myRSS) != -1) {
//do nothing
} else {
// save item title in the array
myRSS.push(item.title);
// publish item
$('.container').prepend("<a target='_BLANK' href='" + item.link + "' class='title' data-date='" + item.pubDate + "'>" + item.title + "</a>");
$("title").text('EMG: ' + item.title);
}
});
});
}
rssReader();
setInterval(rssReader, 10000);
There seems to be a lot of repeated code and therefore isn't very DRY programming. The returned JSON actually has the same structure, from BBC and Sky Sports so there must be a more efficient way of writing this.
Thanks

you can cut your jquery down to this(havent tested it there might be a typo):
var myRSS =[];
function rssReader() {
console.log('ran');
$.getJSON('bbc.php', function(data){
console.log(data);
$.each(data[0].channel.item, function(index, item){
linkhandler(item)
if (jQuery.inArray(item.title, myRSS) == -1) {
$('#loader').remove();
}
});
$.each(data[1].channel.item, function(index, item){
linkhandler(item)
});
});
}
function linkhandler(item)
{ // check if item title is stored in the array
if (jQuery.inArray(item.title, myRSS) == -1) {
// save item title in the array
myRSS.push(item.title);
$('.container').prepend("<a target='_BLANK' href='" + item.link + "' class='title' data-date='" + item.pubDate + "'>" + item.title + "</a>");
$("title").text('EMG: ' + item.title);
}
}
rssReader();
setInterval(rssReader, 10000);

Just to make things a little cleaner, you could do something like this:
var myRSS =[];
var handleData = function(index, item) {
// check if item title is stored in the array
if (jQuery.inArray(item.title, myRSS) != -1) {
//do nothing
} else {
// save item title in the array
myRSS.push(item.title);
// publish item
$('.container').prepend("<a target='_BLANK' href='" + item.link + "' class='title' data-date='" + item.pubDate + "'>" + item.title + "</a>");
$("title").text('EMG: ' + item.title);
$('#loader').remove();
}
}
function rssReader() {
console.log('ran');
$.getJSON('bbc.php', function(data){
console.log(data);
$.each(data[0].channel.item, handleData);
$.each(data[1].channel.item, handleData);
});
}
rssReader();
setInterval(rssReader, 10000);
But, as far as efficiency is concerned, I don't think it's that different. But, it's at least cleaner.

Just a note to be aware of, try and make less consecutive changes to the DOM. In some of the answers it is minimal anyway so not too much of a problem. But each change to them DOM has a massive overhead compared to say constructing blank objects and inserting them en mass or making mass changes to lists and the like.

Related

When I try to send data to the server, I do not get the result expected

I have a Jquery function that is using getJson. I am trying to form something like www.mysite.com/?state=oregon. According to Jquery ("Data that is sent to the server is appended to the URL as a query string..."), but I get all the values in the json data. What I am doing wrong.
Here is my code
function changeLine(line){
$('#table_lines').html('');
$.getJSON("../index.php", {, line}, function(data){
var line_data = '';
$.each(data, function(key, value){
line_data += '<tr id="' +value.line_id+'">';
line_data += '<td>' + otherValueTime(value.MatchTime)+'</td>';
line_data += '<td>' + value.home+'</td>';
line_data += '<td>' + value.away+'</td>';
for(i=0; i < value.Cases.length; i++){
console.log(value.Cases[i].CaseType + ' ' + value.Cases[i].CaseAway + ' ' + value.Cases[i].CaseHome);
if(value.Cases[i].CaseType === "Game"){
line_data += '<td>' + value.Cases[i].CaseAway +'</td>';
line_data += '<td>' + value.Cases[i].Total +'</td>';
line_data += '<td>' + value.Cases[i].Over +'</td>';
}
}
});
$('#table_lines').append(line_data);
});
}
On the line with this code "{, line}", I tried putting the key value from the json array, like {id: line}. What I want to do is to get a group of cases according to the key.
I would like to know how you do that. I want to change it according to the option value. I do get data from the server, but I get all the data. Here is how I call that function
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str = $( this ).val();
$.ajax({
method: "POST",
url: "../index.php",
data: { 'id' : str }
})
});
changeLinea(str);
})
.change();

add [and] + [or ] to search filter for a foreach generated list

So I already have a search filter in place but now I want it to have the ability to combine search phrases. Below is the code that generates a list on page.
<div class="sortable2">
<ul class="connectedSortable links loadfiles" id="loadfiles">
<?php
foreach ($result as $value) {
list($classname, $origin, $name) = explode('_', $value);
$classname = trim($classname, '[]');
$origin = trim($origin, '[]');
$name = pathinfo($name, PATHINFO_FILENAME);
echo "<li class='audiofile " . $name . " " . $classname . "' id='" . $value . "'>".
"<a class='btn_clone fa fa-clone' aria-hidden='true' id='' onclick='repeat(event)' title='Clone'> </a>".
"<a class='btn_addto fa fa-arrow-up' aria-hidden='true' id='' onclick='addto(event)' title='Add to playlist'> </a>".
"<a class='btn_removefrom fa fa-trash' aria-hidden='true' id='' onclick='removefrom(event)' title='Remove element'> </a>".
"<span class='audioclass'>" . $classname . "</span>".
"<a href='" . $directoryname . "/" . $value . "' target='_blank'>".
"<img src='images/avatars/" . $classname . ".jpg'>".
"<div class='audiotext'>".
"<span class='audiotitle'>" . $name . "</span>".
"<span class='audioorigin'>" . $origin . "</span>".
"</div>".
"</a>".
"</li>";
}
?>
</ul>
</div>
This list basically generates blocks like:
frank
hello how are you
link to audio file
william
i am fine
link to audio file
frank
what?
link to audio file
The filtering is done by this code
$('#global_filter').keyup(function() {
var col_name = $(this).attr('class');
var search_val = $(this).val().toLowerCase();
$('.' + col_name).closest('#loadfiles > li').css('display', 'none');
$('.' + col_name).each(function() {
var val = $(this).text();
console.log($(this).text(), 'text');
if(val.toLowerCase().indexOf(search_val) >= 0) {
$(this).closest('#loadfiles > li').css('display', 'block');
}
});
});
which works together with
<div class="input">
<h4>Search field</h4>
<div class="all_all" id="filter_global">
<div align="left"><input type="text" name="global_filter" id="global_filter" class="audiofile"></div>
<div align="left"><input type="checkbox" name="global_regex" id="global_regex" ></div>
<div align="left"><input type="checkbox" name="global_smart" id="global_smart" checked></div>
</div>
</div>
Question
How can I change the filter to allow for multiple searchphrases with [AND] and maybe also [OR] if possible. So the user can type in for instance:
frank [and] hello
and this will then return
frank
hello how are you
link to audio file
Although this project appears to have not been updated in quite some time, you can probably utilize parts of it to work for your needs: https://github.com/bloomtime/boolean-expression-js
$('#global_filter').keyup(function() {
// Init
var col_name = $(this).attr('class');
var search_val = $(this).val().toLowerCase();
// Setup boolean expression
var parsed = new Expression(search_val);
$('.' + col_name).closest('#loadfiles > li').css('display', 'none');
$('.' + col_name).each(function() {
var val = $(this).text();
if(parsed.test(val) == true) {
$(this).closest('#loadfiles > li').css('display', 'block');
}
});
});
It utilizes ReParse behind the scenes to be able to split your search on pre-defined grammar and then test for matching.
Edit
If you are really trying to keep it super simple, it may not be extremely flexible, but you could try this approach. This basically gives the ability to search using [AND] or using [OR] but not both. Could probably use some refactoring as I just quickly whipped it up.
$('#global_filter').keyup(function() {
// Init
var col_name = $(this).attr('class');
var search_val = $(this).val().toLowerCase();
var columns = $('.' + col_name);
// If doing a boolean AND
if (search_val.toLowerCase().indexOf('[and]') >= 0) {
// Get search parts
var parts = search_val.split('[and]');
$(columns).each(function(columnIndex, column) {
var val = $(column).text();
var matched = true;
$(parts).each(function(partIndex, part) {
// Since AND is inclusive, failing to match should assume this column is a non-match
if (val.toLowerCase().indexOf(part.toLowerCase()) < 0) {
matched = false;
// Break early
return false;
}
});
if (matched) {
$(column).closest('#loadfiles > li').css('display', 'block');
}
});
}
// If doing a boolean OR
else if (search_val.toLowerCase().indexOf('[or]') >= 0) {
// Get search parts
var parts = search_val.split('[or]');
$(columns).each(function(columnIndex, column) {
var val = $(column).text();
var matched = false;
$(parts).each(function(partIndex, part) {
// With OR, if ANY of the parts match then it is a match
if (val.toLowerCase().indexOf(part.toLowerCase()) >= 0) {
matched = true;
// Break early
return false;
}
});
if (matched) {
$(column).closest('#loadfiles > li').css('display', 'block');
}
});
} else {
var val = $(this).text();
if(val.toLowerCase().indexOf(search_val) >= 0) {
$(column).closest('#loadfiles > li').css('display', 'block');
}
}
});

Php/jquery: How to show value of array loaded elements from db with a loop?

I've written the following php code:
$query = mysql_query("SELECT * FROM utenti WHERE username = '$username'");
$query_db = mysql_query("SELECT * FROM utenti");
$i = 0;
$array_user = mysql_fetch_array($query);
$dati = array("str"=>array());
while ($array_db = mysql_fetch_array ($query_db)) {
if ($array_user[country] == $array_db[country]) {
if ($array_user[city] == $array_db[city]) {
if ($array_user[cap] == $array_db[cap]) {
if ($array_user[square] == $array_db[square]) {
$dati["str"]["n".$i] = "Nome ".$array_db[username];
$i++;
}
}
}
}
}
echo json_encode ($dati);
I want to load an array using elements from database during a loop:
$dati["str"]["n".$i] = "Nome ".$array_db[username];
and then to show index and value of this array after an Ajax request:
...
success:function(msg){
if(msg){
$.each(msg.str, function(key, value){
console.log(key + ": " + value);
});
}else{
$("#location").html('Not Available');
}
It doesn't work and I can't find the mistake. Could you help me, please?
Supposing your code
$.each(msg.str, function(key, value){
console.log(key + ": " + value);
});
works fine.
Then, your attempt $("#location").html(key + ": " + value); means that everytime contents of #location will be overwritten.
Instead, you can use append():
$.each(msg.str, function(key, value){
console.log(key + ": " + value);
$("#location").append(key + ": " + value);
});

How to get json object using php and mysql array

I am trying to get json data from php and when by using jquery json it show me undefined object. I don't know where is problem in my code. can any one help ?
Here is json code :
$("document").ready(function() {
$("body").css("background", "#ccc");
$(".sitebuttons").click(function() {
$("#subcat").html("");
$.getJSON("subcat.php", {catid: $(this).attr("id")}, function(data){
$.each(data, function(index, array) {
$("#subcat").append("<input type='button' class='subcat' id='" + data.subcat_id + "' value='"
+ data.subcat_name + "'></p>");
});
});
});
});
and Here is PHP Code
$select_subcat = mysql_query("SELECT * FROM wp_leadsubcat WHERE cat_id=" . $_GET['catid']);
$rows = array();
while ($result2 = mysql_fetch_assoc($select_subcat)) {
$rows[] = $result2;
}
echo json_encode($rows);
Please check screenshot here : http://imageshack.us/photo/my-images/560/screenshotqvl.png/
read documentation about jquery each.
in short jQuery.each( collection, callback(indexInArray, valueOfElement) )
index means index and valueOfElement means the current element from the collection. In your case row.
here is a fix.
$("document").ready(function() {
$("body").css("background", "#ccc");
$(".sitebuttons").click(function() {
$("#subcat").html("");
$.getJSON("subcat.php", {catid: $(this).attr("id")}, function(data){
$.each(data, function(index, row) {
$("#subcat").append(
"<input type='button' class='subcat' id='" + row.subcat_id + "' value='"+ row.subcat_name + "'>"
);
});
});
});
and the append part could be optimized like this (it's more readable as you can see)
$("#subcat").append($(
"<input/>"
, {
cssClass: 'subcat'
, id: row.subcat_id
, value: row.subcat_name
}
));
i think an index would solve the problem
$("#subcat").append("<input type='button' class='subcat' id='" + data[index].subcat_id + "' value='"
+ data[index].subcat_name + "'></p>");

how to get result from mysql and display using jquery when radio button is clicked?

I would like to make a bus seating plan. I have seating plan chart using javascript function.I have two radio button named Bus_1 and Bus_2 queried from databases. When I clicked one of radio button, I would like to get available seats to show on the seating plan. Problem is I can't write how to carry radio value and to show database result on seating plan. Please help me.
<SCRIPT type="text/javascript">
$(function () {
var settings = { rowCssPrefix: 'row-', colCssPrefix: 'col-', seatWidth: 35, seatHeight: 35, seatCss: 'seat', selectedSeatCss: 'selectedSeat', selectingSeatCss: 'selectingSeat' };
var init = function (reservedSeat) {
var str = [], seatNo, className;
var shaSeat = [1,5,9,13,17,21,25,29,33,37,41,'#',2,6,10,14,18,22,26,30,34,38,42,'#','$','$','$','$','$','$','$','$','$','$',43,'#',3,7,11,15,19,23,27,31,35,39,44,'#',4,8,12,16,20,24,28,32,36,40,45];
var spr=0;
var spc=0;
for (i = 0; i<shaSeat.length; i++) {
if(shaSeat[i]=='#') {
spr++;
spc=0;
}
else if(shaSeat[i]=='$') {
spc++;
}
else {
seatNo = shaSeat[i];
className = settings.seatCss + ' ' + settings.rowCssPrefix + spr.toString() + ' ' + settings.colCssPrefix + spc.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) { className += ' ' + settings.selectedSeatCss; }
str.push('<li class="' + className + '"' +'style="top:' + (spr * settings.seatHeight).toString() + 'px;left:' + (spc * settings.seatWidth).toString() + 'px">' +'<a title="' + seatNo + '">' + seatNo + '</a>' +'</li>');
spc++;
}
}
$('#place').html(str.join(''));
}; //case I: Show from starting //init();
//Case II: If already booked
var bookedSeats = [2,3,4,5]; //**I don't know how to get query result in this array.This is problem for me **
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
// ---- kmh-----
var label = $('#busprice');
var sprice = label.attr('pi');
//---- kmh ----
// var sprice= $("form.ss pri");
if ($(this).hasClass(settings.selectedSeatCss)){ alert('This seat is already reserved'); }
else {
$(this).toggleClass(settings.selectingSeatCss);
//--- sha ---
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
var selSeat = document.getElementById("selectedseat");
selSeat.value = str.join(',');
//var amount = document.getElementById("price");
// amount.value = sprice*str.length;
document.getElementById('price').innerHTML = sprice*str.length;
return true;
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () { // selected seat
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
alert(str.join(','));
})
});
</SCRIPT>
You can use the onclick to tell AJAX to get your information and then what to do with it using jQuery.
<input type="radio" name="radio" onclick="ajaxFunction()" />
function ajaxFunction()
{
$.ajax({
type: "POST",
url: "you_script_page.php",
data: "post_data=posted",
success: function(data) {
//YOUR JQUERY HERE
}
});
}
Data is not needed if you are not passing any variables.
I use jQuery's .load() function to grab in an external php page, with the output from the database on it.
//In your jQuery on the main page (better example below):
$('#divtoloadinto').load('ajax.php?bus=1');
// in the ajax.php page
<?php
if($_GET['bus']==1){
// query database here
$sql = "SELECT * FROM bus_seats WHERE bus = 1";
$qry = mysql_query($sql);
while ($row = mysql_fetch_assoc($qry)) {
// output the results in a div with echo
echo $row['seat_name_field'].'<br />';
// NOTE: .load() takes this HTML and loads it into the other page's div.
}
}
Then, just create a jQuery call like this for each time each radio button is clicked.
$('#radio1').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=1');
}
);
$('#radio2').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=2');
}
);

Categories