Updating list using AJAX in Codeigniter (within a form) - php

I have a form that adds clients to a database clients/add_client. The add_client method has a parameter of $state which is passed to another method list_centers(). When someone is talking to a potential client, they have all of our centers in a sidebar. There is a <select> above the list of centers in which lists the states where we have centers. When they change the select to another state, it should list all of the centers in that state. Now, I have this working by passing the parameter in the URL like this: localhost/clients/add_clients/GA lists all of the centers in Georgia. The problem is that I want to do this with AJAX and not have the page refresh. I cannot figure out how to pass this data via ajax. I know that I have to reconstruct the list each time but I am stuck. Here is what I have tried:
$('#center_select').change(function(){
var data = $(this).val();
var url = 'add_client/' + data;
$.ajax({
type: 'POST',
dataType: 'html',
data: data,
url: url,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
return false;
});
Just in case you need the method:
public function add_client($state = false) {
$this->load->model('centers_model');
$data = array(
'page_title' => 'Add Client',
'client_status' => $this->clients_model->list_client_status(),
'centers' => $this->centers_model->list_centers(null, $state),
'center_states' => $this->centers_model->list_center_states(),
);
$this->load->view('header');
$this->load->view('clients/add_client', $data);
$this->load->view('footer');
}
View:
<div class="col-sm-3">
<aside id="centers_sidebar" class="well">
<h2>List of Centers</h2>
<select class="form-control" name="center_select" id="center_select">
<option value="all">All</option>
<?php
foreach ($center_states as $center_state) {
echo '<option value="' . $center_state->center_state . '">' . $center_state->name . '</option>';
}
?>
</select>
<ul id="center_list">
<?php
foreach ($centers as $center) {
$output = '<li class="center">';
$output .= '<h5>' . $center->center_name . '</h5>';
$output .= '<p>' . $center->center_type . '</p>';
$output .= '<p>' . $center->center_city . ', ' . $center->center_state . '</p>';
$output .= '<p>' . $center->center_phone . '</p>';
$output .= '</li>';
$output .= '<hr>';
echo $output;
}
?>
</ul>
</aside>
</div>

I failed to notice that you request a POST but setup for a GET. So here we supply the proper structure to ajax.data
select handler
$('#center_select').change(function () {
var st = $(this).val();
var url = 'update_centers';
$.ajax({
type: 'POST',
dataType: 'html',
data: {state: st},
url: url,
success: function (data) {
console.log(data);
$("#center_list").html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
//useful for trouble shooting & error handling
console.log(textStatus, errorThrown);
}
});
return false;
});
AJAX responder method - builds html to send back to ajax.success
We need to pull the input from $_POST (using input->post)
I've put in a bunch of validity checks and a general purpose ajax error response function too. No extra charge.
function update_centers()
{
$this->load->model('centers_model');
$state = $this->input->post('state');
if(!isset($state))
{
$this->ajax_bad_request_error("No state data received");
return;
}
$centers = $this->centers_model->list_centers(null, $state);
if(!isset($centers))
{
$this->ajax_bad_request_error("The database failed to find centers in $state");
return;
}
$output = "";
foreach($centers as $center)
{
$output .= "<li class='center'><h5>$center->center_name</h5>"
."<p>$center->center_type</p>"
."<p>$center->center_city, $center->center_state</p>"
."<p>$center->center_phone</p></li><hr>";
}
echo $output;
}
function ajax_bad_request_error($msg)
{
//All purpose reporting of ajax failure
header('HTTP/1.1 400 Bad Request');
header('Content-Type: application/json; charset=UTF-8');
$data = array('type' => 'error', 'message' => $msg);
echo json_encode($data);
}
Cannot guarantee this will work perfectly as is - syntax errors may exist. But the concept is sound.

Related

Receiving empty response from jquery Ajax from a php file

I am making a commenting reply system in PHP jquery and Ajax. So far I managed to make the commenting and reply to comment action with php and jquery ajax. When I reply to a comment, i receive back from the jquery ajax the number of replies to a comment and i print the number on the screen. Now what i want to do next is printing the reply to the screen after it was submitted. I made the jquery ajax function and wrote my php script. Then I echo the $output formated from the php back to the ajax. The problem is i am receiving blank response nevertheless i tested the php file directly and it is working perfectly and outputting to the screen the $output variable. Please help. Here is my ajax part that takes care of the output replies :
<script type="text/javascript">
load_replies();
function load_replies() {
$.ajax({
url: "widgets/board_reply_fetch.php?comment_id=<?php echo
$board_comment_id_number;?>",
method: "POST",
success: function(data){
$("#reply_comment").html(data);
console.log(data);
}
});
}
</script>
and here is my php file :
<?php
require_once '../includes/session.php';
require_once '../includes/functions.php';
require_once '../includes/validation_functions.php';
if (isset($_GET["comment_id"])) {
$comment_id = (int)$_GET["comment_id"];
$reply_data = find_board_replies_by_comment_id($comment_id);
$output = "";
$output_array = array();
while ($reply_assoc = mysqli_fetch_assoc($reply_data)) {
$reply_comment_id = $reply_assoc['comment_id'];
$reply_board_id = $reply_assoc['board_id'];
$reply_user_id = $reply_assoc['user_id'];
$reply_text = $reply_assoc['reply'];
$reply_timestamp = $reply_assoc['reply_timestamp'];
$reply_user_data = find_user_data_by_id($reply_user_id);
$profile_image = $reply_user_data['profile_picture'];
$profile_image_thumb = "../uploaded_pictures/profile/$reply_user_id/" . $reply_user_id . "small.png";
if ($profile_image == "") {
if ($comment_user_data['gender'] == "Male"){
$user_profile_picture = "../images/ProfilePicMale.png";
} else {
$user_profile_picture = "../images/ProfilePicFemale.png";
}
} else {
$user_profile_picture = $profile_image_thumb;
}
$full_name = ucfirst(htmlentities($reply_user_data['first_name'])) . " " . ucfirst(htmlentities($reply_user_data['last_name']));
$time_of_post = time_of_post($reply_timestamp);
$the_reply_text = nl2br($reply_text);
$output = "<div class=\"reply_comment_div\">";
$output .= "<a href=\"profile.php?user_id=$reply_user_id\" class=\"board_comments_div_picture\">";
$output .= "<img src=\"$user_profile_picture\" width=\"50px\" height=\"50px\" /></a>";
$output .= "$full_name";
if ($reply_user_id == $_SESSION['user_id']){
$output .= "Edit";
$output .= "Delete";
}
$output .= "<div class=\"board_comment_submited_on\">submitted $time_of_post</div>";
$output .= "<span class=\"comment_content_span\">$the_reply_text</span>";
$output .= "</div>";
$output_array[] = $output;
}
foreach ($output_array as $array) {
echo $array;
}
}
?>
try to store you data that is being sent to php page in data object
example:
<script type="text/javascript">
load_replies();
function load_replies() {
var commment_id = "<?php echo $board_comment_id_number;?>";
$.ajax({
url: "widgets/board_reply_fetch.php",
data:{commentId:commment_id },//commment_id store it here
method: "GET",
success: function(data){
$("#reply_comment").html(data);
console.log(data);
}
});
}
</script>
Use POST METHOD:
if (isset($_POST["comment_id"])) {
$comment_id = (int)$_POST["comment_id"];

Unable to use jquery.html() with ajax response

I have a problem when trying to select the <li> inside a <ul> list from an ajax response using jQuery.html();
This is my AJAX request:
if (searchid != '') {
$.ajax({
type: "POST",
url: "/service/search.php",
data: dataString,
cache: false
}).done(function (html) {
$("#result").html(html).show();
var images = $("#result").find(".dbRows.sixth").html();
console.debug(images);
})
.fail(function (jqXHR, textStatus) {
$("#explainMessage").html('Unable to check at the moment. Please retry later').show();
})
}
return false;
and in php I have this code:
if ( mysqli_num_rows($result)==0)
{
$display = '<div id="explainMessage" class="explainMessage">Sorry, this was not found.</div>';
echo $display;
} else {
$counter = 0;
while ($row = $result->fetch_assoc()) {
++$counter;
$image_filename = $row['image_filename'];
$imageFolder = $_SERVER['DOCUMENT_ROOT'] . '/service/img/';
$imageList = scandir($imageFolder, 1);
$imageLink = '/service/img/' . $image_filename;
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $image_filename);
$pattern = '/^(' . quotemeta($withoutExt) . ').*$/';
$display = '<div class="dbRows sixth" style="display:none"><ul>';
foreach ($imageList as $image) {
if (preg_match($pattern, $image)) {
if (in_array($image, $imageList)) {
$display .= '<li><img src="' . $imageLink . '" /></li>';
}
}
};
$display .= '</ul></div>';
echo $display;
the problem is that when I try to use the AJAX.done(); function, in my console I have just <ul></ul> without the list of images.My question is, why i can't select the code inside the <ul> tags even if the list of images is actually in the code? I'm pretty new with PHP, any help will be really appreciated. Thanks in advance.
You are doing it wrong. As I doubt before asking you for response HTML, you have blank `'.
$("#result").find(".dbRows.sixth").html() will print html for first matched element only.
Try this, if you want to fetch html for all matched element:
$("#result").find(".dbRows.sixth").each(function(){
console.log($(this).html());
});
From a quick look I can see a few problems. In your php change your first line of code from <div class="dbRows sixth" style="display:none"><ul>'; to $display = '<div class="dbRows sixth" style="display:none"><ul>';
I'd probably change this: var images = $("#result").find(".dbRows.sixth").html(); to this: var images = $("#result > .dbRows.sixth");.
Then add images.show(); and console.log(images.html());. Not tested but might get you on the right track.

how to properly insert html with jquery

I am using this bit of PHP to return a chunk of html:
if ($action = "update")
{
connect_db();
$query = mysql_query("SELECT * FROM convo ORDER BY date ASC") or die (mysql_error());
while($row = mysql_fetch_array($query))
{
$output = $output . '<p>';
$output = $output . '<b>From:</b> ' .$row['from'];
$output = $output . ' <b>To:</b> ' .$row['to'];
$output = $output . ' <b>Message:</b> ' .$row['content'];
$output = $output . "<br />";
$output = $output . '</p>';
}
//htmlentities($output);
header('Content-Type: application/json');
echo json_encode( $output );
}
And then insert it into a <div> with this bit of jQuery:
function update(){
$.ajax({
type: "GET",
url: "actions.php",
data: {
'action': 'update'
},
dataType: "json",
success: function(data)
{
console.log('update called');
console.log( data);
$('#history').text( data );
//$('#status').text('sent!');
}
});
setTimeout(update, 5000);
}
The ajax call works and returns the correct html however when inserted it is not formatted, I can see all the html code in the browser. See example picture:
Should be using something other than .text?
You are creating JSON in php, and using json dataType for no reason when you want html.
Just output the html string in php and remove the dataType:'json from AJAX.
echo $output ;
Then instert using html() method
$('#history').html( data );
The load() method is ideal for your case. It is a $.ajax shortcut method. You could replace all the AJAX you have with:
$('#history').load("actions.php", { 'action': 'update'},function(){
console.log('new content inserted now')
})
API reference: http://api.jquery.com/load/
change $('#history').text( data ); to $('#history').html( data );

Ajax form return variables to php

I have another question:
Ajax Forms are working well. Most of them need to do mysql stuff and only return values if the entry could be written or not. I used just echo statements. For example echo "1"; if the values could be written and echo "2"; if the values could not be written.
Now I need to call back 3 variables. I know that I can write them in an array. My problem is just, that I can't return this variable into my visible site.
This is my JavaScript Code:
//Show statistic
$('.statistic_submit').click(function(){
if ($('#month').val() == 'none' || $('#year').val() == 'none') {
$("#dialog_empty").dialog( "open" );
return false;
}
var form = $('#statistic_view');
var data = form.serialize();
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
success: function (reqCode) {
if (reqCode == 1) {
//Show generated table
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
if (reqCode == 2) {
//No values found
$('.done').fadeOut('slow');
$("#dialog_error").dialog( "open" );
}
}
});
return false;
});
This is my html code:
<div>
<form id="statistic_view" action="include/scripts/user_statistic.php" method="post">
<select name="month" id="month">
<option value="none" class="bold italic">Monat</option>
<?php
for($i=1; $i<=12; $i++){
if($i == $month)
echo "<option value=\"".$i."\" selected>".$month_name[$i]."</option>\n";
else
echo "<option value=\"".$i."\">".$month_name[$i]."</option>\n";
}
?>
</select>
<select name="year" id="year">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2012; $i<=$year; $i++){
if($i == $year)
echo "<option value=\"".$i."\" selected>".$i."</option>\n";
else
echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<br/><br/>
<div id="user_statistic">
<input type="submit" id="small" class="statistic_submit" value="Daten anzeigen">
</div>
</form>
<br />
<div class="done">
<p class="bold center"><?php echo "Besucher ".$month_name[$month]." ".$year; ?></p>
<canvas id="cvs" width="680" height="250">[No canvas support]</canvas>
<script>
chart = new RGraph.Line('cvs', <?php print($data_string) ?>);
chart.Set('chart.tooltips', <?php print($labels_tooltip) ?>);
chart.Set('chart.tooltips.effect', 'expand');
chart.Set('chart.background.grid.autofit', true);
chart.Set('chart.gutter.left', 35);
chart.Set('chart.gutter.right', 5);
chart.Set('chart.hmargin', 10);
chart.Set('chart.tickmarks', 'circle');
chart.Set('chart.labels', <?php print($labels_string) ?>);
chart.Draw();
</script>
</div>
</div>
And this my user_statistic.php:
... (mysql stuff)
/******************************/
/** Create diagram
/******************************/
$labels = array();
$data = array();
for ($j=1; $j<=$days; $j++) {
$labels[$j] =$j;
$data[$j] = $day_value[$j];
}
// Aggregate all the data into one string
$data_string = "[" . join(", ", $data) . "]";
$labels_string = "['" . join("', '", $labels) . "']";
$labels_tooltip = "['" . join("', '", $data) . "']";
//data written
echo "1";
So echo "1"; tells my script that everything is fine. But now I need $data_string, $labels_string and $labels_tooltip. So how can I return these values from user_statistic.php into my side?
Avoid converting arrays to strings on your own. If you need to pass a PHP array back to your jQuery, you should do so with the json_encode function:
echo json_encode( $array );
This will come through as a JSON object which you can then handle client-side. Your JSON string will be returned into the callback of your $.ajax method:
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
dataType: 'json',
success: function ( response ) {
/* response is your array, in JSON form */
}
});
For instance, if our PHP script did the following:
$response = array(
'message' => 'Success',
'allData' => array( 'Jonathan', 'Mariah', 'Samuel', 'Sally' )
);
echo json_encode( $response );
We could alert the message from our jQuery like this:
success: function ( response ) {
alert( response.message );
}
The best approach here would be to return a json object. Create an array on server side -
$response['error_code'] = '1'; //everything ok. 0 if not ok
$response['data_string'] = 'this will have some data';
$response['labels_string'] = 'labels';
$response['labels_tooltip' = 'here goes the tooltips';
echo json_encode($response);
and in your javascript code, mention the return datatype as json -
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
dataType: json,
success: function (reqCode) {
if (reqCode.error_code == 1) {
alert('this is the data string '+resCode.data_string);
//Show generated table
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
if (reqCode.error_code == 2) {
//No values found
$('.done').fadeOut('slow');
$("#dialog_error").dialog( "open" );
}
}
});

Correct syntax to get my Ajax function to work

The following code will not do what I hoped, that is run the Ajax function when the div ="dist" li
created by the PHP code's is clicked.
Guidance please.
<?php
// ...
$result = mysql_query($sql);
echo "<div class=\"dist\">";
echo "<ul>";
while ($row = mysql_fetch_array($result)) {
echo "<li><a href=\"devplan.php?search-n=" . $row['NAME'] .
"&" . rawurlencode($row['PLAN']) . "\"" . ">" .
$row['PLAN'] . "</a></li>";
};
echo "</ul>";
echo "</div>";
?>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
});
});
</script>
Here is a starter for ten - I've corrected some additional braces and added error handling. If you still get an error, at least you#ll be able to tell us what it is.
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I'd add a console.log(urlplan) right after the click event handler. make sure that returned value works if you manually enter
php/dpdetails.php?q=test&anotherVar=5
into the address bar.
What does console.log(urlplan) return?
Here is a sample piece of code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>What</title>
</head>
<body>
<?php
$anchorList = "";
$rows = array(
array(
'NAME' => 'me1'
, 'PLAN' => 'thePlan1'
)
, array(
'NAME' => 'me2'
, 'PLAN' => 'thePlan2'
)
);
$anchorList .= "<div class=\"dist\">";
$anchorList .= "<ul>";
foreach ($rows as $row) {
$anchorList .= "<li>";
$anchorList .= createAnchorTag($row['NAME'], $row['PLAN']);
$anchorList .= "</li>";
}
$anchorList .= "</ul>";
$anchorList .= "</div>";
echo $anchorList;
function createAnchorTag($name, $plan) {
return "" . $plan . "";
}
?>
</body>
</html>
<script type="text/javascript" src="../scripts/jquery-1.4.2.modified.js"></script>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>
In your click function you need to return false in order to override the anchor tags wanting to redirect.
[EDIT]
I believe your actually looking to parse the href attribute of the anchor tag and pass it to the Ajax, right? If so use this script:
<script type="text/javascript">
$(document).ready(function() {
$('.dist a').click(function() {
var urlquery = $(this).attr('href').val();
// regex would be better than split, could create a more generic function
var urlparts = urlquery.split('&');
var urlplan = urlparts[1];
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>

Categories