Ajax call showing multiple records from database - javascript
I have an ajax call that looks like so;
success: function(data) {
//Return the results of the campaign data and populate the page.
$(data).find('campaign').each(function(i) {
campaignTitle = $(data).find('campaignTitle').text(),
campaignDesc = $(data).find('campaignDesc').text(),
campaignType = $(data).find('campaignType').text(),
campaignStatus = $(data).find('campaignStatus').text(),
campaignDuration = $(data).find('duration').text(),
campaignAuthor = $(data).find('whoCreated').text(),
campaignCreated = $(data).find('dateCreated').text(),
campaignTypeText = $(data).find('type').text(),
campaignDataID = $(data).find('typeID').text(),
campaignTypeName = $(data).find('typeName').text();
});
There are 2 records being returned but the only difference in the 2 is the Data ID which I get from a relational join in my table.
My page is a single "record" with campaign details on it.
For example, there is a title of the campaign.
$('[name=campaignTitle]').empty().append(campaignTitle);
Now because its returning multiple records, its duplicating the campaign title which I understand that it will do that.
Since all of the data is the same in the rows except the data ID's, I only need to show everything one time and then I would keep the multiple ID's that it returns and do something with them.
I am trying to do something like so :
campaignTitle = $(data).find('campaignTitle')[0].text(),
This returns undefined.
In short, I only want the campaign title to show one time, even if there are 5 records and I would do this by specifying which it as [0] since I know it would be the same as 1-4.
Why don't you return a DataSet or DataTable in your return and break down the value-pairs?
Related
Display Firebase data appended with jquery to a table in order
I am currently trying to append data through I pull from Firebase to a table in the order of newest to oldest posts. I currently have the following setup in my code base (simplified to address issue): var theDataRef = new Firebase('https://my-app.firebaseio.com'); theDataRef.orderByChild("timestamp").limitToLast(25).on('child_added', function (snapshot) { var message = snapshot.val(); displaytableRow(message.name, message.text); } function displaytableRow(name, message) { $("#sch").find('tbody > tr:first') .before($("<tr><td><div>" + name + ":" + message + "</div></td></tr>")) }; I have tried to create a table that displays newest to oldest data by using both firebase and jquery techniques but every time my data is displayed in a random order. I have a working timestamp field on every record in my data as well but even ordering by that does not solve the problem. Has anybody had any experience building this successfully? EDIT: The timestamp is gotten with the following code: var timestamp = Firebase.ServerValue.TIMESTAMP; And the database architecture is structured like so:
If you want to order your posts from newest to oldest you can do the following: 1/ Store a field in your post that is the inverse of the TimeStamp as follows: var tDate = new Date().getTime(); var postData = { //..... timestampInverted: (0 - tDate), //..... }; 2/ Query your posts ordered by this field as follows: theDataRef.orderByChild("timestampInverted").limitToLast(25).once('value', function(snapshot) { snapshot.forEach(function(childSnapshot) { displaytableRow(childSnapshot.val().name, childSnapshot.val().text); }); }); It is important to note that theDataRef.orderByChild("timestampInverted").limitToLast(25) returns a Query, which returns a DataSnapshot : Therefore you need to use snapshot.forEach() (see doc here) to iterate over the different posts items. Also note that "even when there is only a single match for the query, the snapshot is still a list; it just contains a single item. To access the item, you always need to loop over the snapshot".
Dynamic Dropdown from Mongo
I have a mongoDB with a DB = Staff and a collection = records. It contains a list of employees, and one of the fields is workgroup and it has items like "management", "union", "support staff", etc. I want to populate a dropdown list with the values of the workgroup field and then use it to retrieve all records from the specified value selected in the dropdown. I am using Ruby and I can retrieve the values ok (I can see them in the console), but they do not populate the dropdown list. This is my Ruby statement: get '/workgroup' do Record.all.to_a.collect(&:workgroup).uniq.to_json end My attempt at the javascript is: <script> //var json = 'http://localhost:4567/api/v1/workgroup'; $(document).ready(function() { $.getJSON("/api/v1/workgroup",function(obj) { $.each(json.records,function(key,value) { var option = $('<option />').val(value.workgroup); $("#dropDownDest").append(option); }) }) }); </script> Once I get the information in the dropdown, I want to use it to return all records with that workgroup value to a table. I haven't figured that part out yet. One step at a time! Thanks!!
Within your $.getJSON call back you are referencing json.records, but there is no json variable or object. The argument you are passing to the callback is obj. I think you really want to be doing $.each(obj, function(key, value)...
Filter a SharePoint list via dynamic checkboxes instantly (with C# and/or Ajax)
I'm currently looking for a way to add a filter function to a list in SharePoint, which filters the lists content via checkbox selection. This little mockup might help to understand what I'm talking about: The idea is to have a normal SharePoint custom list on the right and a checkboxlist on the left side, which will be generated dynamically from the content of the list -> One column is a "filter group" and all the field contents are the filter values. When selecting one or multiple values on the left side, the items in the list should instantly be filtered accordingly (ajax, without reloading the page). For example in the mockup, selecting "New York" and "Blue" would only show the item "Steve's Car". You now, like a product filter in almost every online shop and so on. How can that be achieved? Would be awesome if this could be included in my solution package (which includes other stuff in C#/jQuery already). I'm new to frontend customization in SharePoint, but I'm sure there's a way :-) Edit: I'm using SP2016 by the way.
Pandora! As i understand it, your first question is how you can dinamically get values for left side filter. I see there two ways: first way, you can build caml query and get items from list; second way, you can use ctx.ListData, which sharepoint initialize by itself and in ctx.ListData.Row (array of items) process items and get unique field values. Note, that ctx.ListData.Row contains only items loaded in list view on the page. For list filtration you can concat filter link for hash of the page. Example: "?List={ListID}&View={ViewID}&FilterField1=Color-FilterValue1=Blue". Try to filter columns on list and you will see url modification. ListID and ViewId you can retrieve by ctx.listName and ctx.view. And then pass it in function MyRefreshPageToEx. List will be filtered. More list filtration info function FilterList(){ var tableId = $(".ms-listviewtable").attr("id"); var filterUrl = "?List={ListID}&View={ViewID}&FilterField1=Color-FilterValue1=Blue"; MyRefreshPageToEx(tableId, filterUrl, false); } function MyRefreshPageToEx(lvTableID, url, bForceSubmit) { var tblv = document.getElementById(lvTableID); var clvp = CLVPFromCtx(tblv); if (clvp != null && clvp.ctx.IsClientRendering) { clvp.RefreshPaging(url); clvp.ctx.queryString = url; if ((typeof clvp.ctx.operationType == "undefined" || clvp.ctx.operationType == SPListOperationType.Default) && Boolean(clvp.ctx.ListData)) { var fromPage = clvp.ctx.ListData.FirstRow - 1; var toPage = Number(GetUrlKeyValue("PageFirstRow", false, url)); if (!isNaN(fromPage) && !isNaN(toPage) && fromPage != toPage) fromPage < toPage ? (clvp.ctx.operationType = SPListOperationType.PagingRight) : (clvp.ctx.operationType = SPListOperationType.PagingLeft); } } else { SubmitFormPost(url, bForceSubmit); } }
Delete fails to remove a JSON object
I do have the contents of html tables stored in a database and I use jQuery to extract the data from it and place it in another table by creating JSON objects from these tables. I get the stored table and append it to the DOM as follow: $('#divfortable).append(storedtable); The next step is to create my object : var tableObject = $('# divfortable tbody tr').map(function(i) { var row = {}; $(this).find('td').each(function(i) { var rowName = columns[i]; row[rowName] = $(this).text().trim(); }); return row; }).get(); where I have an existing array with the relevant column names. The next step is to upload these details to the server: data = { id: id, tableObject: tableObject }; $.ajax({ dataType: 'json', url:'my_url', data: $.param(data), error: function(jqXHR, textStatus, errorThrown) { }, success: function(data) { } }); It works fine and I am very happy with the results but my problem is when repeating the process on another table. I want to get a new table and extract its contents in a similar fashion but I cannot get rid of the previous result. The result contains the newly loaded table plus that of the previous table and if I repeat it once again, it contains the result of all 3 tables! It is obvious to me that I must empty all objects and DOM elements from the previous extraction but I tried different ways, to no avail. I gathered from searching the internet and this forum that you can use delete or empty to destroy the tableObject so that you can create a brand new one, but it does not do the job. I tried the following: delete tableObject; and $('#divfortable).remove(storedtable); in the success function, together and separately I also used $('#divfortable).remove(storedtable); after I created my data object data = { id: id, tableObject: tableObject }; but in this case the script does not progress to the ajax call, but by displaying $('#divfortable) it displayed both tables! How can I get rid of the previous result?
You should be able to simply clear the current #divfortable before the second operation: $('#divfortable').empty();
Too much JSON crashes browser :(
I have an ajax country/city selector. When I select United States the browser crashes. Doh! I have a dropdown list of countries. When I select a country a jQuery ajax call is run which gets a JSON response of cities belonging to that country. I should have seen it coming when I had to increase my allowed memory during execution. Here's the JSON response from selecting the UK. {"5947":"Aberdeen","12838":"Aberystwyth","15707":"Aldershot","18575":"Alsagers Bank","18682":"Altrincham","4863":"Andover","41802":"AOL","6471":"Armagh","18945":"Ascot","4864":"Ashby-de-la-Zouch","4865":"Ashford","5948":"Aviemore","12985":"Aylesbury","12281":"Ballymena","14446":"Banbury","12445":"Bangor","13631":"Barking","4866":"Barnet","17004":"Barnsley","16423":"Barrow-in-Furness","16254":"Basildon","12402":"Basingstoke","5826":"Bath","13289":"Beddgelert","15082":"Bedford","4868":"Belfast","4869":"Belper","13874":"Benfleet","5827":"Benson","15514":"Berkhamsted","4870":"Berwick Upon Tweed","12948":"Betws-y-Coed","18776":"Bexley","14530":"Bicester","4871":"Billericay","18436":"Birkenhead","4872":"Birmingham","14592":"Blackburn","14686":"Blackpool","12526":"Bolton","12480":"Bournemouth","13062":"Bracknell","18772":"Bradford","4873":"Braemar","4874":"Brecon","4875":"Brentwood","18820":"Brighton","14260":"Bristol","4876":"Broomfield","42004":"Burgess Hill","14654":"Burnley","4877":"Burton Upon Tren","13812":"Bury","15835":"Bury St Edmunds","16500":"Camberley","4878":"Cambridge","4879":"Canterbury","5957":"Cardiff","14443":"Carlisle","14065":"Carrickfergus","42384":"Chalgrove","5832":"Chatham","13641":"Chelmsford","4880":"Cheltenham","4881":"Chester","42879":"Chesterfield","12160":"Chichester","41768":"Chorley","14056":"Church Stretton","5949":"Cladich","4884":"Colchester","16204":"Congleton","17534":"Coniston","42888":"Corsham","4885":"Coventry","13575":"Crawley","15410":"Crewe","13913":"Croydon","4886":"Cumbernauld","13711":"Dartford","4887":"Dartmouth","5833":"Derby","17468":"Derry","4889":"Doncaster","13696":"Dorchester","15377":"Dorking","5834":"Dover","16659":"Dudley","41867":"Dumbarton","18091":"Dumfries","4890":"Dunbar","14217":"Dunblane","4891":"Dundee","14067":"Dunfermline","4892":"Durham","16058":"East Molesey","17521":"East Preston","12501":"Eastbourne","12374":"Eastrea","4893":"Edinburgh","18992":"Elgin","41763":"Ellesmere","12883":"Ely","16825":"Enfield","14510":"Epsom","5835":"Exeter","4894":"Falkirk","5836":"Falmouth","42388":"Faringdon","42034":"Farmington","14604":"Farnham","42347":"Feltham","12829":"Fleet","4895":"Forres","42315":"Frosterley","5950":"Glasgow","4896":"Glastonbury","12562":"Gloucester","15956":"Gosport","4898":"Grangemouth","12626":"Gravesend","16057":"Grays","4899":"Great Wilbraham","4900":"Greenock","12752":"Grimsby","11747":"Guildford","14506":"Guilford","11938":"Halifax","5010":"Hamilton","15553":"Harlow","41733":"Harpenden","14713":"Harrow","4902":"Hartlepool","18952":"Haslemere","13977":"Hastings","14917":"Hatfield","12529":"Haverfordwest","4903":"Haverhill","4904":"Hawarden","5951":"Hawick","11776":"Hemel Hempstead","15302":"Hereford","14999":"Hertford","41893":"Heston","16056":"Hexham","13019":"High Wycombe","13643":"Hoddesdon","5958":"Holyhead","12420":"Hornchurch","14160":"Horsham","12108":"Huddersfield","5837":"Hull End","13296":"Huntingdon","14801":"Hyde","17707":"Ilford","41721":"Inverkeithing","4905":"Inverness","5838":"Ipswich","4906":"Keighley","4907":"Kelso","18628":"Kendal","17805":"Kenilworth","4908":"Kennet","4909":"Kettering","18578":"Kidsgrove","18984":"Kilmarnock","4910":"Kingston Upon Hull","5952":"Kirkwall","18257":"Lakenheath","15425":"Lampeter","13182":"Lancaster","4911":"Laughton","13488":"Leamington","18824":"Leeds","13135":"Leek","17849":"Leicester","17716":"Leigh","12836":"Lerwick","13387":"Letchworth","4912":"Lewes","41767":"Leyland","13546":"Lichfield","5840":"Lincoln","19039":"Little Chalfont","16778":"Liverpool","13442":"Llandrindod Well","5953":"Loch Ness","12008":"London","15035":"Loughborough","15518":"Loughgall","15011":"Louth","18492":"Lowestoft","14023":"Luton","4913":"Machynlleth","12416":"Maidenhead","12230":"Maidstone","14722":"Manchester","4914":"Mansfield","4915":"Margate","4916":"Marlborough","17889":"Marlow","18870":"Melborne","16170":"Melton Mowbray","4917":"Merton","5844":"Middlesbrough","5959":"Milford","15181":"Millom","12315":"Milton Keynes","12089":"Mold","18816":"Montrose","5954":"Motherwell","18574":"Nantwich","4918":"Newark","17097":"Newbury","5845":"Newcastle","4919":"Newcastle Upon Tyne","19040":"Newport","41682":"Newquay","13629":"Northallerton","4922":"Northampton","18577":"Northwich","42209":"northwold","15080":"Norwich","5847":"Nottingham","4923":"Oban","11975":"Oldham","6474":"Omagh","17161":"Oxford","15422":"Oxshott","18627":"Penrith","4925":"Penzance","16404":"Perth","5848":"Peterborough","4926":"Plains","4927":"Plymouth","15551":"Pontypridd","14208":"Poole","4928":"Portsmouth","17642":"Portstewart","41766":"Preston","5011":"Prestwick","18579":"Radway Green","42069":"Ramsgate","11775":"Reading","14706":"Redditch","16276":"Ringwood","15522":"Ripon","14673":"Rochester","15968":"Romford","41857":"Rugby","15289":"Runcorn","17520":"Rustington","14052":"Saint Albans","16462":"Salford","4931":"Salisbury","42295":"Sandwich","17690":"Sandy","4932":"Scarborough","13975":"Seaford","12003":"Shaftesbury","18891":"Sheffield","5850":"Shrewsbury","13178":"Slough","14708":"Solihull","4935":"Southampton","4936":"Southborough","14524":"Southend-on-Sea","13970":"Southport","42260":"St Albans","5955":"St Andrews","15841":"St Asaph","18576":"St Helens","16114":"St Ives","12717":"Stafford","41746":"Staines","14051":"Stanmore","16656":"Stansted","42032":"Stevenage","5012":"Stirling","11801":"Stockport","14198":"Stockton-on-Tees","4937":"Stoke On Trent","42386":"Stranraer","4938":"Stratford-Upon-Avon","4939":"Stroud","18615":"Sudbury","11860":"Sunderland","16393":"Sutton","5960":"Swansea","12853":"Swindon","4941":"Taunton","5851":"Teeside","13973":"Telford","4943":"Truro","17702":"Virginia Water","5852":"Waddington","12059":"Wakefield","4945":"Wallingford","4947":"Wareham","5853":"Warrington","4948":"Warwick","4949":"Watford","12009":"Wellingborough","12528":"Wellington","13366":"Wells","12530":"Welwyn Garden City","16785":"Weston Under Lizard","16334":"Wetherby","18171":"Weymouth","4950":"Whitby","13308":"Whitehaven","42387":"Whitehead","5956":"Wick","17581":"Wilmslow","5854":"Wimbledon","12524":"Wimborne Minster","12551":"Winchester","15946":"Windsor","18573":"Winsford","4952":"Wisbech","4953":"Wisborough Green","12982":"Woking","18769":"Wokingham","13287":"Wolverhampton","17904":"Woodford","18086":"Woolavington","11783":"Worcester","12128":"Worthing","5961":"Wrexham","13630":"Yarm","17015":"Yeovil","11824":"York"} Here is my Javascipt: $('#current-country').change(function(){ //any select change on the dropdown with id country trigger this code $('.select-current-city').show(); $("#current-cities > option").remove(); //first of all clear select items var country_id = $('#current-country').val(); // here we are taking country id of the selected one. $.ajax({ type: "POST", url: "<?php echo base_url()?>map/get_cities/"+country_id, //here we are calling our user controller and get_cities method with the country_id success: function(cities) //we're calling the response json array 'cities' { $.each(cities,function(id,city) //here we're doing a foeach loop round each city with id as the key and city as the value { var opt = $('<option />'); // here we're creating a new select option with for each city opt.val(id); opt.text(city); $('#current-cities').append(opt); //here we will append these new select options to a dropdown with the id 'cities' }); } }); }); Has anyone any suggestions on how I can process this much data in the browser? I'm using PHP (Codeigniter), MySQL and jQuery.
I would recommend creating an array of your new option nodes, and then appending them en masse. Doing them one at a time may be what's killing you. var newOptions = []; $.each(cities,function(id,city) { var opt = $('<option />', { "val": id, "text": city }); newOptions.push(opt[0]); //need to push actual dom node - thanks RightSaidFred }); $('#current-cities').append(newOptions); Or should this be clearing previous options in the dropdown? If so: $('#current-cities').html(newOptions);
First double check you are not making the same AJAX request more than once. A quick and easy solution would be to split your AJAX requests in more than one. Start by dividing it into two, and if that still isn't enough, divide them by 3 or more. You can then check which JSON size is the right one for you, and use that one. Or you can have your php determine how much requests are needed based on the number of total cities. For really large lists, I had to split the requests into 100 items each. The first request I would get the first piece of list along with a bit of data indicating how much requests I had to make to obtain the full list, append the new nodes, then I would make the remaining requests, until I got the full list.
I don't see how that would crash for you. Here I am doing the worst possible thing and it is blazing fast: http://jsfiddle.net/HZnYQ/ Each time you select something, I remove all elements one by one and then append them one by one, and it's still instant. Actually my CPU doesn't even make a note of it.