JavaScript - Load Json Data With Php And Mysql
Hi,
I was going through this tutorial: http://www.electrictoolbox.com/json-...ery-php-mysql/ and I changed it round slightly, I would like the first select box to be Search by either Town or County - Having links would easier?! http://www.mypubspace.com/dashnew/ So, when a user selects Town, the PHP selects the Towns or if the user selects County, then show the Counties list I am currently getting the following error: $ is not defined [Break On This Error] $(document).ready(function() { here is my HTML Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <script language="javascript" type="text/javascript"> function populateFruitVariety() { $.getJSON('search-by.php', {fruitName:$('#fruitName').val()}, function(data) { var select = $('#fruitVariety'); var options = select.attr('options'); $('option', select).remove(); $.each(data, function(index, array) { options[options.length] = new Option(array['variety']); }); }); } $(document).ready(function() { populateFruitVariety(); $('#fruitName').change(function() { populateFruitVariety(); }); }); </script> </head> <body> <form> Search by: <select name="name" id="fruitName"> <option>Please Select</option> <option id="Town">Town</option> <option id="County">County</option> </select> Variety: <select name="variety" id="fruitVariety"> </select> </form> </body> </html> PHP Code: <?PHP $dsn = "mysql:host=xxx;dbname=[xxx]"; $username = "[xxx]"; $password = "[xxx]"; $pdo = new PDO($dsn, $username, $password); $rows = array(); if(isset($_GET['Town'])) { $stmt = $pdo->prepare("SELECT rsTown FROM pubs WHERE name = ?"); $stmt->execute(array($_GET['rsTown'])); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); } if(isset($_GET['County'])) { $stmt = $pdo->prepare("SELECT rsCounty FROM pubs WHERE name = ?"); $stmt->execute(array($_GET['rsCounty'])); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); } echo json_encode($rows); ?> Please help Similar TutorialsI am going through the example at the bottom of this page: http://api.jquery.com/jQuery.getJSON/ I am using the following code: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <script src="http://code.jquery.com/jquery-1.4.4.js"></script> </head> <body> <script> var id=$("#id").attr("value"); $.getJSON("json.php",{id:id},dates); function dates(datos) { $("#list").html("Town:"+datos[1].rsTown+"<br>"+"County:"+datos[1].rsCounty); } </script> <div id="id"></div> <div id="list"></div> </body> </html> and I'm trying to pull my JSON data from my PHP page: http://www.mypubspace.com/dashtest/json.php the JQuery seems to be doing something but nothing is being output to my screen?! project page http://www.mypubspace.com/dashtest/json.html Please help?! I think the `getJSON` should be taking the JSON URL and returning it as a response - The data file has `Author x3 Body x3 and Title x3`. Once it has this it should map it into the `nodes` and give me three nodes for each section of data. However currently its giving me the `console.log` output that I have below and nothing in my `nodes var` **Console Log:** Code: script.js:7 [Object, Object, Object]0: Object1: Object2: Objectlength: 3__proto__: Array[0] **Code:** Code: $(document).ready(function(){ var url = "assets/js/data.json"; $.getJSON(url).done(function(response) { var nodes = response.map(function(i) { return $('<div>').append( $('<div>', {class: 'title'}).text(i.title), $('<div>', {class: 'author'}).text(i.author), $('<div>', {class: 'body'}).text(i.body) ); console.log(response); }); }); });//Ready function closed Reply With Quote 01-08-2015, 10:56 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts The data file has `Author x3 Body x3 and Title x3`. Literally??? That is, it has something like Code: { Author: "Adam", Author: "Bob", Author: "Carol", Body: "Somethhing...", Body: "something else ...", Body: "more stuff...", Title: "Book one", Title: "Book two", Title: "Book three" } ??? I'm sure that's not what you meant, but what *DID* you mean? Why not simply copy/paste the contents of "data.json" to here? how can I load data onto a form using jquery/java?
Hello, I am trying to copy data from one element to another on page load. Below is the scenario: I want to copy the below data within each element <h2>Product Name</h2> <div class="price">$9.99</div> To the different parts of this URL <a href="https://myaccount.foxycart.com/cart?name=PRODUCT NAME&price=PRICE" class="foxycart">Add to Cart</a> Thank you in advance for your help. Hello, i would like to advise me on sthg. I have built a website using a)MySQL b)HTML c)PHP and d)Javascript. My website consists of basic html pages/templates which have links to the left and point to another templates/pages. For example, i have 4 templates in my site 1st template is for: News 2nd : Library 3nd : Articles 4th : E-shop Each template consists of 1. a small menu with links,every link points to another page 2.space for the content/text of the html page 3. a form for searching in the website using php and a mysql database. Well, i'm thinking of adding some animation in my website using the jquery library.Let's say we have an accordion which has 4 choices and when the user clicks on the first choice the 1st template(NEWS) appears inside the slide of accordion,loads in the same slide, not in a new page!!!This is what i would like to do, place in each slide of the accordion one of my templates. CAn this be done??? Which are the disadvantages of adding in each slide of the accordion a different template for my site and remain in the same slide when the user clicks in one of the links of the template??? Consider that i'm using dynamic content and not static, i have a MySQL database behind. Also,as i have seen in most examples the options of accordion usually contain an image, a content, a text or links which open in a new window or tab not inside the slide!!!These links do not load in the same slide!!i would like to have a template which loads in the slide each time the user clicks on a link of it. CAn this be done?? I would be glad if sm could advise me! Thanks, in advance!!! I have a very large json file, and inside of that json file is an array. I would like to use JavaScript to take that json as an argument, parse through the json and only take certain elements from it and put it into a new json file, below is an example of what I mean: Code: { "contextType": "Account", "preferences": null, "custodianCode": null, "data": [{ "id": "0", "account": "11111111", "field2": true, "field3": false, "field4": "BROK", "field5": "Broker", "field6": "1", "field7": "Cash" },{ "id": "1", "account": "222222222", "field2": true, "field3": false, "field4": "BROK", "field5": "Broker", "field6": "1", "field7": "Cash" }] } And I want to pull from that and get something like this as a new json Code: { "newArray": [{ "id": "0", "account": "11111111", "field2": true, "field3": false, "field4": "BROK", "field6": "1" },{ "id": "0", "account": "222222222", "field2": true, "field3": false, "field4": "BROK", "field6": "1" }] } Also the file is local to my computer and can be outputted locally as well, I am trying to use node.js and JavaScript this is what I have so far Code: var json = require('./simple.json'); var keeperFields = ["id", "account", "field2", "field3", "field4", "field6"]; var newJSON = {newArray: [] }; var i; var fields; for (i = 0; i < keeperFields.length; i++) { for (fields in json) { if (json.hasOwnProperty(keeperFields[i])) { newJSON.newArray.push(keeperFields[i]); } } } console.log(newJSON); This is just a small example the real json file is huge with thousands of lines. Any help or suggestions are appreciated! This current solution is giving me a console log of { newArray: []} instead of the expected result above I am trying to decide whether using a JavaScript-flatfile or a PHP-MySQL setup is the fastest for my application. The PHP-MySQL setup is really basic, just a very simple MySQL 5 database with only 3 columns or so. However, the JavaScript-flatfile is a solution I thought of that could work surprisingly well. Let's say I want to make a Google Suggest like application, but one that only works for single words, and only displays the most likely result and not the 10 most likely. If the user has partially enter the word "banana", by only typing "ban", the Javascipt will do some parsing, and send the user to a filesystem that has the destination "b/a/n/finish.txt". The finish.txt file would be in every one of these directories, and would contain the most likely ending, in this case "ana". Would this be fast, or does having all these directories slow the server down quite a bit? Would there be a faster way, or a more simple way? Thanks! Hi all Is there a way to get the image(s) to load into the table after the page has loaded instead of the way I have it now? I have 4 tabs, but I would like the imgs in tabs 2,3,4 to load after page load. Example of how the tabs look. Code: <div class="tabbertab"> <h2>Australia_____</h2> <table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFCC"> <caption class="highlight_Red">澳洲 Australia </caption> <tr> <td><a href="pages/promotion.html#aus_ACE" rel="nofollow" target="_blank"><img src="pages/images/Pics/AUS/ace.jpg" alt="ACE / ATTC" width="110" height="69" border="0" align="left" class="ozimg_L"/> ...a few more images etc the other tabs look the same. LT This script displays a link to a registration/login form that loads in a light box for Joomla. I've been goin nuts trying to figure out how to get this to load on page load with a delay. Anyone know how to get this done? PHP Code: <?php JHTML::_('behavior.mootools'); $document = JFactory::getDocument(); $document->addStyleSheet(JURI::base() . 'media/system/css/modal.css'); $document->addScript(JURI::base() . 'media/system/js/modal.js'); $document->addScriptDeclaration("window.addEvent('domready', function() {SqueezeBox.initialize({});});"); $user = & JFactory::getUser(); $uri = JFactory::getURI(); $url = $uri->toString(); $return = base64_encode($url); ?> <div id="lbframeid" style="position:absolute;top:1px;left:1px;height:0px;width:0px;overflow:hidden"> <a href="http://www.wowjoomla.com/"><h1>Joomla Login LightBox powered by WowJoomla.com</h1> </a> </div> <?php if ($user->get('guest')) :?> <a href="<?php echo JRoute::_('index.php?option=com_loginbox')?>" onclick="SqueezeBox.fromElement(this); return false;" rel="{handler: 'iframe', size: {x: 660, y: 500}}"><?php echo JText::_('SIGNUP_LOGIN')?></a> <?php else: ?> <?php echo JText::sprintf( 'HINAME', $user->get('name') ); ?> <br> <a href="javascript:void(0);" onclick="LB_onLogout(); return false;"><?php echo JText::_('LOGOUT')?></a> <?php endif; ?> <script type="text/javascript"> function LB_onLogout() { var form = new Element('form'); form.setProperty('method', 'POST'); form.setProperty('target', '_self'); form.setProperty('action', 'index.php'); var input = new Element('input'); input.setProperty('type', 'hidden'); input.setProperty('name', 'option'); input.setProperty('value', 'com_user'); form.appendChild(input); var input = new Element('input'); input.setProperty('type', 'hidden'); input.setProperty('name', 'task'); input.setProperty('value', 'logout'); form.appendChild(input); var input = new Element('input'); input.setProperty('type', 'hidden'); input.setProperty('name', 'return'); input.setProperty('value', '<?php echo $return; ?>'); form.appendChild(input); $E('body').appendChild(form); form.submit(); } </script> I have here a code that will automatically generate two text fields (Title & Price) when "Add another article" is pressed. I got this from the web, but I want instead of using a text field, I want it to create a drop down menu based on a mysql table, then update the price automatically (also based on the mysql table) on the other text field once a selection has been made on the drop down menu. Code: <link rel="stylesheet" type="text/css" media="screen" /> <style type="text/css"></style> <script type="text/javascript"> var elCount = 2; function add() { var parent = document.getElementById('parent'); var article = document.createElement('DIV'); article.id = 'article_' + elCount; article.name = 'article_' + elCount; // NEW LINE var article_title_label = document.createElement('LABEL'); article_title_label.appendChild(document.createTextNode('Title ' + elCount + ': ')); var article_title_text = document.createElement('INPUT'); article_title_text.id = 'article_' + elCount + '_title'; article_title_text.name = 'article_' + elCount + '_title'; // NEW LINE var article_textarea_label = document.createElement('LABEL'); article_textarea_label.appendChild(document.createTextNode('Price ' + elCount + ': ')); var article_textarea = document.createElement('INPUT'); article_textarea.id = 'article_' + elCount + '_price'; article_textarea.name = 'article_' + elCount + '_price'; // NEW LINE article.appendChild(article_title_label); article.appendChild(article_title_text); article.appendChild(article_textarea_label); article.appendChild(article_textarea); parent.appendChild(article); elCount++; } </script> <body> <div id="parent"> <div id="article_1"> <label for="article_1_title">Title 1: </label><input type="text" name="article_1_title" id="article_1_title" /> <label for="article_1_price">Price: </label><input type="text" name="article_1_price" id="article_1_price" /> </div> </div> any ideas? Thanks Hi guys, I am trying to insert the following call into my page; Code: <script type="text/javascript" defer="true"> $('#query').autocomplete({ serviceUrl:'service/autocomplete.ashx', minChars:1, delimiter: /(,|;)\s*/, // regex or character maxHeight:400, width:250, deferRequestBy: 0, //miliseconds params: { country:'Yes' }, //aditional parameters // local autosugest options: lookup: ['January', 'February', 'March', 'April', 'May'] //local lookup values }); </script> It works fine in all browsers except ie(6,7,8) Code: Internet Explorer can not open website. Operation Aborted. I understand it is caused by the jquery autocomplete function loading before the page / DOM has fully loaded. I tried adding Defer="true" to the script however this doesn't seem to work. Could someone please tell me what i must add to the script so that it loads after the dom has fully loaded? Thanks guys George I got no idea how to create a filter based on multiple drop menus to filter & sort data from php mysql query. Can anyone help me to write javascipt for this problem? My php mysql query as below:- mysql_select_db($database_winwin, $winwin); $query_rsMobile = "SELECT product_detail.product_Id, product_detail.product, product_detail.product_category, product_detail.product_brand, product_detail.product_name, product_detail.product_price, product_detail.thumbnail_url, product_detail.product_url, product_detail.product_status, product_detail.commission, product_detail.product_added_date FROM product_detail WHERE product_detail.product='Mobile Devices' AND product_detail.product_status='For sales'"; $rsMobile = mysql_query($query_rsMobile, $winwin) or die(mysql_error()); $row_rsMobile = mysql_fetch_assoc($rsMobile); $totalRows_rsMobile = mysql_num_rows($rsMobile); Whereby:- Product Brand: product_brand Product price: product_price Commission: commission Product name: product_name Product Thumbnail: thumbnail_url Product URL: product_url HTML for filters & sorter:- <div id="filters"> <form action="" method="post" name="form_filters" id="form_filters"> <table width="750" border="0"> <tr> <td>Brand:</td> <td><select name="productBrand" id="productBrand"> <option value="All Brands">All Brands</option> <option value="Sony Ericsson">Sony Ericsson</option> <option value="Samsung">Samsung</option> <option value="Nokia">Nokia</option> </select></td> <td>Price:</td> <td><select name="priceRange" id="priceRange"> <option value="All Price">All Price</option> <option value="Below RM1000">Below RM1000</option> <option value="RM1000-RM1999">RM1000-RM1999</option> <option value="RM2000 & Above">RM2000 & Above</option> </select></td> <td>Sort by:</td> <td><select name="productSort" id="productSort"> <option value="Sort By Name">Name</option> <option value="Sort By Price">Price</option> </select></td> <td><input name="Apply Filters" type="submit" value="Apply Filters"/></td> <td><input name="Reset Filters" type="Reset" value="Reset Filters"/></td> </tr> </table> </form> </div> Once user click on "Apply Filters" javascript has to sort list the product items. HTML for Pager (Value for total items, display some page numbers with hyperlink (1,2,3....10,11,12), hyperlink to previous page, hyperlink to next page) :- <div id="pager"> No. of items per page: <select name="NumOfItem" id="NumOfItem"> <option value="20">20</option> <option value="50">50</option> <option value="100">100</option> </select> Total Item: Pages ... Next... Previous </div> Javascript has to manage pager column. HTML for Product display:- <div id="product"> <div id="Thumbnail"> Here Javascript has to display Thumbnail image based on filters & sorter drop menus inputs. When click on this image page must redirect to "Product URL". </div> <div id="Price"> Here Javascript has to display "Price" based on filters & sorter drop menus inputs. When click on this "Price" page must redirect to "Product URL". </div> <div id="Commission"> Here Javascript has to display "Commission" image based on filters & sorter drop menus inputs. When click on this "Commission" page must redirect to "Product URL". </div> </div> Javascript has to repeat regions (<div id="product"></div>)based on "NumOfItem" drop menu (number of items display per page) and also update the pager column Hello all, I thought I'd share something that I don't see talked about much on the forums. I've been doing a bunch of AJAX development at work. We're really strapped for processing speed on our client (we build the machines our clients use) and therefore we've needed to find ways of speeding everything up. One of the things we decided on within the first week of our current project was to completely scrap XML in favor of JSON for sending data back and forth. JSON is JavaScript Object notation. Many of you have already seen it, it looks like this: Code: {'prop1' : 'someValue', 'prop9' : 5}; That defines an object with 2 properties, prop1 and prop9, with the respective values "someValue" and 5. Compare that to XML: Code: <obj> <prop1 value="someValue" type="String" /> <prop2 value="5" type="Integer" /> </obj> That's a bit more bloated, maybe not too noticeable, but the example is a small one. If you take large amounts of data, and multiple objects, XML can get incredibly bloated, and bloat on the wire slows down your app. That's the first reason we switched. The second reason we switched is that we save time on the processing. We all know what it's like to get at XML data. Import the document, get the node, get the value, get the next node, get the value. And building XML documents can take just as long: Create document, create root node, create node, create attribute node, set value, append child, repeat... All that processing for something so simple. JSON on the other hand is a subset of javascript, so check this out. Code: var data = "{'prop1':'someValue', 'prop2':5}"; var obj = eval("(" + data + ")"); alert(obj.prop1); // *** Alerts 'someValue' *** The string fits right into JavaScript in one function call. Granted, eval can be expensive, but if you test this out yourself, it's far cheaper than building and deconstructing XML in the JavaScript engine. There are 2 simple JSON parsing libraries that we use in development: JSON.php and json.js; these provide the necessary functions to serialize any PHP object into JSON, and serialize any JavaScript object into JSON. You can get them at the links below. We are also following the specification for JSON-RPC, defined in the last link below. We found this to be incredibly fast when compared to XML, and we haven't regretted it yet. Granted, we're not doing full blown web services where the the javascript modifies itself based on the service's self-definition, complete with namespaces and function signatures, but we transfer a lot of data quickly and efficiently to provide our users with the best experience possible. I recommend examining this further if you do AJAX development. Hopefully this helped somebody. http://json.org/ http://mike.teczno.com/json.html http://json-rpc.org/ And now for the "VS" part of this post: Anyone with experience in using both XML and JSON that wants to argue the mertis of either technique? I support JSON for almost all AJAX applications currently. I haven't found a good reason to use XML, and the negatives for using XML (bloat and processing speed) have currently knocked it completely from my "viable options" list. Anyone care to discuss? Hi I have some JSON strings and I want to embed it into my website. The problem is that I don't know how to parse JSON string data into html code. After a long search it seem that there is just a few references and manuals about JSON. Could someone explain to me how to use this function and also with as many examples as possible for understanding, how to put it into html page. Thank You I've been using the JSON.stringify method to convert my JSON object to a string to pass via AJAX but I've read now that it is not supported in most browsers. What then should I use?
All, Say I have the following code: Code: <!DOCTYPE html> <html> <head> <style>img{ height: 100px; float: left; }</style> <script src="http://code.jquery.com/jquery-1.7rc2.js"></script> </head> <body> <div id="images"> </div> <script> $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", { tags: "cat", tagmode: "any", format: "json" }, function(data) { $.each(data.items, function(i,item){ $("<img/>").attr("src", item.media.m).appendTo("#images"); if ( i == 3 ) return false; }); });</script> </body> </html> This came from the jQuery website. What I would like to do is change the link to something like this: https://graph.facebook.com/me/friend...ss_token=12345 The data that comes back is something like: Code: { "data": [ { "review_comment": "Here is a comment", "id": "12" }, { "review_comment": "Testing With more", "id": "34" }, { "review_comment": "Third comment", "id": "643" }, { "review_comment": "More Comments", "id": "120" }, { "review_comment": "Testing", "id": "3455" } ] } What I would like to do is basically read all of the review_comment tags and basically rotate these to display them on the webpage. So have "Here is a comment" be displayed for like 10 seconds and then fade out and have "Testing with More" fade in and be displayed for another 10 seconds etc. What is the best way to do this? I'm not sure how to change my JSON code above to acheive this. Would I need to basically put the comments in a div and then use jQuery to fade in the divs in and out? Any help you could provide would be greatly appreciated!! I am making a dynamic google map and need to pass in a JS Object that has latitude, longitude, address, name, and a link. The JS Object will be getting those values from a DB and may have up to 15 recordsets. I need to know how to separate that out into it's entities to include in the Map API regardless of how many recordsets there are.
hello i am using a json file to import some content into a div like this: Code: $.getJSON('json/main_profile.json', function(data) { $('#info_title').html( '<h1>' + "General Information " + '</h1>' ); }); but the problem appears when i try to replace the json file with a url, like this: Code: $.getJSON("http://interfaces-server.insource.local/users/145198", function(data) { $('#info_title').html( '<h1>' + "General Information " + '</h1>' ); }); why works with the file but not with the link?? thanks I'm trying to get a return of Code: [ ["red","green","blue"] ,["blue","red","green"] ] from a text file that contains Code: red,green,blue blue,red,green Using the following function Quote: Originally Posted by Old Pedant Code: function WRITE_FILE_AS_JSON(file) { fso = Server.CreateObject("Scripting.FileSystemObject"); myPath=Server.MapPath("timecards/" + file); if(!fso.FileExists(myPath))return; myfile = fso.OpenTextFile( myPath, read); var lines = myfile.readAll().split("\n"); Response.Write("[\n"); for ( var i = 0; i < lines.length; ++i ) { Response.Write(' ' + (i >0 ? ',' : '' ) + '["' + lines(i).replace(/\,/g,'","') + '"]\n'); } Response.Write("]\n"); myfile.Close(); Response.End(); } The darn thing keeps returning Quote: 500 (Internal Server) Error as a result of the line Response.Write(' ' + (i >0 ? ',' : '' ) + '["' + lines(i).replace(/\,/g,'","') + '"]\n'); And I don't know how to fix that line... hey guys im trying to create this script which will show array depending on what option has been selected on the select box...but the only thing being returned is "unidentified"....can anyone explain where i am going wrong please...thank you Code: <!DOCTYPE html> <html> <head> <script type="text/javascript" src="/ajax/jquery/libary/jquery.js"></script> </head> <body> <?php $game_type = array(); $division = array(); if ($_POST['game'] == 1) { $game_type[] = array('value' => '1', 'text' => 'TDM' ); $game_type[] = array('value' => '1', 'text' => 'CTF' ); $division[] = array('value' => '1', 'text' => 'Divison 1' ); } elseif ($_POST['game'] == 2) { $game_type[] = array('value' => '1', 'text' => 'CTF' ); $division[] = array('value' => '1', 'text' => 'Divison 2' ); } json_encode($game_type); json_encode($division); ?> <form> <script> $(document).ready(function(){ $("select#game").change(function(){ var post_string = "game=" + $(this).val(); $.ajax({ type: 'POST', data: post_string, cache: false, dataType: 'json', url: 'json.php', timeout: '2000', error: function() { alert("Error has occured"); }, success: function(data) { $.each(data, function(i, j){ var row = "<option value=\"" + j.value + "\">" + j.text + "</option>"; $(row).appendTo("select#sub_category"); }); } }); }); }); //$('#game_type').html('<input type=\"checkbox\" value=\"test\" /> TDM'); //$('#division').html('<input type=\"checkbox\" value=\"test\" /> Division 1'); </script> <select name="game" id="game"> <option value=""></option> <option value="1">Counter Strike</option> <option value="2">COD</option> </select> <div id="game_type"> </div> <div id="division"> </div> <select name="sub_category" id="sub_category"> <option value="">-- Select First Value --</option> </select> </form> </body> </html> |