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()
}
});
Related
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);
i want to display these json data into a html table. i am trying to do many things but i cant figure out how can i do it. So anyone can please help me to fix it.
the json data set will appear in the console. but i cant set it to a table.
this is my model
public function displayRecords()
{
$this->db->select('A.*');
$this->db->from('rahu AS A');
$this->db->where('A.status',1);
return $this->db->get()->result_array();
}
this is my controller
public function allrecodes()
{
/*script allow*/
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed here.');
}
$response= array();
$response['result'] = $this->RahuModel->displayRecords();
echo json_encode($response);
}
this is my js
var get_rec = function(){
//alert("WWW");
$.ajax({
//request ajax
url : "../dashbord/allrecodes",
type : "post",
contentType: "application/json",
dataType : "json",
success: function(dataset) {
//var myobject = JSON.stringify(result);
//alert(myobject[0]);
console.log(dataset);
console.log(dataset.result[0]['id']);
},
error: function() { alert("Invalide!"); }
});
};
the json dataset will appear in console.
And also this get_rec() in js file will called top of the page.
$(document).ready(function() {
//alert("Hello, world!");
get_rec();});
can anyone please help me to fix it.. thank you !!
There is no "simple" way to do it. You will have to loop through the resultset and render the html.
function renderTable(data) {
var result = ['<table>'];
var header = false;
for (var index in data) {
var row = data[index];
if (!header) {
// Create header row.
header = Object.keys(row);
var res = ['<tr>'];
for (var r in header) {
res.push("<th>" + header[r] + "</th>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
// Add data row.
var res = ['<tr>'];
for (var r in header) {
res.push("<td>" + row[header[r]] + "</td>");
}
res.push('</tr>');
result.push(res.join("\n"));
}
result.push('</table>');
return result.join("\n");
}
document.getElementById('output').innerHTML = renderTable(data);
Have a div tag with id output on your HTML
<div id="output"></div>
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");
});
Scoop...
I have a drop down list that might not display a particular option you're looking for. I added a button with pop up modal to type in a field you want to add to the drop down list. It functions perfectly, but I need to add an ajax postback method to refresh the list after the user hits enter. I don't want to refresh the whole page, just the list. any help?
Controller:
public ActionResult AddLeadSource()
{
return View();
}
[HttpPost]
public ActionResult AddLeadSource(string name)
{
LeadSource ls = new LeadSource();
ls.Name = name;
db.LeadSources.Add(ls);
db.SaveChanges();
return Json(new { success = true });
}
JS
<script>
$("#AddNew").change(function () {
var name = $("#Name").val();
// var order = $("#DisplayOrder").val();
$.ajax({
type: 'POST',
dataType: 'json',
cache: false,
url: '/Admin/LeadSource/AddLeadSource',
data: { name: name },
success: function (response) {
//alert("Success " + response.success);
$('#FollowUpNotes').kendoWindow('destroy');
// Refresh the DropDown <-- Heres where I need some help!
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
});
In your success function of your Ajax call add this:
$("IdOfDropDownList").data("kendoDropDownList").dataSource.read();
In this way your dropdownlist will call the read function and reload all data. I assumed that your dropdownlist is binding throught read call.
I highly recommend looking at jQuery UI's autocomplete widget. That said,
$('#YourDropDownID option').remove(); //this will remove all option elements inside the <select id="YourDropDownID">
Then you just need to build new ones based on the response data,
for (var o in data) {
if (data[o].Value != undefined) {
$('#YourDropDownID').append('<option value="' + data[o].Value + '">' + ("" + data[o].Display) + '</option>');
}
}
I do this inside the .done() callback of my AJAX:
.done(function (data) {
//above code
}
Depending on the nature of the data you are sending back you may need to loop through it differently. Mine is an array of objects with a Value and Display properties (in my case, account numbers and account names).
//server side controller
var query = #"
Select
SubString([mn_no], 0, 6) As Value,
RTRIM([acct_desc]) As Display
From [some_table]";
return con.Query(query, new { AccountNumber = accounts.Select(x =>
{
return new { Value = x.Value, Display = x.Display };
});
I have a function which updates a database via ajax. My issue is then how to update the data displayed on the page to show updated details. The POST data can vary and therefore the datastring would be something like this:
var dataString = '[name resource we are editing]=1' +
'¶1='+ para1 +
'¶2=' + para2+
'¶3=' + para3
I want the function below to split or loop through each of the POST variables in the datastring to update the text of an element on the page. I cannot figure out how.
function editAccount(dataString, details, form){
status = $(".status");
$.ajax({
type: "POST",
url: "<?php echo BASE_PATH; ?>/edit/",
data: dataString,
success: function(response) {
$.each(response, function(key, value) {
success_code = key;
message = value;
});
if(success_code == 1){
status.text(message).addClass("valid");
//show details and hide form
$("#" + details).show();
$("#" + form).hide();
//HOW to do below?
//update details being displayed with datasource data
//loop through dataString to assign eg. $('#para1')text(para1);
} else {
status.text(message).addClass("invalid");
}
},
error: function(response){
status.text("There was a problem updating your details into our database. Please contact us to report this error.").addClass("invalid");
}
});
}
As mentioned in a previous comment, I would suggest declaring the dataString variable as an object:
var dataString = { '[name resource we are editing]' : 1,
'para1': para1,
'para2': para2,
'para3': para3
}
Now it'll be much easier to loop over the params, just using the function each, for instance, which you already use in your code:
$.each(dataString, function(key, value) {
// Do stuff with each param
});
EDIT:
As #Qpirate suggests, you also can use the javascript for loop:
for(var key in dataString){
// value => dataString[key]
}