Losing formatting on reload of data on AJAX call - javascript

I am having an issue when I reload the jstree with data from my AJAX call. So on load it works fine, but adding data, and getting a response back the tree loses its structure
Initial html is an empty div, data is updated on button click using ajax
<div id="pnlTree">
<div id="jstree" style="text-align: left">
</div>
</div>
success: function (data)
{
if( data )
{
var output = '<ul class="appointmentlist">';
$.each(data, function(key, val){
output += "<li id='"+data[key].data1+"' name='dtpurchase'"+counter+"' value='" + data[key].data2 + "'>" +dtdata + "</li>";
//output += '<a id="dtappointment" name="dtpurchase" value="' + data[key].data3 + '"'+ '>'+data[key].purchase_date + '</a>';
//output += '</li>';
counter++;
});
output += '</ul>';
$('#jstree').html(output);
}
},
I have tried refreshing, reloading but nothing seems to fix the issue.

Soooo what you need to do is to refresh() the tree after you updated the data.
Now this works only if you append the date to the element with $("#jstree").jstree(true).settings.core.data = output. If you use $('#jstree').html(output) then it doesn't work
Run the snippets to see it in action:
Working:
$('#jstree').jstree()
function update() {
var output = `<ul><li>New Item</li></ul>`
$("#jstree").jstree(true).settings.core.data = output
$('#jstree').jstree(true).refresh();
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<div id="jstree">
<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
</div>
<button onclick="update()">Update data</button>
Okay, so this second one is working with AJAX. It doesn't work in the Stack Overflow sandbox, but it does work on a normal HTML page (see screenshots). It's the exact same concept, you just need to apply it in the right order:
$('#jstree').jstree()
function update() {
$.ajax({
url: "https://swapi.dev/api/people/1",
success: function(data){
var output = `<ul>
<li>${data.name}</li>
<li>${data.eye_color}</li>
<li>${data.height}</li>
</ul>`
$("#jstree").jstree(true).settings.core.data = output
$('#jstree').jstree(true).refresh();
}
});
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<div id="jstree">
<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
</div>
<button onclick="update()">Update data</button>

Related

Ajax and PHP debug

Building a script that once a date is selected in a datepicker calendar, it uses ajax to post the selected date in a php script;
in the success of that ajax call, it uses another ajax call to post the same selected date to another php script and displays that in the page.
Did some research around and this seemed to be the best solution for what I try to do.
The script is the following:
<script> //for the events
jQuery(function($) {
$(".date").datepicker({
onSelect: function(dateText) {
display("Selected date: " + dateText + "; input's current value: " + this.value);
$(this).change();
}
}).on("change", function() {
display("Got change event from field");
// call next ajax function
var mydate = this.value;
$.ajax({
type: "POST",
url: 'boxes_script.php',
data: ({dates: mydate}),
dataType : 'html',
success: function(data) {
$('.caixas').html(data);
alert(data);
$.ajax({
type: "POST",
url: 'events_script.php',
data: ({dates1: mydate}),
dataType : 'html',
success: function(data) {
$('.results-ajax').html(data);
alert(data);
}
});
}
});
});
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
</script>
This is the code being used atm. Got some updates because of the feedback given here, but the solution still hasn't worked 100%
There's a problem on it and I think it's because the second Ajax call is inside of a success Ajax.
The problem is the following:
The data is being posted in the php scripts, which run like how they should.
The array gets populated with the right information.
The
$('.caixas').html(data);
works fine and displays data from 'boxes_script.php' there.
The
$('.results-ajax').html(data);
receives 100% of the data being sent from 'events_script.php' but for any weird reason, doesn't append it to the page..
I can see the data in alert messages and it's the right data being sent to the browser.
Why isn't that data being appended to the page?
This is the php code for 'events_script.php':
<?php
include 'config/config.php';
include 'libraries/database.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
print_r($_POST);
echo $_POST[dates1];
$dias= $_POST[dates1];
$mysql_date = date('Y-m-d', strtotime($dias));
echo $mysql_date;
//Make database query
$sql = "***";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$image = $row['Company_Logo'];
$myArray = json_decode($image, true);
$event=$row['eventID'];
echo '<div class="tab-pane" role="tabpanel">
<div id="'.$dias.'" class="container day-events">
<div class="row event-list">
<div class="event-list-time col-md-3 col-sm-3 center" style="background-image:url('.$myImage = $myArray[0]['name'].');">
<p class="event-list-start-time">'.$row['Start_Date'].'</p>
<hr class="event-list-time-divider">
<p class="event-list-end-time">'.$row['End_Date'].'</p>
</div>
<div class="event-list-info col-md-9 col-sm-9">
<h2 class="event-list-name">'.$row['Event_Name'].'</h2>
<p>Organized by <span class="event-list-organizer">'.$row['Company_Name'].'</span></p>
<p class="event-list-description">'.$row['Event_Description'].'</p>
<button type="button" class="btn more-info-list">More Information</button>
</div>
</div>
</div>
</div>';
}} else { echo 'No results found.'; }
}
?>
Note: no errors were found in the error log. The network gives status 200.
The data can be seen sent to the browser here:
The first part of the data is being appended to the browser, as you can see in the images.
Why is not working everything?
This was what fixed the problem and made the following final result:
Old:
<div class="row events-tabs">
<div class="container" data-example-id="togglable-tabs">
<ul class="nav nav-pills center caixas" id="myTabs" role="tablist">
</ul>
<div class="results-ajax tab-content" id="myTabContent">
</div>
</div>
</div>
New:
<div class="row events-tabs">
<div class="container" data-example-id="togglable-tabs">
<ul class="nav nav-pills center caixas" id="myTabs" role="tablist">
</ul>
<div class="tab-content" id="myTabContent">
<div class="results-ajax"></div>
</div>
</div>
</div>
So, basically using results-ajax as class of an own div fixed the problem.
Change
data1: ({dates1: this.value})
to
data: ({dates1: this.value})
var mydate = this.value; // add before the 1st ajax call
change -
data1: ({dates1: mydate})

Creating a search query using JSON news api

So I got to create a search query based on an written javascript file (below) and I also have to use this URL to create the search query. At the end of the URL, you can add any search term you like. For example, we will search about food : https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=food
Can anyone tell me what to do to create it?
$(document).bind('pageinit', function(ev){
$('#search').on('keyup', function(e){
if(e.keyCode == 13){
$.get('search.php', {"q": $('#search').val()}, function(data){
var json = JSON.parse(data);
console.log(json);
$('#results').listview('refresh');
});
}
});
First:
You can access this api direct with javascript (jquery).
If you try it with the normal url https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=food you get an error because of the "Access-Control-Allow-Origin" Settings.
If you append "&callback=?" you will get proper data returned
Now you have to append the returned data to your listview.
The important thing to know is: what is returned. In your code the value of data or the value of var json Since you dont provide any of your php. i can only do it direct with the jquery getJSON Call.
$(document).bind('pageinit', function(ev) {
$('#search').on('keyup', function(e) {
if (e.keyCode == 13) {
// The Base URL
var baseUrl = 'https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=';
// The question from the inputfield
var q = $('#search').val();
// putting the url togehter and append &callback=?
var url = baseUrl + q + "&callback=?";
console.log(url);
// Call The API for a JSON
$.getJSON(url, function() {
console.log("success");
}).done(function(data) {
console.log("second success");
console.log(data.responseData.results);
// create a var for the results and append a header
var results = '<li data-role="list-divider">Results</li>';
$.each(data.responseData.results, function(index, item) {
results += '<li>';
results += item.title;
results += '</li>';
});
// clear the results . append the results .refresh the listview
$('#results').empty().append(results).listview('refresh');
}).fail(function() {
console.log("error");
}).always(function() {
console.log("always");
});
}
});
});
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- jQuery Mobile -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<!-- page1 -->
<div data-role="page" id="page1" data-title="page1">
<!-- Header -->
<div data-role="header" data-position="fixed">
<h1>Page 1</h1>
</div>
<!-- /Header -->
<!-- Content -->
<div role="main" class="ui-content">
<label for="search">Search Input:</label>
<input name="search" id="search" value="" placeholder="palceholder" type="search">
<ul data-role="listview" id="results" data-inset="true">
</ul>
<script>
</script>
</div>
<!-- /Content -->
</div>
<!-- /page1 -->
$(document).bind('pageinit', function(ev) {
$('#search').on('keyup', function(e) {
if (e.keyCode == 13) {
// The Base URL
var baseUrl = 'https://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=';
// The question from the inputfield
var q = $('#search').val();
// putting the url togehter and append &callback=?
var url = baseUrl + q + "&callback=?";
console.log(url);
// Call The API for a JSON
$.getJSON(url, function() {
console.log("success");
}).done(function(data) {
console.log("second success");
console.log(data.responseData.results);
// create a var for the results and append a header
var results = '<li data-role="list-divider">Results</li>';
$.each(data.responseData.results, function(index, item) {
results += '<li>';
results += item.title;
results += '</li>';
});
// clear the results . append the results .refresh the listview
$('#results').empty().append(results).listview('refresh');
}).fail(function() {
console.log("error");
}).always(function() {
console.log("always");
});
}
});
});
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<!-- jQuery Mobile -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquerymobile/1.4.5/jquery.mobile.min.js"></script>
<!-- page1 -->
<div data-role="page" id="page1" data-title="page1">
<!-- Header -->
<div data-role="header" data-position="fixed">
<h1>Page 1</h1>
</div>
<!-- /Header -->
<!-- Content -->
<div role="main" class="ui-content">
<label for="search">Search Input:</label>
<input name="search" id="search" value="" placeholder="palceholder" type="search">
<ul data-role="listview" id="results" data-inset="true">
</ul>
<script>
</script>
</div>
<!-- /Content -->
</div>
<!-- /page1 -->

Git remote repo no showing in <ul>

I am trying to list my github repos through their api but its not showing up on my page but by using the exact same code its working here on JSFiddle
Debugging shows that the script is being called but its just not loading in its <div>:
<div id="repos">
<ul id="repo_list">
</ul>
</div>`
Here is the markup in my source code:
<section id="git-hub">
<div class="container">
<div class="box">
<div class="center">
<h2>GitHub</h2>
<p class="lead">Go on! Take a look through my repos!</p>
<div id="repos">
<ul id="repo_list">
</ul>
</div>
<div id="repo_content"></div>
<script>
$.ajax({
type: "GET",
url: "https://api.github.com/users/google/repos",
dataType: "json",
success: function(result) {
for( i in result ) {
$("#repo_list").append(
"<li><a href='" + result[i].html_url + "' target='_blank'>" +
result[i].name + "</a></li>"
);
console.log("i: " + i);
}
console.log(result);
$("#repo_count").append("Total Repos: " + result.length);
}
});
</script>
</div><!--/.center-->
</div>
</div>
</section><!--/#pricing-->
Does anybody know what could be the reason?
You're putting this script tag above where you're loading your jQuery. Place this script tag below where you're loading your jQuery.

Append <li class> to <ul class> with jQuery

When I run the function in the browser, "[object Object]" shows up instead of the text stored inside the variable $new_comment. I wish to append user inputs.
HTML :
<li class="list-group-item">"User comments"</li>
<div class="comments">
<ul class="list-group"></ul>
</div>
Js :
var addCommentFromInputBox = function() {
var $new_comment;
if ($(".input-group input").val() !== "") {
$new_comment = $("<p>").text($(".input-group input").val());
$new_comment.hide();
$(".list-group").append('<li class="list-group-item">' + ($new_comment) + '</li>');
$new_comment.fadeIn();
$(".input-group input").val("");
}
};
Everything runs fine when I change the code to:
$(".list-group").append($new_comment);
But I wish to style it with Bootstrap.
You can use it something like this $(".list-group").append($('<li class="list-group-item"></li>').html($new_comment));
Here this the full demo code
addCommentFromInputBox = function() {
var $new_comment;
if ($(".input-group input").val() !== "") {
$new_comment = $("<p>").text($(".input-group input").val());
$new_comment.hide();
$(".list-group").append($('<li class="list-group-item"></li>').html($new_comment));
$new_comment.fadeIn();
$(".input-group input").val("");
}
}
addCommentFromInputBox();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comments">
<ul class="list-group">
</ul>
</div>
var listGroupItem = $('<li class="list-group-item"></li>').html($new_comment)
$(".list-group").append($listGroupItem);

Displaying jQuery checkbox selection

This web page is currently displaying data from an "all" category from an rss feed once the page is loaded. My question is there are several categories which I would like the user to select and display. There are a total of 10 categories, and each correspond to a separate rss feed. Can anyone explain how I handle this event? Also, if one of the categories is selected, will it automatically override the current data being displayed? I will elaborate any unclear parts if needed. Thank you!
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'GET',
url: '/example',
dataType: 'xml',
success: function (xml) {
$(xml).find("item").each(function () {
var title = $(this).find("title").text();
var description = $(this).find("description").text();
var linkUrl = $(this).find("link").text();
//var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>";
var displaytitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
$('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+description+'</p>');
});
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<!-- /field panel -->
<div data-role="panel" id="fieldpanel" data-position="left" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<fieldset data-role="controlgroup">
<legend>Categories</legend>
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
<input type="checkbox" name="checkbox-eleP" id="checkbox-eleP">
<label for="checkbox-eleP">Electrical/Power</label>
<input type="checkbox" name="checkbox-eleD" id="checkbox-eleD">
<label for="checkbox-eleD">Electronics/Design</label>
<input type="checkbox" name="checkbox-nano" id="checkbox-nano">
<label for="checkbox-nano">NanoEngineering</label>
<input type="checkbox" name="checkbox-opt" id="checkbox-opt">
<label for="checkbox-opt">Optics/Display</label>
<input type="checkbox" name="checkbox-semi" id="checkbox-semi">
<label for="checkbox-semi">Semiconductors</label>
</fieldset>
</ul>
</div><!-- /field panel -->
<!-- /settings panel -->
<div data-role="panel" id="settingspanel" data-position="right" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<li>Join IEEE</li>
<li> subscription services</li>
</ul>
</div><!-- /settings panel -->
<div data-role="header" data-theme="b">
Menu
Settings
<h1>MOBILE</h1>
</div>
<div data-role="content">
<div id="feedContainer"></div>
<h3></h3>
<p></p>
</div>
<div data-role="footer">
<h4>Advertisements</h4>
</div>
</div>
</body>
</html>
I will assume you want to get the basic information about this code!
Ok, the first thing to handle is the type of the data to be shown.
<input type="checkbox" id="1" />
<input type="checkbox" id="2" />
Lets start with 2 instead of 10! The jQuery code for this would be easy to understand.
$('input[type=checkbox]').click(function () { // click on checkbox
var val = $(this).attr('id'); // get its id as value
if(val == '2') {
$('someelement).html('2 was selected');
$('#1').prop('checked', false); // unselect the other one
}
}
So, this is the basic code which will execute when a click event occurs on a checkbox. Now in your code you'll be using something like ajax then add the ajax request code before the .html() thing and write the response there.
To update the content being displayed you will be needed to use only one element as the basic clipboard for your app. Why? Because everytime you will get the data, you will be needed to replace the current content with that one and this way you will get only the current data; the selected data.
Lets try one checkbox from your code:
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
Now lets handle the jQuery
$('input[type="checkbox"]').click(function () {
// and all others will be here just as they are.. to check the id
// your ajax request is perfect, just copy paste that here..:)
});
But just need to make a change there, instead of sending the same request try to add one more thing there,
$.ajax({
// url and datatype here,
data: value
// success function goes here
});
Note that the value was the variable that we took from the checkbox. Which will be sent with the request so that you can process only the necessary part of the RSS and leave all other, just like an if else block.
Here is a working fiddle for this http://jsfiddle.net/afzaal_ahmad_zeeshan/KU9JT/.
But I am sorry, I didnot include the if else block to make the code work as it was meant to be. But you'll understand how to manipulate this.

Categories

Resources