hi guys i need to append data to a div where i cant dynamic the div look at this code
<li class="media_comment'+$post_id+'"></li>
now the post_id is a dynamic value that i am joining to my class
now i need to append some data to this
$(.media_comment).append('<li class=" media-top"><?php echo img($user_file_image); ?> <p>'+comment +'</p> <br>Like · Reply </li>');
i have the same variable post_id avialable in the append function too. but the value is in a loop and i need to only append this in the li where the same post_id is passing which is posting the same data to every li so what can i do to design a dynamic selector ?
is it possible to do this or should i try another approach?
$(window).load(function(e){
// grab the scroll amount and the window height
loadmore();
select_likes();
select_share();
// get_recieve_friend_requests();
// get_sent_friend_requests();
});
function loadmore(){
var lastID = $('.load-more').attr('lastID');
alert(lastID);
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/get_all_post"); ?>',
data: {id: lastID },
dataType: 'json',
beforeSend:function(data){
$('.load-more').show();
},
success:function(data){
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
if (json=="") {
$("#bottom").append('<div class="btn btn-default col-md-6" >'+'No More Results'+'</div>');
$("#Load_more_data").hide();
}else{
$postID=json[json.length-1].id;
$('.load-more').attr('lastID', $postID);
$.each(json, function (key, data) {
var post_id=data.id;
// alert(data_id);
var post_status=data.status;
var status_image=data.status_image;
var multimage=data.multimage;
if(!post_status=="" && !status_image==""){
alert(post_id);
$("#status_data").append('<div class="panel-footer " onload="select_comment('+post_id+');"><div class="row"><div class="col-md-12">13 people like this</div></div><ul class="media-list"><li class="media_comment" id="comment_div'+post_id+'"></li><li class="media"><div class="media-left media-top"><?php echo img($user_file_image); ?></div><div class="media-body"><div class="input-group"><form action="" id="form_content_image"><textarea name="textdata" id="content_comment_image" cols="25" rows="1" class="form-control message" placeholder="Whats on your mind ?"></textarea><button type="submit" id="comment_button_image" onclick="comment_here_image('+post_id+');">Comment</button></form></div></div></li></ul></div></div>');
}
});
}
}
});
}
function select_comment(post_id)
{
// alert(post_id);
var Post_id=post_id;
var User_id = $('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/select_comment"); ?>',
data: {Post_id:Post_id,User_id:User_id},
dataType: 'json',
success:function(data)
{
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
$.each(json, function (key, data) {
var comment=data.comment;
var post_id=data.post_id;
$post_id=post_id;
$("#comment_post_id").attr('value',$post_id);
$(#comment_div).append('<li class=" media-top"><?php echo img($user_file_image); ?> <p>'+comment +'</p> <br>Like · Reply </li>');
});
}
});
}
here is the loop.
UPDATE: (try to update the loop something along this lines..)
success:function(data)
{
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
$.each(json, function (key, data) {
var comment=data.comment;
var post_id=data.post_id;
var mediaID = '.media_comment' + post_id;
$( mediaID ).append('<li class=" media-top"><?php echo img($user_file_image); ?> <p>'+comment +'</p> <br>Like · Reply </li>');
});
when you loop over json object try to insert something like this there,, if that code is on the php side ofcorse..
$sel = ".media_comment$post_id";
$img = img($user_file_image);
$com = $comment;
echo "$($sel).append('<li class='media-top'>$img <p>$com</p> <br><a href='#'>Like</a><a href='#'>Reply</a> </li>');";
Related
This is my dropdown box:
I am sending drop down value to ajax controller function to get some value.But the value is not passed correctly and i can't find the error;
My ajax code:
<script type="text/javascript">
$(function() {
$('.states').change(function(){
$id = $('.states').val();
$.ajax({
type : "POST",
url : "<?php echo base_url();?>Reports/Fetch_Item",
data :{id:$(this).val()},
success : function (data) {
alert(data);
var obj=jQuery.parseJSON(data);
}
});
});
});
</script>
My controller code;
public function Fetch_Item(){
$name = $this->input->post('id');
$result = $this->db->query("SELECT * FROM acc_master WHERE accName = '$name'")->row();
echo json_encode($result);
}
Front drop down box :
<div id="item3">
Party Name Selection:
<select multiple="multiple" style="width:400px;height:205px;" name="PName"id="Name" class="form-control states">
<option value=""></option>
</select>
<?php echo form_error('Area', '<div class="text-danger">', '</div>'); ?><br><br><br></div>
Dropdown ajax code:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "<?php echo base_url();?>Reports/get_countries1",
data:{id:$(this).val()},
beforeSend :function(){
$('.states').find("option:eq(0)").html("Please wait..");
},
success: function (data) {
$('.states').find("option:eq(0)").html("");
var obj=jQuery.parseJSON(data);
$(obj).each(function()
{
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('.states').append(option);
});
}});
});
</script>
Can you try this
<script type="text/javascript">
$(function() {
$('.states').change(function(){
var id = this.value;
$.ajax({
type : "POST",
url : "<?php echo base_url();?>Reports/Fetch_Item",
data :{'id':id,},
success : function (data) {
alert(data);
var obj=jQuery.parseJSON(data);
}
});
});
});
</script>
The $(this).val() returns an array, you have to change your backend code to handle the array.
Something like below.
public function Fetch_Item(){
$name = implode(",", $this->input->post('id'));
$result = $this->db->query("SELECT * FROM acc_master WHERE accName in ('$name')")->rows();
echo json_encode($result);
}
Note: Fetch_Item methon sql will return multiple results so you have to handle this as well.
The following code consists of drop-down "(id=name" which populates from "listplace.php" through ajax call which works correctly.
Now I am trying to make another ajax call using the change function. when I select the particular item already populated on dropdown box it has to pass the selected item name1 in 'where' query to dataprod.php and has to display the products by clearing the existing products list available.
I am doubtful over the $name1 response from dataprod.php. Please help!!
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}else {
alert('No data found!');
}
}
});
</script>
ajax 2
$(document).ready(function(){
$("#name").change(function(){
var name1 = this.value;
$.ajax ({
url: "dataprod.php",
data: {place: '<?= $_GET['name1'] ?>'},
success: function (response) {
$('.products-wrp').html('')
$('.products-wrp').html(response);
}
}else {
$('.products-wrp').html('');
}
}
dataprod.php
<?php
include("config.inc.php");
$name1 = $_POST['name1'];
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code,
product_image, product_price FROM products_list where product_name='$name1'");
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
Since you are calling ajax event on element which is loaded via ajax action so the change event is not bind and nothing is happend.
For ajax 2 action use below code.
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = this.value;
$.ajax ({
url: "dataprod.php",
data: {place: '<?= $_GET['name1'] ?>'},
success: function (response) {
$('.products-wrp').html('')
$('.products-wrp').html(response);
}
}else {
$('.products-wrp').html('');
}
}
here i have written the code for a functionality using jquery-ajax in CODEIGNITER where i need to pass the value of the drop down to the database using 'ajax post method' execute a query and get and display the results/data in the same view page using onChange, but the problem is onChange no change is visible.
Please help me out on this.
view.php
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" name="ProductCategoryID" id="item_code" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="'.$row->ItemCode.'">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group" id="description">
</div>
<script src="<?php echo base_url("assets/js/jquery-1.10.2.js"); ?>" type="text/javascript"></script>
<script type="text/javascript">
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#item_code').append('<textarea value="' + id + '">' + name + '</textarea>');
}
});
$('#item_code').trigger('chosen:updated');
});
</script>
Controller.php
<?php
class Ajax extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
$this->load->model('Gst_model');
$this->load->model('User_model');
$this->load->model('Report_model');
$this->load->helper('url');
}
function get_description()
{
$id = $this->input->post('id');
echo(json_encode($this->Report_model->get_description($id)));
}
}
Model.php
function get_description($item_code)
{
$result = $this->db->where('ItemCode', $item_code)->get('gst_itemmaster')->result();
$id = array('0');
$name = array('0');
for ($i=0; $i<count($result); $i++)
{
array_push($id, $result[$i]->ItemDescription);
array_push($name, $result[$i]->ItemDescription);
}
return array_combine($id, $name);
}
Your problem is that updating chosen-select dropdowns is a bit tricky. After you've updated your option list you have to call something like $('.my_select_box').trigger('chosen:updated'); Take a look at the chosen-select docs here.
Just put this after your ajax call at the end of your change() function:
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#state').append('<textarea value="' + id + '">' + name + '</option>');
}
});
$('#item_code').trigger('chosen:updated');
});
trying to use datatype json to get the value in json format but when i add it into my script it shows error that elemet ] is missing what am i doing wrong?
$(document).ready(function(){
$(window).scroll(function(){
var lastID = $('.load-more').attr('lastID');
if ($(window).scrollTop() == $(document).height() - $(window).height() && lastID != 0){
$.ajax({
type:'POST',
url:'<?php echo base_url("user/get_all_post"); ?>',
data:"id="+lastID,
dataType:'json',
beforeSend:function(html){
$('.load-more').show();
},
success:function(html){
//alert(html);
var ParsedObject = JSON.stringify(html);
var json = $.parseJSON(ParsedObject);
//alert(json);
/*
var json =" [{'id':1,'name':'Test1'},{'id':2,'name':'Test2'}]";
var jsonArray = eval('(' + json + ')');
for (i in jsonArray)
{
alert(jsonArray[i]["name"]);
}
*/
// alert(json.id);
var jsonArray = eval('(' + json + ')');
$PostId=jsonArray[4]["id"];
// alert($PostId);
for(i in jsonArray)
{
$post_status=jsonArray[i]["status"];
$status_image=jsonArray[i]["status_image"];
$multimage=jsonArray[i]["multimage"];
//alert(Lastid);
//alert($post_status);
//alert($status_image);
//alert($multimage);
$('.load-more').attr('lastID',$PostId);
$('#result_table').append(jsonArray);
}
}
});
}
});
});
</script>
i want to access my json data so that i can display it but all the variable shows undefined when i access then in my view
first, your user/get_all_post need to return json data (and also have response header with application/json)
use output class
(ref. https://codeigniter.com/user_guide/libraries/output.html)
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
then you can use json attribute in jquery when it response
success:function(response){
alert(response.foo)
}
I think I found a solution for this i was just adding everything in my code where i just needed to access my json value for that i only needed to parse the json value and then i can access the array in for loop
hope it helps other too
<script type="text/javascript">
$(document).ready(function(){
$(window).scroll(function(){
var lastID = $('.load-more').attr('lastID');
if ($(window).scrollTop() == $(document).height() - $(window).height() && lastID != 0){
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/get_all_post"); ?>',
data: "id=" + lastID,
dataType: 'json',
beforeSend:function(html){
$('.load-more').show();
},
success:function(data){
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
$PostId=json[4]['id'];
for(i as json)
{
var post_status = json[i]['status'];
$status_image = json[i]['status_image'];
var multimage = json[i]['multimage'];
alert($status_image);
$("#status_data").append('<div style=" margin: 20px 50px 0px 40px; ">'+'<a>'+'<?php echo img($user_image); ?>' +'</a>'+'<a>'+ ' <?php echo $uname; ?>' +'</a>'+'<div>'+post_status+'</div>' +'</div>');
$("#status_data").append('<div style=" margin: 20px 50px 0px 40px; ">'+'<a>'+'<?php echo img($user_image); ?>' +'</a>'+'<a>'+ ' <?php echo $uname; ?>' +'</a>'+'<div>'+'<img src="'+<?php base_url('uploads/'); ?> status_image+'">'+'</div>' +'</div>');
}
$('.load-more').attr('lastID', $PostId);
}
});
}
});
});
</script>
this would work there is no need for eval or jsonArray. thanks to everyone for replying.
On document load I run the following ajax script.
function LoadData() {
$.ajax({
type: "GET",
url: "display.php",
dataType: "html",
success: function(text){
$("#responsecontainer").html(text);
}
});
}
Here is the PHP script it pulls the data from.
Yes I know it's depreciated and most likely vunerable to attack.
<?php
include 'db.php';
$counter = 0;
echo '<table class="table" id="tableShow">
<tr>
<td align=center><b>ID</b></td>
<td align=center><b>Name</b></td>
<td align=center><b>Quantity</b></td>
<td align=center><b>Price</b></td></td>
<td align=center><b>Description</b></td>
<td align=center><b>Edit Item</b></td>
';
$result = mysql_query("SELECT * from user ORDER BY `id` ASC");
while($data = mysql_fetch_row($result))
{
echo "<tr>";
echo "<td align=center>$data[0]</td>";
echo "<td align=center>$data[1]</td>";
echo "<td align=center>$data[3]</td>";
echo "<td align=center>$data[4]</td>";
echo "<td align=center>$data[2]</td>";
echo '<td align=center><a class="btn Edititem btn-info btn-small" id="'.++$counter.'">Test1</a></td>';
echo "</tr>";
}
echo "</table>";
?>
As you can see, within the table it has a button for each row.
<a class="btn Edititem btn-info btn-small" id="'.++$counter.'">Test1</a></td>
I then have this script.
$(".Edititem").click(function ()
{
$('#Edit').modal('show');
$("#updateResults").click(function (){
$.ajax({
url: 'api.php',
data: "id="+ $(this).find('a').attr('id'),
dataType: 'json',
success: function(data)
{ var id = data[0];
var name = data[1];
var desc = data[2];
var quant = data[3];
var price = data[4];
$('#inner-title').html(name);
$('#itemid').val(id);
$('#Name').val(name);
$('#quant').val(quant);
$('#price').val(price);
$('#desc').val(desc);
$('#Edit').modal('hide');
$('#success').alert();
},
error: function(){$("#failure").alert();}
});
});
});
It seems that the html thats pulled from the PHP script, is invisible to jQuery. For example, when you click on one of the buttons, it should launch the modal I have within my page, however, it don't happen and I get no console errors either. But if I just insert the button into the #responsecontainer like so:
<div id="responsecontainer">
<a class="btn Edititem btn-info btn-small" id="'.++$counter.'">Test1</a>
</div>
jQuery can find it, and the modal launches?
What is wrong here?
I recommend you to use .on() jQuery function.
.on() | jQuery API Documentation
Consider following script update:
$("#responsecontainer").on("click", ".Edititem", function() {
$('#Edit').modal('show');
$("#updateResults").click(function() {
$.ajax({
url: 'api.php',
data: "id=" + $(this).find('a').attr('id'),
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
var desc = data[2];
var quant = data[3];
var price = data[4];
$('#inner-title').html(name);
$('#itemid').val(id);
$('#Name').val(name);
$('#quant').val(quant);
$('#price').val(price);
$('#desc').val(desc);
$('#Edit').modal('hide');
$('#success').alert();
},
error: function() {
$("#failure").alert();
}
});
});
});
This is because when the document is loaded the elements are not loaded yet.
You can try the following. This does late binding on Jquery. Read More here https://api.jquery.com/on/
$(document).on('click', '.Edititem', function (e)
{
e.preventDefault();
$('#Edit').modal('show');
$("#updateResults").click(function (){
$.ajax({
url: 'api.php',
data: "id="+ $(this).find('a').attr('id'),
dataType: 'json',
success: function(data)
{ var id = data[0];
var name = data[1];
var desc = data[2];
var quant = data[3];
var price = data[4];
$('#inner-title').html(name);
$('#itemid').val(id);
$('#Name').val(name);
$('#quant').val(quant);
$('#price').val(price);
$('#desc').val(desc);
$('#Edit').modal('hide');
$('#success').alert();
},
error: function(){$("#failure").alert();}
});
});
});