Why is my data not displaying when onClick function is added? - javascript

My code could display the data without the onclick function but when it's added the data does not display in my table. There are no errors being displayed as well.
This is the code to get the json data and display:
<script>
var url = "http://127.0.0.1:8080/Assignment2/video/backend/RestController.php?view=all";
$('#viewUser').on('click',function (e){
$.ajax({
method: "GET",
cache: false,
url: url,
success: function(data) {
var student = '';
// ITERATING THROUGH OBJECTS
$.each(data, function (key, value) {
//CONSTRUCTION OF ROWS HAVING
// DATA FROM JSON OBJECT
student += '<tr>';
student += '<td>' +
value.id + '</td>';
student += '<td>' +
value.username + '</td>';
student += '<td>' +
value.videoName + '</td>';
student += '</tr>';
});
//INSERTING ROWS INTO TABLE
$('#table').append(student);
},
error:function(exception){alert('Exeption:'+exception);}
})
e.preventDefault();
});
</script>
This is the code for the button (for onclick function):
<h2>View Stored User</h2>
<button type="button" id="viewUser">GO</button>
[The error i'm receiving from the console log of the browser tho it's not related][1]
[1]: https://i.stack.imgur.com/7TZ3a.png

Related

Passing multi parameter to Td inline JavaScript function

Passing one parameter (report.id) to removeUser function works fine, but when I want to pass two parameter (report.id and report.name) I get Uncaught SyntaxError: Invalid or unexpected token.
I tried '(" +report.id +","+ report.name +")'
I tried '(" +report.id report.name +")'
but none works, what I am doing wrong here
$.ajax({
url: "xxx",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, report) {
html += '<tr>';
html += '<td>' + report.id + '</td>';
html += '<td>' + report.name + '</td>';
html += "<td><a onClick='removeUser(" +report.id + report.name +")'" + "'> Remove </a></td>";
html += '</tr>';
});
$('#users').html(html);
},
function removeUser(id, name) {
alert("ID: "+ id + "Name: "+ name)
}
You need commas between the parameters, and you need quotes only around report.name.
It's much easier to write this using a template literal rather than concatenation.
html += `<td><a href="#" onClick='removeUser(${report.id}, "${report.name}")'> Remove </a></td>`;
Also, since you're doing this with an a element, you should set its href so it doesn't try to link to another page after running the onclick function.

Change text of td element when click on it using jquery

I am getting Json data in output and appended to table with edit option, so what I want is when click on Edit of td then clicked td element text should change from 'Edit' to 'Save' and when click on 'save' again it change to edit, but at time one td element should change from 'Edit' to 'Save' at atime only one 'Save' should active and others remain 'Edit' .
<table class="append_data">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
<th>Action</th>
</tr>
</table>
//script to get data:
$.ajax({
url: "<?= base_url('controller/get_users') ?>",
type: 'POST',
data: {
},
success: function (myJSON) {
var output = myJSON;
var html = '';
$.each(output, function (key, value) {
html += '<tr>';
html += '<td>' + value.name + '</td>';
html += '<td>' + value.mobile + '</td>';
html += '<td>' + value.id + '</td>';
html += '<td><span class="change_res' + value.id + '">Edit</span></td>';
html += '</tr>';
});
$('.append_data tbody').append(html);
},
error: function (xhr) {
alert(xhr.status);
}
});
//script to change text
$("body").on('click', '.edit_user', function () {
var userid = $(this).attr("data-id");
$(this).text('Save').siblings().text('Edit');
});
getting output:
Expected output:
you can try
$("body").on('click', '.edit_user', function () {
var userid = $(this).attr("data-id");
$('.edit_user').not(this).text('Edit'); // back all the edit_user to Edit but not this
$(this).text(($(this).text().trim() == 'Save') ? 'Edit' : 'Save'); // change the text for this between Edit or Save
});
Explanation :
$('.edit_user').not(this).text('Edit'); back all other elements text to Edit
$(this).text().trim() == 'Save') ? 'Edit' : 'Save' is a short hand method of if statement .. means if the text of the element is Save set it to Edit and vice versa .. and about .trim() here for double check that the text is exactly equal the string

Getting JSON in loop doesn't fetch all of the elements in JQuery

