php echo mysql array result in ajax - php

the below function is my controller code which is called by an ajax request:
function search_featured_candidates() {
$skills = $this->input->post('skills');
$this->load->model('Featured_candidate', 'featured', TRUE);
$result = $this->featured->get_featured_candidates_by_skills($skills);
if ($result) {
$str = "";
foreach ($result as $row) {
$str .= "Name: " . $row->candidate_name . "<br/>";
$str .= "Exp: " . $row->experience . "<br/>";
$str .= "Skills: " . $row->skills . "<hr/>";
}
$html = $str;
echo json_encode(array('html' => $html, 'success' => TRUE));
} else {
$html = 'No Candidates Found!';
echo json_encode(array('html' => $html, 'success' => FALSE));
}
}
my view code:
<script>
$(function() {
$("#featured_candidates").on("change paste keyup", function() {
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>mypage/search_featured_candidates/",
data: {skills: $(this).val()},
dataType: "json",
success: function(data) {
if (data.success === true) {
$("#featured").html(data.html);
} else {
$("#featured").html(data.html);
}
}
});
});
});
</script>
<div class="panel-body">
<div>
<input type="text" style="width: 100%"
name="featured_candidates" id="featured_candidates"
placeholder="keyword / skills" title="Featured Candidates"
/>
<br/><hr/>
</div>
<div id="featured">
<?php
foreach ($result as $row) {
echo "Name: " . $row->candidate_name . "<br/>";
echo "Exp: " . $row->experience . "<br/>";
echo "Skills: " . $row->skills . "<hr/>";
}
?>
</div>
</div>
now i am trying to display the result array using ajax like i have displayed in my view code using foreach. so to display it using ajax i have concatenated the array in my controller method in $str but it is not working while when i updated my controller method to this:
function search_featured_candidates() {
$skills = $this->input->post('skills');
$html = $skills ;
echo json_encode(array('html' => $html, 'success' => TRUE));
}
it is working fine..any help or suggesttion would be a great help...thanks in advance..

You have a mistake here
foreach ($result as $row) {
echo "Name: " . $row->candidate_name . <br/>";
echo "Exp: " . $row->experience . "<br/>";
echo "Skills: " . $row->skills . "<hr/>";
}
You forgot the "
. $row->candidate_name . "<br/>";
// ^ You forgot the "

The formulation of your question makes it difficult to know where your problem really is. But from a quick look you normally have to set proper headers in order to output json formatted data with PHP.
Try adding this before you do your echo, maybe this solves your problem:
header('Content-Type: application/json');

Related

Dependency of HTML rendering on function's return value that executes later?

I have a function that prints "Our data" first and then inside a loop checks for all the data in the database and then prints the data.
However, if there is no data, it shouldn't print "Our data", how do I achieve this since "Our data" is already printed?
The layout is as follows :
<h1> Our Data </h1>
<p> <!-- DATA --> </p>
The function is as follows:
function cpt_info($cpt_slug, $field_name, $title) {
echo "<h1>Our" . $title . "</h1>"; //here I want to print our data
$args = array('limit' => -1);
$cpt = pods($cpt_slug, $args);
$page_slug = pods_v('last', 'url');
echo "<h1 class='projects-under-" . $cpt_slug . "'>" . $title . "</h1>";
if ($cpt->total() > 0) :
while ($cpt->fetch()) :
if (!strcasecmp($cpt->field('post_name'), $page_slug)) :
$data = $cpt->field($field_name);
foreach ((array) $data as $key => $value) {
if ($value != null) : //here I check whether data is empty
$url = wp_get_attachment_url(get_post_thumbnail_id($value['ID']));
echo "<div class='col-sm-3 col-xs-6'><div class='border-to-circle'>";
echo "<div class='circle-container' style='background: url(" . $url . ")center center, url(" . get_template_directory_uri() . '/images/rwp-banner.jpg' . ")center center;'><h4><a href='" . get_permalink($value['ID']) . "'>" . $value['post_title'] . "</a></h4></div>";
echo "</div></div>";
endif;
}
endif;
endwhile;
endif;
}
Something like below:
if(count($data)){
echo '<h1> Our Data </h1>';
}

