Best practise to display success in AJAX / HTML - html

I hava an Ajax function that GET all users information, and then pass it to the displayUser function.
In the displayUser function, i print it out in table with ID = displayUsers. This is working fine. But i now want to add more html code to this, without having a to dirty code. Does anyone have a good practice for this?
<script>
$(function () {
$.ajax({
type: 'GET',
url: '?page=getUserInfo',
dataType: 'json',
success: function(data) {
$.each(data, function(i, item){
displayUsers(item);
});
}
});
});
</script>
<script>
function displayUsers(item) {
var $displayUsers = $('#displayUsers');
$displayUsers.append('<tr><th>navn:</th><td>' + item.name + '</td><th>Brukernav:</th><td>' + item.username + '</td></tr>');
}
</script>

I have 2 thoughts. 1 what you are doing good and 2 what I can suggest (also brings in es2015 in discussion).
I see that you are creating an element and then appending it. It is really a good practice and is more performant because leads to less document repaint. You can extend this idea with more things like document.createElement. You can create 3 elements and then append them one by one to parent element. Although you may label it initially with bad looking code, it works great and is a good code.
You can also look into es2015 templates that supports multi line templates. Browsers have good support for it however I'm not sure if you do want to introduce es2015.

Related

Pass ajax result to HTML paragraph

I'm probably missing something very obvious since I'm not familiar with ajax and it's been years since I touched html but I have a fairly simple function that calls an API via POST
// Predict
$('#btn-predict').click(function () {
var form_data = new FormData($('#upload-file')[0]);
// Show loading animation
$(this).hide();
$('.loader').show();
// Make prediction by calling api /predict
$.ajax({
type: 'POST',
url: '/DiabeticRetinopathy',
data: form_data,
contentType: false,
cache: false,
processData: false,
async: true,
success: function (data) {
// Get and display the result
$('.loader').hide();
$('#result').fadeIn(600);
$('#result').text(data[0]);
console.log('Success!');
},
});
});
And I can see the result in the html if I give it it's own dedicated section like
<h3 id="result">
<span> </span>
</h3>
But it's an float and I just wanted something simple like appending it to the end of a static paragraph
<p>Model Predictive Probability:<div class="result"></div> </p> <-doesn't work
I'm fairly sure that I'm using the wrong syntax somewhere. I can get around it by changing the python script in the backend to actually return the string "Model Predictive Probability: (insert float here)" to the ajax function instead of just returning the float but the end result is going to have several floats all with different strings and there's no way that's the easiest way to go about it
EDIT: I used div class= instead of div id= like an dummy. div id works just fine

Json Table Sorting?

I have a table that populates prices from two apis. Unfortuantly this isn't sorted. Annoyingly. On each api however, it is sorted ^_^ So the issue i have is say site b is cheaper than site a. As it currenlty stands wouldn't work.
Heres my code. at the moment its just one api.
Forgot to mention, As it stands its site a ontop of site b in the same table. if there is a row thats cheaper tthen the row would have to move preferably.
Sam
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for(var i =0;i < json.results.length;i++) {
var title = json.results[i].section;
var price = json.results[i].price;
var href = json.results[i].quantity;
var button = "<button class='redirect-button' data-url='button link'>Link</button>";
$("#apple").append("<tbody><tr><td>"+title+"</td><td>"+href+"</td><td>"+price+"</td><td>"+button+"</td></tr></tbody>");
$("#apple").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
So (assuming I understand this correctly), you want to have the rendered data be sorted by price? Luckily, that's easy to do :).
Here's a js fiddle so you can experiement: http://jsfiddle.net/e9sdb91v/
Here's the basic code you need:
success: function (data) {
var json = data.sort(sorter);
// Rest of your code goes here
}
You need to obviously write the sorter function as well:
function sorter(a, b) {
return (a.price - b.price);
}
That's basically it, sorter can be as simple or complex as you like (this will sort your objects from low to high on price). Just sort, then render.
If you need further clarification, just post a comment :).
Note: This sorts the data before rendering, so it assumes you are starting from scratch each time, if you are trying to add rows dynamically into the correct place in the #apple div, then that'll be slightly different (and you'll need to amend your question).

