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" );
}
}
});
Related
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.
I want to create a dropdown list that populated by another dropdown list. I'm using AJAX and PHP.
I have created my AJAX file like this:
<?php
if(isset($_POST['selname']))
{
include('config.php');
$clientId = $_POST['selname'];
$query = "SELECT tv.*, v.* FROM t_vorder tv LEFT JOIN m_vehicle v ON tv.tv_vehicleid = v.v_id WHERE tv_orderid = '$clientId'";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$namek = "";
$namek .= $row['v_id'];
if($row['v_jenis'] != "" || !empty($row['v_jenis']))
{
$namek .= ' - '.$row['v_jenis'];
}
if($row['v_platno'] != "" || !empty($row['v_platno']))
{
$namek .= ' - '.$row['v_platno'];
}
if($row['v_merk'] != "" || !empty($row['v_merk']))
{
$namek .= ' - '.$row['v_merk'];
}
$xx .= "<option value='$row[v_id]'>$namek</option>";
}
return $xx;
exit;
}
?>
After that, I called this AJAX file to my main program, here's my JQuery code:
function getVehicle()
{
var selname = $("select[name=noorder]").val();
$('#combobox2').html('');
$.ajax({ url: "getVehicle.php",
data: {"selname":selname},
type: 'post',
dataType: "json",
success: function(output) {
console.log(output);
$('#combobox2').append(output);
}
});
}
And last is my HTML code:
<select name="noorder" id="combobox" class="form-control">
//get my vehicle from database
<?php
$querycon = mysqli_query($conn, "SELECT * FROM m_order WHERE o_status='1' ORDER BY o_id");
while($rowcon = mysqli_fetch_array($querycon, MYSQLI_ASSOC))
{
$invoice = sprintf("%s%"."04d", $rowcon['o_code'], $rowcon['o_id']);
?>
<option value="<?php echo $rowcon['o_id']; ?>"><?php echo $invoice; ?></option>
<?php
}
?>
</select>
<select name="kendaraan" class="form-control" id="combobox2" onclick="getVechile();">
</select>
My Ajax works fine, my console log return that the file finished load. But my dropdown list not appended by Jquery. Anyone know where's my mistakes?
You did't request for json obj/data into ajax success callback, then no need for dataType: "json", inside ajax properties. Remove that and change return $xx; into echo $xx;
AJAX request gets data from PHP file only when its printed out on the page.
Returning and data from PHP (AJAX backend) to jQuery/Javascript does not mean anything.
Change
return $xx;
to
echo $xx;
You use the dataType: "json" in your ajax call, so it get response in JSON. First remove dataType: "json" line from ajax call. Then replace return $xx; with echo $xx; in your php script.
Hope this solution may works for you, Thanks!
I've got a form where users can choose a car brand. After that I send an SQL-query with Ajax to fill the next select with all the models of the selected brand.
When the form is submited I check it via PHP and if there is any error I return to the previous form with an error-message and fields filled.
The problem is that the 'model' field has the "trigger" set on brand change.
How can I fix this: call the jquery again (to show the models in the select) and display the previous model as selected?
Ajax.php
if ($_POST['brand_car']) {
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $_POST['brand_car']);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
echo json_encode($model);
}
jQuery
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
}}
});
});
XHTML + PHP
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
There are various ways you can fix it.
jQuery Approach
I think the simplest way is to refractor your change() and seperate the ajax call from the change event, like so:
$('#brand_car').change(function () {
var id = $(this).children(":selected").attr("id");
getModels(id, 0);
}
function getModels(id, select) {
if(id!=0)
$.ajax({
url: '/js/ajax.php',
dataType: 'json',
type: "POST",
data: {brand_car: id},
success: function(data){
$('#model_car').html('<option id="0" value="0">choose the model</option>');
if (data.length > 0) {
data.forEach(function (elem) {
$('#model_car').append('<option value="' + elem.id + '" id="' + elem.id + '">' + elem.modele+ '</option>');
});
$('#model_car').val(select);
}}
});
}
This allows you to make an AJAX call by calling getModels(). So all you have to do is call it:
<select id="brand_car" name="brand_car">
<?php
$sql = "SELECT id_brand_car, name_brand_car FROM brand_car";
$req = $dbh->query($sql);
foreach ($req as $row) {
$val=$row['id_brand_car'];
echo '<option value="'.$row['id_brand_car'].'" id="'.$row['id_brand_car'].'" title="'.$row['nom_brand_car'].'"';
if($_SESSION['brand_car'] == $val ){echo ' selected';} // If return from the check_form.php
echo ' >'.$row['nom_brand_car'].'</option>';
}
?>
</select>
<select id="model_car" name="model_car">
<option></option>
</select>
Tag this at the end:
<?php
echo '<script>getModels('.$_SESSION["brand_car"].', '.$_SESSION['model_car'].');</script>';
?>
This way the code is also more testable. This isn't a perfect solution and you should definitely consider using $(function(){}); to make sure the document is ready. AJAX request also needs time to complete, so that models won't be there instantaneously when the page loads.
PHP Approach
Alternatively, you could consider reusing your AJAX code. Wrap it into a function:
function getModels($dbh, $brand_car) {
// I know nothing about your design, but globals are no good
$sql = "SELECT id_model_car, name_model_car FROM model_car WHERE id_brand_car = :idBrand";
$req = $dbh->prepare($sql);
$req->bindValue(':idBrand', $brand_car);
$req->execute();
$model = array();
foreach ($req as $row){
$model[] = array(
'id' => $row['id_model_car'],
'modele' => $row['name_model_car']
);
}
return $model;
}
AJAX.php
if ($_POST['brand_car']) {
echo json_encode(getModels($dbh, $_POST['brand_car']));
}
In your XHTML + PHP
<select id="model_car" name="model_car">
<?php
foreach(getModels($dbh, $_SESSION["brand_car"]) as $model) {
echo '<option name="'.$model["id"].'" id="'.modelp["id"].'">'.$model["modele"].'</option>';
}
?>
</select>
PS. It looks like your $_SESSION['brand_car'] is never updated.
how to retrieve much data in view (codeigniter) using while(). if I use foreach, I can't get the desired result. this is my code:
//my view home.php
$(document).ready(function(){
$('#check').click(function(event){
event.preventDefault();
var form_data = {
name: "xxxx"
};
$.ajax({
url: 'http://localhost:8000/jqjx/index.php/cont/getname',
type: 'POST',
async : false,
data: form_data,
dataType: 'html',
success: function(resp){
$('#content').html(resp);
}
});
return false;
});
});
//my controller cont.php
public function getname()
{
$data = array();
$namex = $this->input->post('name');
if($q = $this->my_model->detail_data($namex))
{
$data['data_detail'] = $q;
$this->load->view('tamp_page', $data);
}
}
my helper page (view) tamp_page.php
<?php
if(isset($data_detail))
{
foreach ($data_detailas $row) {
echo $row['name']."<br/>";
echo $row['birthday']."<br/>";
}
}
?>
if I use :
<?php
if(isset($data_detail))
{
echo $name_data['id_transactions'] . "<br/>";
echo $name_data['goods'] . "<br/>";
}
?>
it's still work but just for 1 data result. so how I can loop more much data.. thanks..
<?php
if(isset($data_detail))
{
foreach ($data_detail as $row)
{
echo $row['name']."<br/>"; //$row['name] was not properly closed. single quote(') was missing
echo $row['birthday']."<br/>";
}
}
?>
Just basic use of foreach:
if(isset($data_detail)){
foreach ($data_detailas as $row) {
echo $row['name'] . "<br/>";
echo $row['birthday'] . "<br/>";
}
}
I made an ajax form with json response. The json array contains information out of a mysql database. Now I want to show these datas in a table.
I made a placeholder in the html file which is hidden.
Here my Code for the ajax/json part:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
//alert(select.ID[0]);
//alert(select.ID[1]);
//alert(select.ID.length);
$("#coffee_talk").fadeOut();
$("#coffee_talk").fadeIn();
}
});
return false;
});
This is my html:
<p class="bold underline headline">Bereits eingetragen:</p>
<form id="coffee_talk_year" action="include/scripts/select_event.php" method="post" accept-charset="utf-8">
<select name="year_coffee_talk" id="year_coffee_talk">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2008; $i<=$year; $i++){
if ($i == $year) {
echo "<option value=\"".$i."\" selected=\"$i\">".$i."</option>\n";
} else echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<button id="select_coffee_talk_year">anzeigen</button>
<input type="hidden" name="coffee_talk_year_submit" value="true" />
</form>
<br />
<div id="coffee_talk"></div>
<br />
<button id="add_coffee_talk">hinzufügen</button>
select_event.php:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
/*******************************/
/** Erzaehlcafe auswählen
/*******************************/
if (isset($_POST['coffee_talk_year_submit'])) {
$getID = array();
$getDate = array();
$getTheme = array();
$getContributer = array();
$getBegin = array();
$getPlace = array();
$getEntrance = array();
$getFlyer = array();
$sql = "SELECT
ID,
Date,
Theme,
Contributer,
Begin,
Place,
Entrance,
Flyer
FROM
Coffee_talk
WHERE
YEAR(Date) = '".mysqli_real_escape_string($db, $_POST['year_coffee_talk'])."'
";
if (!$result = $db->query($sql)) {
return $db->error;
}
while ($row = $result->fetch_assoc()) {
$getID[$i] = $row['ID'];
$getDate[$i] = $row['Date'];
$getTheme[$i] = $row['Theme'];
$getContributer[$i] = $row['Contributer'];
$getBegin[$i] = $row['Begin'];
$getPlace[$i] = $row['Place'];
$getEntrance[$i] = $row['Entrance'];
$getFlyer[$i] = $row['Flyer'];
$i++;
}
$result->close();
$response['ID'] = $getID;
$response['Date'] = $getDate;
$response['Theme'] = $getTheme;
$response['Contributer'] = $getContributer;
$response['Begin'] = $getBegin;
$response['Place'] = $getPlace;
$response['Entrance'] = $getEntrance;
$response['Flyer'] = $getFlyer;
echo json_encode($response);
}
}
Div with id=coffee_talk is my placeholder. Now I wish to fade in the table with its data and if I change the year and submit it with the button I wish to fade the old one out and fade new in.
My only problem is that I need to write this table in php with loops. But I think its not possible in Java Script. What should I do?
PS I used ajax cause I dont want to have a reload all the time.
Your quick solution would be:
$("#select_coffee_talk_year").button().click(function() {
var form = $('#coffee_talk_year');
var data = form.serialize();
$.ajax({
url: "include/scripts/select_event.php",
type: "POST",
data: data,
dataType: 'json',
success: function (select) {
var coffee_talk = $("#coffee_talk");
coffee_talk.fadeOut('fast', function() {
for(i in select) {
row = select[i];
div = coffee_talk.append('<div id="row_'+i+'" />');
for(column in row) {
div.append('<span class="column_'+column+'">'+row[column]+'</span>');
}
}
coffee_talk.fadeIn();
});
}
});
return false;
});
For a nicer approach you should lookup Moustache.js which is a client side JavaScript templating engine (which has equivalents in PHP/Java/Ruby/Python/Go and other languages and is based on Google CTemplates).
It will allow you to create HTML templates and populate them with the data you have in a variable such as the JSON variable an AJAX request might receive.