Get values from array of data from jquery data ajax object - php

Hi I am trying to get attribute values from array of elements...
JQuery
function sendM(){
$.ajax(
{
type:'POST',
url:'../business_logic/send_chat_user.php', //URL
data:{ u_id: <?php echo $_SESSION['uid']?>,c_id }, //Data
beforeSend:function(){},
success:function(data,status){ //Data,status
var item = $(data).hide().slideDown("slow");
var el = $.parseHTML(data);
var e = $("a", el).attr ("value"); // This only gives me single value.. I want an array
$('#msg').append(item);
}
});
}
send_chat_user.php file
echo '<ul class="nav nav-list">';
for($i = 0 ; $i < count($list) ; $i++)
{
echo '<li>';
echo '<div class="user_list">';
echo '<img src="../images/default_profile_pic/d_boy.png" class="img-rounded">';
echo ''.$list[$i]['fn'].' '.$list[$i]['ln'].'';
echo '</div>';
echo '</li>';
}
echo '</ul>';
I want to get array of values from attribute 'value' of Anchor tag . I am able to get single value in jquery in variable e ... but i want array of values.

$.ajax({
type:'POST',
url:'../business_logic/send_chat_user.php', //URL
data:{ u_id: <?php echo $_SESSION['uid']?>,c_id }, //Data
beforeSend:function(){},
success:function(data,status){ //Data,status
var arr = [];
var item = $(data).hide().slideDown("slow");
var el = $.parseHTML(data);
var e = $("a", el);
e.each(function(index) {
arr.push($(this).attr('value'));
});
alert(arr.toString());
$('#msg').append(item);
}
});

Related

How to access JSON values returned by AJAX call

I have written AJAX code to fetch MySQL data and show it on an HTML page. But my output is not showing on the page.
What am I doing wrong?
PHP:
function nav() {
$this->dbConnect();
$qry="SELECT pid, ptitle FROM pages WHERE pagepub='1' ORDER BY porder ASC";
$result=mysqli_query($this->connect,"$qry") or die('MySql Error! ' . mysqli_error());
$results = array();
while($row=mysqli_fetch_row($result)) {
$results[] = $row;
}
echo json_encode($results);
$this->dbclose();
}
Here is the output of my PHP file:
[
{
"pid":"1",
"ptitle":"One Time Registration Tips"
},
{
"pid":"2",
"ptitle":"First men in India"
},
{
"pid":"3",
"ptitle":"First Women in India"
}
]
JavaScript / HTML:
<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script type="text/javascript" src="dist/js/jquery.js"></script>
<script type="text/javascript">
$(function () {
jQuery.ajax({
url: 'http://keralapsctuts.com/app/category.php',
data: "",
dataType: 'json',
success:function(data) {
var id = data[0]; //get id
var title = data[1]; //get name
$('#output').html(" <a class='list-group-item' href='"+id+"'"+title+" <i class='fa fa-chevron-right pull-right'></i></a>");
}
});
});
</script>
As you returning more rows, you should use for if you want to iterate through them.
success:function(data) {
var result = "";
for(var i=0; i < data.length; i++) {
var id = data[i]["pid"]; //get id
var title = data[i]["ptitle"]; //get name
result += "<a class='list-group-item' href='"+id+"'>"+title+"<i class='fa fa-chevron-right pull-right'></i></a>";
}
$('#output').html(result); //Set output element html
}
Given your output of:
[{"pid":"1","ptitle":"One Time Registration Tips"},{"pid":"2","ptitle":"First men in India"},{"pid":"3","ptitle":"First Women in India"}]
Your data would be addressable like so:
success:function(data){
var id = 0;
var title = "";
$.each(data, function(k, v){
id = v.pid;
title = v.ptitle;
$('#output').append("<a class='list-group-item' href='"+id+"'>"+title+"<i class='fa fa-chevron-right pull-right'></i></a>");
});
}

Convert data to Json in CodeIgniter with AJAX

I am struggling to convert json code in CodeIgniter, i wanna make pagination.
I am using ajax and want to controle data convert to json and send it to view. I can someone explain me how to do that.
Code in controler, instead foreach part i am trying to make Json, and send it to view
function ajax(){
$rpp= $_POST['rpp'];
$last = $_POST['last'];
$pn = $_POST['pn'];
if($pn<1){
$pn=1;
}
elseif($pn>$last){
$pn =$last;
}
$l = ($pn - 1) * $rpp;
$this->db->limit($l, $rpp);
$row = $this->db->get('pages');
$dataString='';
foreach($row->result() as $r){
$id = $r->id;
$info = $r->info;
$dataString .= $id.'|'.$info.'||';
}
echo json_encode($dataString);
}
}
view part
function request_page(pn)
{
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
$.ajax({
type: "POST",
url: "<?php echo site_url('search/ajax')?>",
data: { 'rpp' : rpp , 'last' : last, 'pn' : pn},
dataType: "text",
success: function(msg){
// alert(msg)
;
var dataArray = msg.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "ID: "+itemArray[0]+" - Testimonial from <b>"+itemArray[1]+"</b><hr>";
}
results_box.innerHTML = html_output;
}
});
var paginationCtrls = "";
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
its easy
you should have a view to encode the data to json. Its just this:
<?php
$this->output->set_header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
In the controller you just have to load this view with an array as parameter (i think that stdClass is also valid):
$data['json'] = array("foo" => "bar", "bar" => "foo");
$this->load->view('your_json_view', $data);

