Add html table to content loaded by jQuery - javascript

I'm working on an Ajax/PHP-powered sequence of forms. The first form is submitted and, upon successful submission, the page returns a new form using Ajax, PHP and jQuery. This first part works fine. The part where the new form is yielded upon form success, does not.
$('#some_form').submit(function (event) {
event.preventDefault();
var form = $(this);
console.log(form);
var formdata = {
'title': form.find('input[name=title]').val(),
'user': form.find('select').val()
};
$.ajax({
type: 'POST',
url: "some_url",
data: formdata,
dataType: 'json',
encode: 'true',
success: function (res) {
if(res.field_errors) {
// If there are errors: do stuff
}
else {
//No errors, so successful submission, time to load new form
var form_div = $("<div>",{"id":"some_div","class":"col-lg-12"});
var table = fill_table(res.data);
var form_content = form_div.load('page_template.html');
//The line below does not work.
form_content.find("#table-div").append(table);
form_div.append(form_content);
form_div.appendTo("#page-wrapper");
}
},
error: function (jqXHR, errorThrown) {
console.log('jqXHR:');
console.log(jqXHR);
console.log('errorThrown:');
console.log(errorThrown);
}
});
)};
And the fill_table functions (a bit clumsy but it's still work-in-progress):
function create_table_row(row_data){
var tr = $('<tr>');
var first_td = "<td class='checkbox'><label><input type='checkbox' value="+mi.id+" name='mi[]'/></label></td>";
var second_td = "<td>"+row_data.title+"</td>";
var third_td = "<td>"+row_data.description+"</td>";
var fourth_td = "<td class='file'><i style='vertical-align:middle; line-height:30px;' class='fa fa-1x fa-file-pdf-o'></i></td>";
tr.append(first_td);
tr.append(second_td);
tr.append(third_td);
tr.append(fourth_td);
return $(tr);
}
function fill_table(data_pool) {
if(data_pool.length==0){
return "There is no data available yet.";
}
else {
var table = $("<table>",{"class":"mi-list","id":"mi-table"}).append("<tr><th class='checkbox'><label><input type='checkbox' id='bulk' name='data[]'/> </label></th> <th>Title</th><th>Description</th><th>Date</th><th>File</th></tr>");
$.each(data_pool, function(index, val){
table.append(create_table_row(val));
});
return table;
}
}
The table functions work fine, and so does the .load() which correctly loads the static HTML part. However, I can't seem to correctly add the yielded table to the div that was just loaded by.load(). Logging the table data to console shows me that the table is there, with both the static and dynamic table data inside of it.
form_content.find("#table-div").append(table); Does not work. form_content.find("#table-div").html(table); doesn't either.
How do I correctly append this to the new div?

Since the load is async, you need to use a callback which is going to be run once the load process is complete. See jQuery.load() documentation.
Then, your could should look like this:
form_div.load('page_template.html', function() {
form_content.find("#table-div").append(table);
form_div.append(form_content);
form_div.appendTo("#page-wrapper");
});

Related

jQuery().append is working but .html is not working on ajax call

I'm using WordPress. After getting response I'm using jQuery().append(response) .Its working fine. Problem is that it is generating multiple div .That's why I need to use html or innerHtml .But it is not working. Though I'm getting response back from server.
function get_chat_history() {
//var doc = document.getElementById("show-chat-div-text");
document.getElementById("show-chat-div-text").lastElementChild;
var id_of_incoming_chat_user=document.getElementById("show-chat-div-[![enter image description here][1]][1]text").lastElementChild;
var id_incoming_chat_user;
if (id_of_incoming_chat_user!=null) {
id_incoming_chat_user= id_of_incoming_chat_user.getAttribute('class');
}
else (id_of_incoming_chat_user===null)
{
id_incoming_chat_user=document.getElementById("show-chat-div-text").getElementsByTagName("Div")[0].getAttribute('class');
}
if(id_incoming_chat_user==="user-hide")
{
id_incoming_chat_user=document.getElementById("show-chat-div-text").getElementsByTagName("Div")[1].getAttribute('class');
}
cur_user = '<?php echo get_current_user_id() ;?>';
var message = document.getElementById("myInput").value;
var listitem="";
var postdata = {action: "navid_history_ajax_call",
param_user_to_chat: id_incoming_chat_user,
param_main_user:cur_user,
message:message
};
jQuery.post(ajaxurl, postdata, function (response) {
//jQuery("#show-chat-div-text").html=response;//not working
// jQuery("#show-chat-div-text").append(response);//Working
console.log(response);
chatBox.scrollTop = chatBox.scrollHeight;
});
}
setInterval(get_chat_history, 5000);
You should wrap the response within brackets.
Ex:
jQuery("#show-chat-div-text").html(response);

Jquery ajax load comment without page refresh in codeigniter

I'm developing a post comment system with PHP CodeIgniter framework.When a user comment for a post-it didn't get loaded without page refresh. Here is my ajax code.
var id = $(this).attr("data-id");
// check to see which events this comment already has
var events = $._data( this, 'events' ).keypress;
// Try to find if keypress has already been registered
// registering it twice causes duplicate comments
var hasEvents = false;
for(var i=0;i<events.length;i++) {
if(events[i].namespace == "") {
hasEvents = true;
}
}
if(!hasEvents) {
$.ajax({
url: global_base_url + 'feed/post_comment/' + id,
type: 'POST',
data: {
comment: comment,
csrf_test_name: global_hash,
page: global_page,
hide_prev: hide_prev
},
dataType: 'json',
success: function(msg) {
if (msg.error) {
alert(msg.error_msg);
return;
}
$('#feed-comments-spot-' + id).html(msg.content);
$('#feed-comments-' + id).html(msg.comments);
}
});
}
My form code is:
<div class="feed-comment-area" id="feed-comment-<?php echo $r->ID ?>">

jQuery blur based checking and print result to a view in codeigniter

Possibly someone asked question like as my question. But, I can't find any solution.
ProfileEditor.php (controller)
method 1:
public function modify_personal_information() {
$this->data['userinfo'] = $this->personal_information_of_mine($userid);
$this->load->view('layouts/header', $this->data);
$this->load->view('profile/personalinformation', $this->data);
$this->load->view('layouts/footer', $this->data);
}
method 2:
public function check_url_if_exists() {
$newportalurl = $this->uri->segment(2);
$this->results = $this->profile_model->checknewportalurl($newportalurl);
if ($this->results == 1) {
$this->status['status'] = 1;
$this->status['msg'] = 'This name is available. Thanks.';
} else {
$this->status['status'] = 0;
$this->status['msg'] = 'This name is not available. See suggestions.';
}
$this->load->view('profile/layouts/availiability', $this->status);
//or echo json_encode($this->status);
}
profile/personalinformation.php (views)
a form with <div id="urlsuggestions"></div>
profile/layouts/availiability.php (views)
where i am printing the message which i am getting from the check_url() function
ajax.js (ajax)
$('#newportalurl').blur(function() {
var fval = $(this).val();
var ifexists = fval.toLowerCase().replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
$.ajax(baseurl + "check/"+ifexists, function(data) {
//i tried following things
//alert(window.location);
//$('#msgbox').html(data.msg).show().addClass('alert-success').delay(2000).fadeOut();
//$('#urlsuggestions').load(window.location + 'modifypersonalinformation #urlsuggestions');
});
});
Now, I am trying to load the message to personalinformation view. What I am doing wrong or what will be the procedure to do it? I actually want to know the process how codeigniter handle them.
Please try like this, im not able to get response from your metod.
$.ajax({
url: "<?= base_url("check/") ?>"+ifexists,
success: function (data) {
$("#urlsuggestions").html(data);// if you want to replace the data in div, use .html()
or if you want to append the data user .append()
}
});

How to create/find right ID in multiple Form elements of same type $ajax function with jQuery Mobile?

I have a collapsible part of my jQuery Mobile page that are generated from PHP output from a MS Sql databas and content render as I like it to so that part is ok.
in each section I create a form with 3 buttons and they are supposed to have unique Id:s.
All forms are also created to have a unique id created in runtime.
actions.php (renders out my elements into mobilepage i a DIV)
$counter=0; reset counter for ID:s
while (odbc_fetch_row($rs)){
// data output from Db to make like 10 collapsible with different data
$html = "";
$html = "<div data-role='collapsible-set' data-mini='true'>";
$html.="<div data-role='collapsible' data-mini='true'>";
$html.="<h3><span style=float:left;><img src='../_pic/$image' alt='$imageText' /> ".substr($Time,0,16)." $Area</span><span style='float:right;' class='ui-btn-up-c ui-btn-corner-all' cnt> $data </span></h3>";
$html.="<p>ID: $ID $Id $Status<br />$Status $Description)</p>";
$html.="<form method='post' action=''>";
$html.="<button value='action1' id='action1$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action2' id='action2$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action3' id='action3$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<input type='hidden' id='id$counter' name='id' value='$dataName' />";
$html.="</form>";
$html.="</div>";
$html.="</div>";
echo utf8_encode($html);
$counter++; //upcount to make Id:s unique
} //end While
Then I have this function that listens for a button that submit:
$(':submit').live('click', function() {
var button = $(this).val();
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+$('#id').val(),
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
I cant seem to get another id than the first one since i need to make all ID:s unique in my forms and all I do now is to check: &id='+$('#id').val(). what I would like to have done is to link the button pressed-id number to my hidden field id-number so i get the right data out from it. As of now I only get the first form:s id evaluated...
If someone could point me in the right direction how to make that happen i´d be greatful.
functions.php (a switch statement is pre-testing for submit:ed action
function actions1(){
try {
if(isset($_GET['id'])){
do stuff with 'id'
}else{
do other stuff with 'id'
}
} catch(Exception $e) {
show error
}
}
If some part is unclear or if you feel I missed posting somepart - let me know. /thanks
Within event handlers this referes to the element
$(':submit').live('click', function(){
var id= this.id;
var button = $(this).val();
/* traverse within form to set hidden input, no need to worry about using ID's for them*/
$(this).closest('form').find('input[name=id]').val(id);
/* then in ajax */
data: 'button=' +button+'&id='+id,
})
Not full code....I left some of your code out for simplicity
You can use jQuery .attr() function to get an id or any other attribute value of an element.
$(':submit').live('click', function() {
var button = $(this).val();
var id = $(this).attr("id");
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+ id,
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
The solution was to go by attributes name of my hidden input.
var id = $(this).closest("form").find(':hidden').val();

How to unbind or turn off all jquery function?

I have constructed an app with push state. Everything is working fine. However in some instances my jquery function are fireing multiple times. That is because when I call push state I bind the particular js file for each page I call. Which means that the same js functions are binded many times to the html while I surf in my page.
Tip: I am using documen.on in my jquery funciton because I need my function to get bound to the dynamical printed HTML through Ajax.
I tried to use off in the push state before printing with no success!
Here is my code:
var requests = [];
function replacePage(url) {
var loading = '<div class="push-load"></div>'
$('.content').fadeOut(200);
$('.container').append(loading);
$.each( requests, function( i, v ){
v.abort();
});
requests.push( $.ajax({
type: "GET",
url: url,
dataType: "html",
success: function(data){
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
$('a').off();
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
})
);
}
$(window).bind('popstate', function(){
replacePage(location.pathname);
});
Thanks in advance!
simple bind new function with blank code
$( "#id" ).bind( "click", function() {
//blank
});
or
used
$('#id').unbind();
Try this,
var requests = [];
function replacePage(url) {
var obj = $(this);
obj.unbind("click", replacePage); //unbind to prevent ajax multiple request
var loading = '<div class="push-load"></div>';
$('.content').fadeOut(200);
$('.container').append(loading);
$.each(requests, function (i, v) {
v.abort();
});
requests.push(
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function (data) {
var dom = $(data);
//var title = dom.filter('title').text();
var html = dom.find('.content').html();
//alert(html);
//alert("OK");
//$('title').text(title);
obj.bind("click", replacePage); // binding after successfulurl ajax request
$('.push-load').remove();
$('.content').html(html).fadeIn(200);
//console.log(data);
$('.page-loader').hide();
$('.load-a').fadeIn(300);
}
}));
}
Hope this helps,Thank you

Categories

Resources