nestedSortable on codeigniter

I do sorting function with codeigniter for pages with "nestedSortable".. When i click submit button it doesnt find " {sortable: cSortable}"
my code example:
in views
$(document).ready(function() {
$.post('<?php echo site_url('admin/pages/order_ajax'); ?>', {}, function(data) {
$('#orderResult').html(data);
});
$('#save').click(function() {
oSortable = $('.sortable').nestedSortable('toArray');
$.post('<?php echo site_url('admin/pages/order_ajax'); ?>', {sortable: cSortable}, function(data) {
$('#orderResult').html(data);
});
});
});
in model file
public function save_order($pages) {
if (count($pages)) {
foreach ($pages as $order => $page) {
dump($page);
if ($page['item_id'] != '') {
$data = array('parent_id' => (int) $page['parent_id'], 'order' => $order);
$this->db->set($data)->where($this->_primary_key, $page['item_id'])->update($this->_table_name);
echo '<pre>' . $this->db->last_query() . '</pre>';
}
}
}
}
in the controller file
public function order_ajax() {
// save order from ajax call
if (isset($_POST['sortable'])) {
$this->page_m->save_order($_POST['sortable']);
}
//fetch all pages
$this->data['pages'] = $this->page_m->get_nested();
//fetch view
$this->load->view('admin/pages/order_ajax', $this->data);
}
I see this error http://i57.tinypic.com/2uj6wpd.jpg
another error:
<?php
echo get_ol($pages);
function get_ol($array, $child = FALSE) {
$str = '';
if (count($array)) {
$str .= $child == FALSE ? '<ol class="sortable">' : '<ol>';
foreach ($array as $item) {
$str .= '<li id="list_' . $item['id'] . '">';
$str .= '<div>' . $item['title'] . '</div>';
//do we have childrens ?
if (isset($item['children']) && count($item['children'])) {
$str .= get_ol($item['children'], TRUE);
}
$str .= '</li>' . PHP_EOL;
}
$str .= '</ol>' . PHP_EOL;
}
return $str;
}
?>
so i dont get it shows me on line 10 and 11 that could't find name and title
"TypeError: parentItem is null
pid = parentItem[2];"
Looks like a type, wrong variable name. Should cSortable actually be oSortable?

CodeIgniter appending to the beginning of the view when it shouldn't be