I'm trying to get elements from my JSON API like in a example below.
The thing is it doesn't work properly. I'm getting only values from One Hub instead from all of them.
/api/hubsUser/:id - returs JSON with all my hubs and
/api/sensorsHub/:id - returns JSON with all my sensors which have hubID element.
var tableContent = '';
var wholeContent = '';
var hubList = [];
$.getJSON('/api/hubsUser/' + document.getElementById("txt").innerHTML, function (result) {
$.each(result.data, function () {
//alert(this.hubID);
hubList.push(this.hubID);
});
$.each(hubList, function (i, hub) {
// alert(hub);
$.getJSON('/api/sensorsHub/' + hub, function (data) {
$.each(data.data, function () {
//alert(this.sensorID);
tableContent += '<tr>';
tableContent += '<td>' + this.sensorID + '</td>';
tableContent += '<td>' + this.hubID + '</td>';
tableContent += '<td>' + this.desc + '</td>';
tableContent += '<td>' + this.state + '</td>';
tableContent += '</tr>';
});
wholeContent += tableContent;
});
});
$('#sensorList table tbody').html(wholeContent);
});
};
That's because after first ajax succeeds you make a lot of other ajax calls, async of course, and you don't wait for them to execute before you call $('#sensorList table tbody').html(wholeContent);. Strange you even get that one, probably because you are yet on localhost.
You should call $('#sensorList table tbody').html(wholeContent) after all your ajax calls return result. I think a route to follow is to use jQuery when option (see here) or 'promises'.
Another thing that you probably had in mind is to use var tableContent = '' in every secondary ajax instead of declaring it once in the beginning. Otherwise it will contain results of previous ajax calls and same content will be added to wholeContent multiple times.
Try adding .bind(this) to your $.each loops:
$.each(result.data, function () {
//alert(this.hubID);
hubList.push(this.hubID);
}.bind(this)); // <- force the loop to use the object context of your choice

All Dynamic Posts defaults to first Object

I am currently working on an app to retrieve feeds from a wordpress site and list individual posts in a jquery mobile list format. Below is the JS code:
$(document).ready(function () {
var url = 'http://howtodeployit.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json_xml&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 6; i++) {
var entry = postlist[i];
console.log(entry);
html += '<li>';
html += '<a href="#articlepost" onclick="showPost(' + entry.id + ')">';
html += '<div class="etitle">' + entry.title + '</div>';
html += '<div class="esnippet">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#devotionlist").append(html);
$("#devotionlist ul[data-role=listview]").listview();
}
});
});
function showPost(id) {
$('#articlecontent').html("Loading post...");
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function (data) {
var html = '';
html += '<h3>' + data.post.title + '</h3>';
html += data.post.content;
$('#articlecontent').html(html);
});
}
When I click on any of the 6 posts displayed, only the contents of the first Post gets displayed instead of the contents of the individual posts.
How did I workaround this?
Step1: From my WordPress Permalink Settings, I selected Custom Structure and added /%postname%/%post_id% This means my RSS XML output results for my 'Link' element will be in this format:
<myurl>/<postname>/<postID> (http://howtodeployit.com/xxx/111/)
Step2: To make it easier for me instead of writing a regex query I used a Split command like this:
var postlink = entry.link;
var id = postlink.split(/\//)[4];
(///)[4] would simply split the URL by the number of slashes and take only that 4th bit which is where my postID is.
I hope this comes in handy for others in my position

.focus() does not work because dynamic table not loaded yet - JQUERY

I am dynamically creating a table using data from an AJAX call. I am using a "select/dropdown box" .on('change') function to send values to my PHP. Once the table displays, I want to set focus to a search box dynamically created on the table.
The trouble seems to be that since the table takes a couple seconds to become visible, the .focus() command fires before the table is visible. I would like to have the .focus() command fire after the create table function completes.
Javascript/Jquery Code:
$('#t6F3Box1').on('change', function()
{
var $newTable ='<table id="tempEmployerTbl" class="studentTables"><thead><tr>';
var $searchStr=new RegExp("ID");
var $tableContainerDiv="#t6F3TableCont";
var $rowFlag=0;
var $responseDataValue=[]
var $employerState=$('#t6F3Box1').val();
var $getTableDataPhp="../application/employer.php";
var $data=[];
$('#t6F3ErrDiv').text('');
$('#t6F3TableCont, #t6F3HLine2, #t6F3HLine2').show();
$data += "&employerState=" + encodeURIComponent($employerState);
$.ajax({
type: 'POST',
async: false,
url: $getTableDataPhp,
cache: false,
datatype: 'json',
data: $data,
success: function($responseData)
{
//Loop through the responsdata returned in a JSON Array
//dynamically create the Employer drop down box
if (!$responseData.authenticationError)
{
//Create the header for the Employer Table
$.each($responseData, function($key, $value)
{
if($rowFlag==0)
{
$responseDataValue=$responseData[$key];
$.each($responseDataValue, function($keys, $values)
{
if ($searchStr.test($keys))
{
$newTable += '<th class="tableDataHide">' + $keys + '</th>';
}
else
{
$newTable += '<th class="tableDataShow">' + $keys + '</th>'
}
});
$rowFlag=1;
}
});
$newTable +='</tr></thead><tbody>';
//Create the body for the Employer Table
$.each($responseData, function($key, $value)
{
$newTable += '<tr>'
$responseDataValue=$responseData[$key];
$.each($responseDataValue, function($keys, $values)
{
if ($searchStr.test($keys))
{
$newTable += '<td class="tableDataHide">' + $values + '</td>';
}
else
{
if($values==null)
{
$values="";
}
$newTable += '<td class="tableDataShow">' + $values + '</td>'
}
});
$newTable +='</tr>';
});
$newTable +='</tbody></table>';
$($tableContainerDiv).html($newTable);
$("#tempEmployerTbl").dataTable();
$('#tblSearchBox').focus();
}
}
});
I don't see where you even call .focus in your example, but the solution is simply to call it after the $($tableContainerDiv).html($newTable); -- i.e. after it's appended by the ajax callback.

Categories