JQuery Ajax multi array repsonse

I got the following problem. I want to display a multi array via ajax.
Javascript:
function getContent(HSID,HSname){
$.ajax({
url: 'ajax/script.gethandlungslogContent.php',
type: "POST",
data: { HSID : HSID },
dataType : "json",
success: function(data) {
document.getElementById('wartungslogHead').innerHTML = HSname;
document.getElementById('wartungslogContent').innerHTML = data.hl_aenderung;
document.getElementById('wartungslogID').value = data.HSID;
//document.getElementById('wartungslogID').value = data.KentID;
document.getElementById('buttonEdit').style.display = 'inline';
document.getElementById('buttonDelete').style.display = 'inline';
}
});
}
PHP Script:
<?php
include_once('../classes/class.mysql.php');
if (isset($_POST['HSID'])){$HSID = $_POST['HSID'];};
$HSID = 2;
$mydb3 = new DB_MySQL('localhost','','','');
$query3 = "SELECT * FROM hosting_handlungslog WHERE HSID = '$HSID'";
$mydb3->query($query3);
while ($row3 = $mydb3->fetchRow()){
echo json_encode($row3);
}
?>
The return of the php script looks like this:
{"HLID":"1","HSID":"2","hl_datum":"2014-01-19","hl_info":"n","hl_aenderung":"Windows-UpdatesJava Update"}
{"HLID":"2","HSID":"2","hl_datum":"2014-02-02","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"}
{"HLID":"3","HSID":"2","hl_datum":"2014-03-03","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"}
{"HLID":"4","HSID":"2","hl_datum":"2014-04-13","hl_info":"y","hl_aenderung":"Windows-UpdatesTomcat-Update auf 6.0.39Apache Update 2.4.8 (OpenSSL auf 1.0.1g)"}
{"HLID":"5","HSID":"2","hl_datum":"2014-04-14","hl_info":"n","hl_aenderung":"Zertifikatsaustausch wegen Heartbleed Bug"}
{"HLID":"6","HSID":"2","hl_datum":"2014-04-27","hl_info":"y","hl_aenderung":"Java Update auf 7.0.58"}
{"HLID":"7","HSID":"2","hl_datum":"2014-06-08","hl_info":"y","hl_aenderung":"Windows-UpdatesTomcat-Update auf 6.0.41Apache Update auf 2.4.9 (OpenSSL auf 1.0.1h)Java Update auf 7.0.60"}
{"HLID":"8","HSID":"2","hl_datum":"2014-07-21","hl_info":"y","hl_aenderung":"Apache Update auf 2.4.10Java Update auf 7.0.62"}
What to do here? Thanks in advance!
You must save it to another Array and show after gets all data from mysql.
<?php
include_once('../classes/class.mysql.php');
if (isset($_POST['HSID'])){$HSID = $_POST['HSID'];};
$HSID = 2;
$myjsonarray = null;
$mydb3 = new DB_MySQL('localhost','','','');
$query3 = "SELECT * FROM hosting_handlungslog WHERE HSID = '$HSID'";
$mydb3->query($query3);
while ($row3 = $mydb3->fetchRow()){
$myjsonarray[] = $row3;
}
echo json_encode($myjsonarray);
?>
And now you get this
[{"HLID":"1","HSID":"2","hl_datum":"2014-01-19","hl_info":"n","hl_aenderung":"Windows-UpdatesJava Update"},{"HLID":"2","HSID":"2","hl_datum":"2014-02-02","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"},{"HLID":"3","HSID":"2","hl_datum":"2014-03-03","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"},...]
Example show in php...
<?php
echo $myjsonarray[0]["HLID"];
echo $myjsonarray[1]["HLID"];
?>
In jquery you may use "for"
for(i=0;i<data.lenght;i++){
mydata = data[i];
alert(mydata["HSname"]);
}
Change your PHP to :
$tempArray = array();
while ($row3 = $mydb3->fetchRow()){
tempArray[] = $row3;
}
echo json_encode($tempArray);
Then in javascript:
success: function(data) {
$.each(data, function(index, item){
// Now loop through e.g.
$('body').append('<div class="wartungsLogID">' + item.HSID + '</div>');
});
}
In your javascript, in the success callback, you need to parse the json (var data).
If you have a table element, you can fill it with your data.
First you need a table and cycle:
var t = document.getElementById(mytableId);
for (var i = 1; i < data.length; i++)
...
inside the loop you need to create a row for every object inside your json:
var tr = document.createElement('tr');
var td = document.createElement('td');
td.innerHTML = data[i].hl_aenderung;
tr.appendChild(td);
t.appendChild(tr);
and repeat this for every field (every object's propery (hl_datum,hl_info,etc.)).
Within the Ajax Success callback you must loop through the array to display each object individually.
Below is an example, including some best practice techniques:
success: function(data) {
var textToDisplay = '';
$.each(data, function(i, item){
textToDisplay += '<li data-id="'+item.HLID+'">'+item.hl_aenderung+'</li>'
});
$('ul').append(textToDisplay);
}
Here's a working fiddle which you can expand on.

Php variable not getting incremented in jquery

I want to increment $j in $.each function of jquery. But $j is not getting incremented. What may be the reason. My code is as follows:
$.ajax
({
url : "test.php",
type : "post",
data : {
"categoryIds" : categoryIds
},
dataType : "json",
success : function(resp){
var html = "";
var i = 1;
<?php $j = 1; ?>
$.each(resp,function(key,questions ){
<?php
$j = 1;
$testdataIndex = "answer_".$j;
?>
var test = "<?php echo $testdataIndex?>";
alert(test);
var res = "<?php echo $_SESSION['testdata'][$testdataIndex]; ?> ";
var index = "<?php echo $j++;?>";
alert(index);
});
});
Each time test prints 'answer_1' and index as 1
Fixed session issue :
$.ajax
({
url : "test.php",
type : "post",
data : {
"categoryIds" : categoryIds
},
dataType : "json",
success : function(resp){
var html = "";
var i = 1;
<?php $j = 1; ?>
$.each(resp,function(key,questions ){
var testdataIndex = "answer_" + i ;
var filename = "getsession.php?sessionName="+testdataIndex;
$.get(filename, function (data)
{
sessionValues = data;
$("#"+testdataIndex).text(sessionValues);
});//get
html += '<textarea class="form-control answer" rows = "5" style="width:127%;" id="answer_'+i+'" name="answer_'+i+'" required="required"></textarea>';
i++;
});//each
});//ajax
getsession.php
<?php
session_start();
$sessionName = $_GET['sessionName'];
print ($_SESSION['testdata'][$sessionName]);
?>
I have answered my question for other who face same problem.

Appending new comment to the old comments division

I am trying to append new comment to the old comment box .
Here is my code , Dont know why its not working
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$(".bsubmit").click(function () {
var id = $(this).parent().parent().attr("id");
var comm = document.getElementById(id).getElementsByClassName("commentadd")[0].value;
$.ajax({
type: "POST",
url: "comment.php",
data: {
id: id,
comm: comm
},
cache: false,
success: function () {
$('.addcomment').slideUp('slow', function () {
// POSTED IN DATABASE SUCCESS NOW APPEND The comment with other COMMENTS
document.getElementById(id).getElementsByClassName(".itemcomment").append('<div class="comm">
<a href="profile.php?id=<?php echo $_SESSION['
fbid ']; ?> class="comm_img"><img src=" <?php echo $_SESSION['
smallest ']; ?> width="50" height="50" /></a>
<p width="50"><strong>
</strong></p>
</div>');
});
$('#load').fadeOut();
}
});
return false;
});
});
});
</script>
I think the error is in the code inside the "slideUp" callback, so I think the correct way to do it is:
Using regular JavaScript:
$('.addcomment').slideUp('slow', function () {
var elem = getElementById(id).getElementsByClassName(".itemcomment")[0],
div = document.createElement("div"),
a = document.createElement("a"),
p = document.createElement("p"),
img = document.createElement("img"),
strong = document.createElement("strong");
div.className = "comm";
a.className = "comm_img";
a.href = "profile.php?id=<?php echo $_SESSION['fbid ']; ?>";
img.src = "<?php echo $_SESSION['smallest ']; ?>";
img.width = "50";
img.height = "50";
p.width = "50";
p.appendChild(strong);
a.appendChild(img);
div.appendChild(a);
div.appendChild(p);
elem.appendChild(div);
});
Using JQuery:
$('.addcomment').slideUp('slow', function () {
var html = '<div class=comm>';
html += '<a href="profile.php?id=' + "<?php echo $_SESSION['fbid'];?>" + 'class=comm_img>';
html += '<img src="' + "<?php echo $_SESSION['smallest']; ?>" + 'width="50" height="50" /></a>';
html += '<p width="50"><strong></strong></p></div>';
$(".itemcomment", "#"+id).append(html);
});
Hope it helps!

Categories