I'm trying to load data into the html5 canvas roulette which I found here:
http://www.switchonthecode.com/tutorials/creating-a-roulette-wheel-using-html5-canvas
I added another button called loader which will load the data from a php file. The data is an array of names. I then assigned it to the people array. Then called the drawRouletteWheel(). The drawRouletteWheel uses the data from the people array.
var people = [];
$('#loader').click(function(){
$.post('loader.php', function(data){
people = data;
drawRouletteWheel();
});
});
The loader.php file just loads random records fetched from mysql database:
$select_random = $db->get_results("SELECT people FROM tbl_people ORDER BY RAND() LIMIT 12");
if(!empty($select_random)){
foreach($select_random as $k=>$v){
$data[] = $v->people;
}
echo json_encode($data);
}
Something is actually being loaded into the roulette but it seems to be incomplete. And firebug is also returning something:
What do I need to do here?It seems like the data that was returned from the php file isn't being treated as an array.
The data that is returned from the php page is treated as a string, so you are getting individual letters as javascript gets the character at each index.
To fix this:
var people = [];
$('#loader').click(function(){
$.post('loader.php', function(data){
people = $.parseJSON(data);
drawRouletteWheel();
});
});
Related
i am tying to build an application where user can reorder items (and save the order to database). The items user is reordering are navigation links, which are generated dynamically on the page from php loop:
$nav_links.='<li class="collection-item ui-state-default item" data-ord="'.$navorder.'" data-url="'.$pageurlname.'"><a>' .$pagename. '</a></li>';}
$navorder is order of the page in the navigation
$pageurlname is string which is used to call the page dynamically (index.php?page=$pageurlname) and is unique key in the table.
I am using jqueryUi sortable funcion to make the process drag & drop, it is working fine and each time i reorder the links, the new order is updated to "data-ord".. the sript:
$('#sortable').sortable({
stop: function(event, ui){
$(".sortable li").each(function(i, el){
$(el).attr('data-ord',$(el).index()+1);
});
}
});
Now to the problem, which is my ajax script:
$(document).on('click','.saveorder',function(){
var neworder = $('.collection-item').attr('data-ord');
var pgurl = $('.collection-item').attr('data-url');
$.ajax({
type:'POST',
dataType:'text',
url:'/rs/pages/nav_order.php',
data: { neworder:neworder, pgurl:pgurl },
success: function(data) {console.log(data); $('#response').html(data);},
error: function(data) {console.log('Error!', data); }
});
});
I am new to ajax, so it is mostly build on scripts i found in other quiestions here. (I was able to succesfully implement cript link this to my other functions) however it is not working in this case. The problem seems to be that i am trying to post multiple data for multiple rows (At this time i have 4 links i am trying to reorder, but the link count can be more or less). When i tried to get values of variables "neworder" and "pgurl" (using alert), it always show only the values for the first item.
I have tried lot of solutions found in similar quiestion but none of them worked, simply because user were posting form data and then serialized it, which is not my case because i am not sending data from the form.
Lastly here is the nav_order.php (i guess it is wrong here too, probably need to add foreach but at first i need to have the ajax working correctly):
<?php
include "/rs/include/db.php";
$neworder = $_POST['neworder'];
$pgurl = $_POST['pgurl'];
$query = mysqli_query($Connection, "UPDATE horus_pages SET nav_order='$neworder' WHERE url_name='$pgurl'") or die (mysqli_error($Connection));
echo 'Reordered';
?>
Also when i check the console, there is no data.
So please can you tell me how to correct the ajax script to send the data for each object and then handle it correctly in the php script? Hope i described my problem clearly. Thank you for any help.
Put data-id="your_database_id" in your links html. Selecting them in your database with href, will be slow and bug things if there are multiple records with the same href.
You have save button which sends the order and href of the first link it finds? And what happens when multiple items change their order? If you have many links, you will be throwing hundreds of mysql updates for each save?
You should be better off sending json to your php. Something like that:
[{id:123, order: 332}, {id:124, order:334}, ... ]
dataType:'text' becomes dataType:'json'
If you don't care about scalability, then this will work on the backend.
$data = file_get_contents("php://input");
$links = json_decode($data, true);
foreach($links as $link) {
$order = intval($link['order']);
$id = intval($link['id'])
// UPDATE table SET `order` = '$order' WHERE id = '$id'
}
Btw. Your php code allows SQL injection. Thats bad
Perhaps you can make the order 'float' and make an algorithm which finds empty spot. This will allow you to reduce these 100's of SQL requests to 1.
I am trying to find the best method for passing a large array of IDs from one page to the next.
I've built a simple downloadable image site that allows users to select any number of images to download. Right now, when a user selects an image its ID is stored in a JSON string inside a cookie. The problem I've been having is finding the best way to pass the JSON to the review before downloading page.
Currently, I'm sending the JSON as a URL parameter but I'm not sure if this is the smartest solution since the number of IDs in the JSON could reach into the hundreds.
I've looked in PHP sessions but I don't really understand how can I enable the user ability to add/subtract from the variable once the page has been loaded.
$(function(){
$('.download_cart').click(function(){
var urlArray = [];
obj = JSON.parse(getCookie("downloads"));
if(obj != null){
if(obj.items.length !== 0){
$.each( obj.items, function( i, value ) {
urlArray.push(obj.items[i].id);
});
}
}
window.location = cart_url+'?array='+urlArray;
})
});
Try POSTing your data to the new PHP page:
var data = 'urlArray='+urlArray
$.ajax({
type: "POST",
url: 'new_php_page.php',
data: data
});
Now you'll be able to get your variable at $_POST['urlArray'] on your new page.
http://api.jquery.com/jQuery.post/
Consider to pass them in a set of ajax-requests, by 200 (for example, to not overflow input limit) IDs in each request.
Assign urlArray to a hidden field then submit the form, it can parse large no of array to another page
I'm using jquery UI auto completion to give the project name suggestion in a list. I'm providing a project name list as a json array from the php file as follows.
function getProjectList($projectList) {
foreach ($projectList as $project) {
$jsonArray[] = array('name' => $project['projectName'], 'id' => $project['projectId']);
}
$jsonString = json_encode($jsonArray);
return $jsonString;
}
And I'm geting the whole project name list to a javascript variable.
var projectsForAutoComplete=<?php echo $timesheetForm->getProjectListAsJson(); ?>;
This project list have more than 10000 projects and I'm have 20 project name text boxes which should provide the auto suggestions. So when I try to do it as follows at the load time the page get 30 seconds to get load due to higher procession of the js.
$(".project").autocomplete(projectsForAutoComplete, {
formatItem: function(item) {
var temp = $("<div/>").html(item.name).text();
return temp.replace("##", "");
}
,
matchContains:true
})
So I need to load the auto suggestions in the key press event as in the demo in the Jquery Documentation. http://jqueryui.com/demos/autocomplete/#remote-jsonp
But the example shows how to do it with a remote json source. Can I do the same with the local json array. Is it possible. Can someone help me on this.
If you already have the json array on the page then you can simply include it as a source
source: projectsForAutoComplete
However, autocomplete expects it's source to be a 1D array and your array is 2D. You'll either need to make two arrays, provide the one with the strings as the source, and write a function to map the name to the id, or do something similar to the combobox example in the jQueryUI autocomplete documentation.
I inserted the below command in
developer.yahoo.com/yql/console/
yql = select * from yahoo.finance.quotes where symbol in ("XAUUSD=X","XAGUSD=X")
but show all the datas which are not necessary to me.
XML Code Generated by Yahoo YQL and Json Code Generated by Yahoo YQL
i just want to pull out the Ask, Bid, AskRealtime, BidRealtime, LastTradeRealtimeWithTime, LastTradeWithTime, LastTradePriceOnly. By using php session, I want to insert the grabbed datas into html table/div in the same page.
Got no idea either XML would be easier to pull the data or Json. Which would be easier for me to grab the data of the fields and session it and paste it to the html table.
And also want the grabbed data to be streamable or auto refresh when datas are refreshed in yahoo ..
found this link
streamerapi.finance.yahoo.com but got no idea how to work
please help
i tried this but printed nothing
<script type='text/javascript'>
function forex(o){
var items = o.query.results.item;
var output = '';
var no_items=items.length;
for(var i=0;i<no_items;i++){
var Ask = items[i].Ask;
var AskRealtime = items[i].AskRealtime;
var BidRealtime = items[i].BidRealtime;
var LastTradeDate = items[i].LastTradeDate;
var LastTradePriceOnly = items[i].LastTradePriceOnly;
var LastTradeTime = items[i].LastTradeTime;
output += Ask + AskRealtime + BidRealtime + LastTradeDate + LastTradePriceOnly+ LastTradeTime;
+title + desc ;
}
// Place news stories in div tag
document.getElementById('results').innerHTML = output;
}
</head>
check out json_decode(); ! works perfectly.
$x = json_decode($json_string); // gives back an array
$x = json_decode($json_string, true); // gives back an object
this thing has helped me a lot of times...
Use
http://api.jquery.com/jQuery.getJSON/
and put it on a timer. If you log the response (console.log) you'll see its an object that you can traverse through to get what you want.
It needs to be a valid json too, so make sure it is with JSON Lint:
http://jsonlint.com/
If it isn't (i think usually people prefix valid jsons with strings) then you'll have to use PHP to get the json (file_get_contents or CURL) and chop up the response until it's a valid json.
I have a PHP page with an unordered list. I have a some jQuery code that waits for a user to click on one of the items in the list:
$(function() {
$('li.large_box').css('cursor', 'pointer')
.click(function() {
$('#db_sections').empty();
var show_id = this.id;
$.post('get_section_dates.php', { show_id: show_id }, function(sections) {
$('#section_dates_feedback').html(sections);
});
});
});
When a user clicks on one of these items the jQuery code sends it's id to a php script that makes a database query and builds a dropdown list with the results:
if (isset($_POST['show_id'])) {
$show_id = $_POST['show_id'];
$result = mysql_query("SELECT `id`,`air_date` FROM `daily_show` WHERE show_id = '".$show_id."'");
echo"<div id='dates_select'>";
echo "<select id='date_select'>";
echo "<option value='0'>Choose a date</option>";
while ($query = mysql_fetch_assoc($result))
{
$id = $query['id'];
$air_date = strtotime($query['air_date']);
$date = date("M-d-Y \(D\)",$air_date);
echo "<option value='$id'>$date</option>";
}
echo "</select>";
echo "</div>";
}
The first time I click on one of the list items everything works quickly and the dropdown box comes out correctly. The problem is, when I click on the next list item, the code takes a few seconds longer to build the new dropdown list in place of the old one. Each new click on a different list item compounds the time it takes to build the dropdown list until it takes more then a minute each time.
The database table that it's querying is only 12 records long, and generally it's only returning 1 or 2 rows at the most.
I'm new to PHP/jQuery and was wondering if there was anything blatantly obvious in my code slowing this process down.
Thanks for taking a look at my problem!
you should consider optimizing your transport method as well as your JS that handles it.
First of all, your scripts are building "fat" every click. that is, there are excessive jQuery calls. you can optimize it into this:
$(function() {
//put into reference static elements
$db_sections = $('#db_sections');
$section_dates_feedback = $('#section_dates_feedback');
//delegate event to parent handler using .on()
$('the_containing_ul').on('click', 'li.large_box', function() {
$db_sections.empty();
$.post('get_section_dates.php', {
show_id: this.id
}, function(data) {
//callback
});
});
});
as for your PHP reply, you should at least use JSON for transport and not HTML to make it light. you can use json_encode to turn a PHP array to a JSON string for transport.
if (isset($_POST['show_id'])) {
$show_id = $_POST['show_id'];
$result = mysql_query(query_here);
$resultArray = mysql_fetch_assoc($result)
//do a little formatting before we send over
while ($resultArray){
$resultArray['air_date'] = date("M-d-Y \(D\)",strtotime($resultArray['air_date']));
}
echo json_encode($resultArray);
}
this will print the following JSON string which is better than printing HTML:
[
{"id":"1","air_date":"January 1, 12"},
{"id":"2","air_date":"January 2, 12"},
{"id":"3","air_date":"January 3, 12"},
... and so on
]
now, in the POST request, jQuery intuitively converts it into a JSON object which we can parse. you can now use it to generate your selectbox. this will be the callback:
function(data) {
//create a select and div, and append it to a div
$div = $('<div id="dates_select" />');
$select = $('<select id="date_select" />').appendTo($div);
//create options based on data and append to select
$.each(data,function(index,row){
$('<option />')
.attr('value',row.id)
.text(row.air_date)
.appendTo($select);
}
//put div into the feedback
$section_dates_feedback.html($div);
}
Sounds like a multiple binding issue to me. Just a guess, but maybe you are adding the click function to the clickable item each time the POST returns. So, the next time you click, it's going to run the POST twice. Then three times. That's adding a new request each time as well as adding redundant DOM manipulations each time.
However, the code as it looks in the sample isn't showing obvious signs of having the click bound again. So even though I have a suggestion, it's sort of a shot in the dark.
(Side note: there's no reason to add the CSS via jQuery here. Just put this rule into your style sheet! I've eliminated it from the sample)
Now, I don't know your markup, so I'm going to play safe and use document as my suggested listener to help avoid multiple binding. Basically, the first selector in here is ideally an actual node that never gets destroyed as part of the Ajax call. It's rendered on first page load and then never rendered again. You might use $('#someContainer').on( /* ... */) for example. I'll just use document.
$(function() {
$(document).on('click', '.large_box', function() {
/* all the stuff that should happen on click */
});
});
Now here's the truly important thing that you SEEM to be doing in your sample but may not be. This document ready function must be fired only once when the page first loads. A true document ready function as it was intended to be. Don't put it inside any functions that might get fired.
Quick way to tell if it's being bound multiple times is to open Firebug or Webkit Developer Tools... you'll see the POST HTTP requests. If multiple are getting fired for one click, just figure out why it's being bound again.