Can't populate data with binding

This is my first try to make a single page application with HTML5. I'm using jquery, knockout and sammy.
Code: http://codepaste.net/apdrme
The problem is that I don't know what I'm doing wrong. I know it is the following:
this.get("#/", function() {
this.personList(this.persons);
});
But how else can I populate the list?
You could populate your list as follows:
function ViewModel() {
this.personList = ko.observableArray([{"name":"Josh"}, {"name":"Barry"}, {"name":"Mike"}]);
};
[...]
ko.applyBindings(new ViewModel());
Pay attention to use ko.observableArray() at the declaration. So, you could also remove the argument and call this.personList([{"name":"Josh"}, {"name":"Barry"}, {"name":"Mike"}]) in your main Sammy route and fill the list with other values in another route.
Another mistake is that you have used the with-binding that is not necessary here. Check the documentation about it.
You would normally use jQuery and an ajax call to populate personList. personList should be an ko.observableArray.
this.personList = ko.observableArray();
this.get("#/", function() {
$.ajax({url:"/api/persons/", dataType: 'json', success:function(persons){
this.personList(persons);
}});
});

Dynamically updated datalist won't show

I'm updating an html5 datalist dynamically, as the user types, with the following script:
$('#place').on('keyup', function() {
$.post('content/php/autocomp.php', { field: 'plaats', val: $('#place').val() }).done(function(response) {
$('#autocomp-places').html(response);
});
});
Which works fine except that the datalist often doesn't show right away. When I inspect the element the html is there but the datalist is not shown as soon as it's updated. How can I force it to show?
For the record: it works... I just wish it would always show the new suggestion right away.
Please use success instead of done method of ajax and try again.
$('#place').on('keyup', function () {
$.post('content/php/autocomp.php', {
field: 'plaats',
val: $('#place').val()
}).success(function (response) {
$('#autocomp-places').html(response);
});
});
I think I just have found a decent workaround for this!
Here is my pseudo-code:
As I type, I make async httprequests to get data.
When data is returned, i clear and re-populate the datalist.
If the current input field is still focused, manually call .focus() on the input element (this seems to force the data-list popup behavior to occur).
First, I would try to use one of already available solutions such as the jQuery UI autocomplete. It will shorten your development time and make the code free of typical bugs (not to mention getting the benefits from someone else work in the future).
If you really want to create your own version, I would make sure the list is cleared and repopulated with the following code:
$('#place').on('keyup', function() {
var posting = $.post('content/php/autocomp.php', { field: 'plaats', val: $('#place').val() });
posting.done(function(data) {
$('#autocomp-places').empty().append(data);
});
});

new to using the autocomplete with jquery

I am using the mvc pattern to pull in an autocomplete. I have searched around and apologize if this is a repeat question but I couldnt find my exact case which technically is very straighforward.
I have the following code:
<script type="text/javascript">
$(function() {
$( "#search" ).autocomplete({
source: "remote_bookmark.php?f=autocomplete",
minLength: 3,
select: function( event, ui ) {
ui.a.val;
ui.b.val;
ui.c.val;
ui.d.val;
}
});
});
</script>
this calls the remote page which calls a sql query in the model. The information is put into a multidimensional array that looks like the following in the model:
array_push($bookmark_array, array($row['a'],$row['b'], $row['c'], $row['d'], $row['e']));
I then echo the json_encode in the remote and after looking at the documentation still dont seem to follow how I am supposed to put the information in the select:
$( "#search" ).autocomplete({
source: "remote_bookmark.php?f=autocomplete",
minLength: 3
});
You do not need a select function unless you want to add extra functionality that is npt already there.
Just change your php to:
$bookmark_array = array($row['a'],$row['b'], $row['c'], $row['d'], $row['e']);
echo json_encode($bookmark_array);
And you should be all fine and dandy :-)