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

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.

Related

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

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

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

How to make table updating content without refresh the whole page

i've made a project using php ajax i use it for input data and displaying data into a table. the code work fine but when displaying data the table content didnt update the latest input in there i need to refresh page to update them.
anyone know how to make it update without refresh the whole page?
this my ajax function for input and displaying
INPUT
$(document).on('click','#ok',function(e) {
if ($('#netto').val() == '') {
alert('Kolom Netto Tolong Di Isi');
} else {
var data = $("#form_input").serialize();
$.ajax({
data: data,
type: "post",
url: "../php/bkk/bkk_i.php",
success: function(data){
alert("Data: " + data);
}
});
}
clearInput();
});
$("#form_input").submit( function() {
return false;
});
function clearInput() {
$("#form_input :input").each( function() {
$('#nopol').val('');
$('#netto').val('');
});
}
Display
$(document).ready(function(){
$.ajax({
type: "Post",
url: "../php/bkk/bkk_isel.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#mat').val((list[i]['material']));
$('#lok').val((list[i]['lokasi']));
$('#kpl').val((list[i]['kapal']));
$('#po_numb').val((list[i]['po']));
$('#dok').val((list[i]['doc_mat']));
var tr = "<tr>";
tr += "<td>"+list[i]['no']+"</td>";
tr += "<td>"+list[i]['tanggal']+"</td>";
tr += "<td>"+list[i]['no_pol']+"</td>";
tr += "<td>"+list[i]['netto']+"</td>";
tr += "</tr>";
$("#table_s tbody").append(tr);
}
return false;
}
});
});

Ajax returning an undefine value

I have a search function that is suppose to search a name from the database, and then when the user clicks add, the item choosen has to appear below the search field, in short it has to be posted back so that the user can re-select his/her second option from the search element so that all the selected options can be saved in the database. The problem im facing is that after I click add im getting undefined value back instead of the one I choose and my response is a name instead of an Id number, here is my code and a picture below.
MODEL
public function getName($id)
{
$select = $this->select()
->where('service_provider_id LIKE "' . $id . '%"')
->order('service_provider_name');
return $this->fetchAll($select);
}
CONTROLLER
{
$id = $this->getRequest()->getParam('id');
$mdlserviceprovider = new Model_ServiceProviders();
$serviceprovider = $mdlserviceprovider ->getName($id);
$arr_rtn = array();
if (count($results) > 0){
foreach($results as $result)
{
$myarr = array( 'label' => $result->service_provider_name,
'value' => $result->service_provider_name,
'id' => $result->service_provider_id
);
array_push($arr_rtn, $myarr);
}
}
echo Zend_Json::encode($arr_rtn);
}
PHTML/AJAX
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
var row = '<tr><td>' + data["serviceprovider"] + '</td></tr>';
$('#t1').append(row);
//alert();
}
});
});
Thanks in advance
You can use data["value"] instead of data["serviceprovider"]:
var row = '<tr><td>' + data["value"] + '</td></tr>';
Since you've encoded the array which contains three keys: label, value and id. So there's no serviceprovider key at this moment for Zend to encode.
You are looking for a key that doesn't exist in the array you are returning try this
var row = '<tr><td>' + data['label'] + '</td></tr>';
Or this
var row = '<tr><td>' + data['value'] + '</td></tr>';
As those are the two keys you defined in your PHP page
Try
var row = '<tr><td>' + data[0].value + '</td></tr>';
Also try to put an alert() in the success function like,
alert(JSON.stringify(data));
and see what is included in it..
From what I see I think you are ruturning a multidimensional array from php so I would try something like this in javascript:
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
data.each(function(index, el){
var row = '<tr><td>' + el.label + '</td></tr>';
$('#t1').append(row);
//alert();
}
}
});
});
In your controller try:
$this->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
return $this->_helper->json(array('key1' => $val1, 'key2' => $val2, ...));

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

Categories