When I call regularDashboard(), it appends to the beginning of my view. In my view I'm calling $reg from inside a formatted style. So it shouldn't be echoing out at the beginning of the view... Any ideas as to why this is happening?
public function dcr() {
// pass all dashboard accesses through this function
$username = $this->session->userdata("username");
$query = $this->db->get_where('users', array('username' => $username));
$userType = $this->session->userdata('userType');
if ($userType == 'regular') {
foreach ($query->result() as $row) {
$data = array('reg' => $this->regularDashboard(), 'firstname' => $row->firstname);
$this->load->view('dashboard', $data);
} public function regularDashboard () {
$userid = $this->session->userdata('userid');
$results = $this->db->query("SELECT * FROM users");
foreach ($results->result() as $row) {
if($userid != $row->userid) {
echo $row->firstname . " " . $row->lastname;
echo "<form method='GET' action='processing/lib/process-send-friend-request.php?'>";
echo '<input name="accepted" type="submit" value="Send User Request" /><br />';
echo '<input name="AddedMessage" placeholder="Add a message?" type="textbox" />';
echo '<br>Select Friend Type: ' . '<br />Full: ';
echo '<input name="full_friend" type="checkbox"';
echo '<input type="hidden" name="id" value="' . $row->idusers . '" />';
echo '</form>';
echo "<br /><hr />";
} elseif ($userid == $row->userid) {
echo $row->firstname . " " . $row->lastname;
echo "<br />";
echo "You all are currently friends";
}
}
}
Views are buffered. When you echo something directly in a controller, it is sent before the buffer is flushed (therefore before the output containing the view is sent to the browser), that's why it appears before anything.
You shouldn't to this (sending a direct output/echoing something outside of views), you risk getting into troubles as soon as you use anything related to headers (redirect, cookies, CI's sessions...)
UPDATE:
To fix it, just assign all those string to a variable (as jeff showed), and send that to the view:
$data['form'] = $row->firstname . " " . $row->lastname;
$data['form'] .= "<form method='GET' action='processing/lib/process-send-friend-request.php?'>";
$this->load->view('formview',$data);
There, you just echo $form and you'll have all your strings output correctly.
EDIT :
all above if you're inside a Controller. If you're in a Model, just assign everything to a variable and return it to the Controller:
function regularDashboard()
{
$form = $row->firstname . " " . $row->lastname;
$form .= "<form method='GET' action='processing/lib/process-send-friend-request.php?'>";
return $form;
}
In the controller:
$data['form'] = $this->model->regularDashboard();
$this->load->view('formview',$data);
If you allow me, I'd suggest writing the form directly into the view, without the hassle (and the structural error) of creating something that's supposed to be "presentation" outdside of views.
It seems that your issue is the use of echo from within regularDashboard(). Try setting a variable that contains the form markup and return it instead of using echo.
Here is an example:
function regularDashboard()
{
$html = "";
$html .= "<form>";
//Append the rest of the form markup here
return $html;
}

jquery add to array then submit and pass data not working

My problem is:
I'm trying to submit an array of hidden input types, which are stacked into an array using jquery onclick, to a PHP file. However, when I try to count or even echo the passed variable in the php file (saveTest.php), no data appears or the count variable is zero.
I've searched and I found this guy's question:
pass an array from jQuery to PHP (and actually go to the page after submit)
I think I'm close to the above post but I'm still a newbie in jQuery so I don't understand much of the codes.
This is my jquery:
$(function(){
$("td").click(function(){
if($(this).hasClass("on"))
{
alert("Already marked absent");
}
else
{
$(this).addClass("on");
var currentCellText = $(this).text();
$("#collect").append("<input type='text' hidden = '" + currentCellText + "'/>" + currentCellText);
}
});
$("#clicky").click(function(){
$("td").removeClass("on");
$("#collect").text('');
$("#collect").append("Absentees: <br>")
});
});
<?php
session_start();
include 'connectdb.php';
$classID = $_SESSION['csID'];
$classQry = "SELECT e.csID, c.subjCode, c.section, b.subj_name, e.studentID, CONCAT(s.lname, ', ' , s.fname)name
FROM ENROLLMENT e, CLASS_SCHEDULE c, STUDENT s, SUBJECT b
WHERE e.csID = c.csID
AND c.csID = '" . $classID . "'
AND c.subjCode = b.subjCode
AND e.studentID = s.studentID
ORDER BY e.sort;";
$doClassQry = mysql_query($classQry);
echo "<table id='tableone'>";
while($x = mysql_fetch_array($doClassQry))
{
$subject = $x['subj_name'];
$subjCode = $x['subjCode'];
$section = $x['section'];
$studentArr[] = $x['name'];
$studentID[] = $x['studentID'];
}
echo "<thead>";
echo "<tr><th colspan = 7>" . "This is your class: " . $subjCode . " " . $section . " : " . $subject . "</th></tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
for($i = 0; $i < mysql_num_rows($doClassQry); $i++)
{
if($i % 7 == 0)
{
echo "</tr><tr><td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
else
{
echo "<td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
}
echo "</tr>";
echo "</tbody>";
echo "</table>";
?>
This is my php file (saveTest.php)
<?php
$absent = $_POST['absent'];
//echo "absnt" . $absent[] . "<br>";
echo count($absent);
?>
Add name to hidden field:
$("#collect").append("<input type='hidden' name="absent[] value= '" + currentCellText + "'/>" + currentCellText);
It looks like you want to submit a javascript array to a php script and then make use of it. You can make use of .each() function to loop through all the hidden values and adding them into the array. Then use $.post to submit the array to a php script.
<script src="jquery.js"></script>
<script>
$(function(){
$('#btn_submit').click(function(){
var array_hidden = [];
$('input[type=hidden]').each(function(index){
var current_value = $.trim($(this).val());
array_hidden[index] = current_value;
});
$.post('arraysubmit.php', {'hidden_array' : array_hidden}, function(data){
$('#results').html(data);
});
});
});
</script>
<?php for($x=0; $x<=10; $x++){ ?>
<input type="hidden" name="name[]" value="Name<?php echo $x; ?>">
<?php } ?>
<input type="button" id="btn_submit">
<div id="results"></div>
You can then access the array in the php script using the post variable and do whatever you want with it:
$_POST['hidden_array']

wrong return value with jquery ajax and codeigniter

I do not know if this is specifically a jquery problem, actually I think it has to mostly do with my logic in the php code.
What Im trying to do is make a voting system that when the user clicks on the vote up or vote down link in the web page, it triggers an ajax call to a php function that first updates the database with with the required value, on success of the database updating the another function is called just to get the required updated html for the that particular post that the user has voted on. (hope I havnt lost you).
The problem I think deals with specifically with this one line of code. When I make the call it only returns the value of $row->beer_down and completly ignores everything else in that line. Funny thing is the same php code to display the html view works perfectly before the ajax function updates it.
echo "<p>Score " . $row->beer_up + $row->beer_down . "</p>";
so here is the code to hope you can help as I have absolutely no idea how to fix this.
here is the view file where it generates the page. This part is the query ajax function.
<script type="text/javascript">
$(function() {
$(".vote").click(function(){
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='up') {
$.ajax({
type: "POST",
url: "http://127.0.0.1/CodeIgniter/blog/add_vote/" + id,
data: dataString,
cache: false,
success: function(html) {
//parent.html(html);
$("." + id).load('http://127.0.0.1/CodeIgniter/blog/get_post/' + id).fadeIn("slow");
}
});
}
else
{
$.ajax({
type: "POST",
url: "http://127.0.0.1/CodeIgniter/blog/minus_vote/" + id,
data: dataString,
cache: false,
success: function(html) {
//parent.html(html);
$("." + id).load('http://127.0.0.1/CodeIgniter/blog/get_post/' + id).fadeIn("slow");
}
});
}
return false;
});
});
</script>
Here is the html and php part of the page to display the post.
div id="post_container">
<?php //echo $this->table->generate($records); ?>
<?php foreach($records->result() as $row) { ?>
<?php echo "<div id=\"post\" class=\"" . $row->id . "\">"; ?>
<h2><?php echo $row->id ?></h2>
<?php echo "<img src=\"" . base_url() . $dir . $row->account_id . "/" . $row->file_name . "\">" ?>
<p><?php echo $row->content ?></p>
<p><?php echo $row->user_name ?> On <?php echo $row->time ?></p>
<p>Score <?php echo $row->beer_up + $row->beer_down ?></p>
<?php echo anchor('blog/add_vote/' . $row->id, 'Up Vote', array('class' => 'vote', 'id' => $row->id, 'name' => 'up'));
echo anchor('blog/minus_vote/' . $row->id, 'Down Vote', array('class' => 'vote', 'id' => $row->id, 'name' => 'down'));
echo anchor('blog/comments/' . $row->id, 'View Comments');
?>
</div>
<?php } ?>
here is the function the ajax calls when it is successfull:
function get_post() {
$this->db->where('id', $this->uri->segment(3));
$records = $this->db->get('post');
$dir = "/uploads/user_uploads/";
foreach($records->result() as $row) {
echo "<div id=\"post\" class=\"" . $row->id . "\">";
echo "<h2>" . $row->id . "</h2>";
echo "<img src=\"" . base_url() . $dir . $row->account_id . "/" . $row->file_name . "\">";
echo "<p>" . $row->content . "</p>";
echo "<p>" . $row->user_name . " On " . $row->time . "</p>";
echo "<p>Score " . $row->beer_up + $row->beer_down . "</p>";
echo "<p>Up score" . $row->beer_up . "beer down" . $row->beer_down . "</p>";
echo anchor('blog/comments/' . $row->id, 'View Comments');
echo "</div>";
}
Ok I solved the problem, it seems that I needed to perform the add operation of the two values beer_up and beer_down before I could echo it out. Adding a + in between string concatenation is a no go.
Thanks for everyone helping out.

Categories