In my cakephp application I am trying to create a commenting functionality. So I use an ajax request to get the comments and then clone an html template and append it to the page:
//load comments
$(document).ready(function(){
$.ajax({
type: 'POST',
url: '/app/tasks/getComments',
datatype: 'json',
beforeSend: function (xhr) { // Add this line
xhr.setRequestHeader('X-CSRF-Token', $('[name="_csrfToken"]').val());
},
data: {
task_id : "<?php echo $task->id; ?>"
},
success: function( data )
{
for (var i=0; i < data.length; i++)
{
//Clone the template
var item = $(template).clone();
document.cookie = 'photos['+i+']='+data[i].user.photo;
document.cookie = 'names['+i+']='+data[i].user.username;
//Find the element
$(item).find('#comment_photo').html('<?php if(isset($_COOKIE["photos[$num]"])) {echo $this->Html->image($_COOKIE["photos[$num]"], ["class" => "avatar avatar-online", "alt" => $currentUser->username]); } ?>');
$(item).find('#comment_username').html('<?php if(isset($_COOKIE["names[$num]"])) { echo $_COOKIE["names[$num]"]; }?>');
$(item).find('#comment_time').html(moment(data[i].created_date, 'DD-MM-YYYY hh:mm:ss').format('MMMM Do YYYY, h:mm:ss a'));
$(item).find('#comment_text').html(data[i].comment);
$(item).find('#comment_id').html(data[i].id);
//Append to the source
$('#target').append(item);
}
}
});
});
In order to access the returned results in php I store them in cookie arrays (photos[], names[]). How I can set and update the value of $num in order to iterate the arrays in every html code append? Is it possible to achieve what I want with this approach? Or I need a complete new one?
The solution was much simpler than I actually thought... I did it with JQuery like this:
.......
$(item).find('#comment_photo').prepend("<img src='/app/img/' class='avatar avatar-online'/>");
$(item).find('.avatar.avatar-online').prop('src', '/app/img/'+data[i].user.photo);
......
Related
I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);
Here i am passing javascript varaible into PHP function using AJAX ,here it will be working fine,** console.log(fname);** Here i got all values but append the tables means i am getting [object Object],how can solve this error
<script type="text/javascript">
$(document).ready(function(){
$("#reservation").on("change", function() {
var reservation = $(this).val();
$.ajax({
type: 'post',
url: 'date-range.php',
data: {
logindate: reservation,
},
success: function( data ) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
if(res['status']=="success"){
var htmlString='';
$.each( res['data'], function( key, value ) {
htmlString+='<tr>';
var ssm_id = value.ssm_id; // here i got ssmid
htmlString+='<td>'+value.ssm_id+'</td>';
htmlString+='<td>'+ $.ajax({
type: 'post',
url: 'config/functions.php',
data: {
ssm_id: ssm_id,
},
success: function( fname ) {
console.log(fname);//HERE I GOT ALL VALUES
htmlString+='<td>'+fname+'</td>';// BUT HERE I CAN'T APPENT THE VALUES IN TABLE
}
});+'</td>';
htmlString+='<td>'+'Muthuraja'+'</td>';
htmlString+='<td>'+'20-05-2016'+'</td>';
htmlString+='<td>'+'status'+'</td>';
htmlString+='<td>'+value.source+'</td>';
htmlString+='<td>'+ "<span style='color:green'>View Profile</span>"+'</td>';
/* htmlString+='<td>'+ "<span style='color:green'>Completed</span>"+'</td>';*/
htmlString+='</tr>';
});
$('#datatable-editable > tbody').empty().append(htmlString);
}
else{
$('#datatable-editable > tbody').empty().append("<center style='height:100px;padding-top:36px;color:red;font-size:17px;'><b>No matching records found</b></center>");
}
}
});
});
});
</script>
functions.php
<?php
$ssm_id = $_POST['ssm_id'];
if(!empty($ssm_id)){
echo firstname($ssm_id);
}
function firstname($id)
{
$f="SELECT firstname FROM register WHERE matri_id='$id'";
$rr=mysql_query($f);
while($row=mysql_fetch_array($rr)) {
$firstname = $row['firstname'];
}
return $firstname;
}
?>
Without knowing the exact format of your JSON, it's hard to give a definitive answer. However, assuming you have a JSON array of objects that represent your rows, you'd need to iterate over that array and for each object do the following:
Create a new <tr> element - var $tr = $('<tr/>');
For each item of information (I assume one item per <td>), create a <td> element and set its content - var $td = $('<td/>').html(x.y) (x is your current object, y is a field in the object) then append it to the row - $tr.append($td);.
Append the row before the last row in the existing table - $('.list-order tr:last').before($tr);
Following from the additional information provided in the question, the following code should do what you need to do:
success: function(result) {
//result is json format
var $tr = $('<tr/>');
$tr.append($('<td/>').html(result.itemname));
$tr.append($('<td/>').html(result.qty));
$tr.append($('<td/>').html(result.prices));
$('.list-order tr:last').before($tr);
}
So, I have the following ajax call:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data);// Need changes
});
Then my php:
function rhmain_tag() {
// 1. Getting wp tag list:
$args = array(
'orderby' => 'count',
'order' => 'DESC'
);
$tags = get_tags($args);
foreach ( $tags as $tag ) {
echo $tag->term_id;
}
//2. Getting "another.php" file
$template_part_path = 'page-parts/another_php';
get_template_part($template_part_path);
exit;
}
add_action('wp_ajax_ajax_call', 'ajax_call');
add_action('wp_ajax_nopriv_ajax_call', 'ajax_call');
As you can see, in the php function, there are two separate thing going on.
Getting tag list passed onto the js as variable.
echo $tag->term_id; shows a number like this "16508164981650616502165031650416505165071650116520." So, somehow I need to put comma in between each term id (not sure how) so it looks like this : "16508,16498,16506,16502,16503,16504,16505,16507,16501,16520"
Then I need to pass these values to js to be used as a variable (not sure how)
another_php file is passed onto js (Works fine).
Questions:
How to do I add "comma" in between the tag term_id?
How do I pass these tag values to js?
EDIT: Using json_encode to pass data
PHP
function rhmain_tag() {
$template_part_path = 'page-parts/another_job';
$return_data['another_job'] = get_template_part($template_part_path);
$return_data['tag_id'] = '16498';
echo json_encode($return_data);
exit;
}
add_action('wp_ajax_rhmain_tag', 'rhmain_tag');
add_action('wp_ajax_nopriv_rhmain_tag', 'rhmain_tag');
JS:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});
Using json_encode to send an array containing both data that you require front end you then need to make the following changes to your ajax function.
Change the dataType to json
Access the data as data.another_php and data.tag_id
The full ajax:
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'json',
data: ({ action: 'ajax_call'}),
success: function(data){
jQuery('.container').append(data.another_php);
var tag_list = data.tag_id;
});
To add the comma in between you could use a variable to store instead of echo'ing immediately. Like this :
$args=array(
'orderby'=>'count',
'order'=>'DESC'
);
$tags = get_tags($args);
$tag_list = "";
foreach ( $tags as $tag ) {
$tag_list += $tag->term_id + ",";
}
// Now trim the last comma
$tag_list = rtrim($tag_list, ",");
echo $tag_list;
Am trying to generate multiple line charts at one go using the code below. However, it isn't working. What would be the best way to generate graphs using a for/while or any other looping mechanism? I have many charts to generate.
var db_query = Array();
db_query[1] = <?php echo json_encode($db_query_1) ?>;
db_query[2] = <?php echo json_encode($db_query_2) ?>;
var chartConfig1 = clone(chartConfigLineOne);
var chartConfig2 = clone(chartConfigLineOne);
for(var i=1, len=2; i <= len; i++) {
/* chart initialization */
var chart_num = "chart" + i.toString();
var plot_num = "plot" + i.toString();
var chartConfig_num = "chartConfig" + i.toString();
/*alert(chart_num);
alert(plot_num);
alert(chartConfig_num);*/
chart_num = AmCharts.makeChart(plot_num, chartConfig_num);
$.ajax({
type: 'POST',
url: "query_db.php",
data: {'db_que': db_query[i]},
dataType: 'json',
context: document.body,
global: false,
async: true,
success: function(data) {
//alert(data);
chart_num.dataProvider = data;
chart_num.validateNow();
}
});
}
UPDATED CODE
<script type="text/javascript">
var chartNameList = ['chart1','chart2'];
var divId = ['plot1','plot2'];
var configList = ['chartConfig1','chartConfig2'];
var dbQuery = [];
var chartConfig1 = clone(chartConfigLineOne);
var chartConfig2 = clone(chartConfigLineOne);
dbQuery[0] = <?php echo json_encode($db_query_1) ?>;
dbQuery[1] = <?php echo json_encode($db_query_2) ?>;
/* chart initialization */
for(var i =0; i < 2; i += 1) {
//window["chart"+i] = createChartObj(divId[i],configList[i]);
execDbQuery(divId[i],configList[i],dbQuery[i],chartNameList[i]);
}
</script>
/**
* Execute of DB query
*/
function execDbQuery(divId, configObj, dbQuery, chartObj) {
chartObj = AmCharts.makeChart(divId, configObj);
$.ajax({
type: 'POST',
url: "query_db.php",
data: {'db_que': dbQuery},
dataType: 'json',
context: document.body,
global: false,
async: true,
success: function(data) {
//alert(data);
chartObj.dataProvider = data;
chartObj.validateNow();
}
});
}
As many comments correctly pointed out, you should probably start with rethinking your approach to data loading. Passing SQL queries in from client-side is asking for trouble. Will you be able to properly sanitize your queries to guard against malicious code? You can't be sure.
It's far more reasonable to move your DB access layer to PHP. You can pass in parameters needed for PHP script running on server to identify what needs to be loaded from DB and construct and execute actual SQL queries.
I.e.: query_db.php?chart_id=5
It would be up for PHP script to determine what to do. Given that you're currently using PHP to format those SQL queries, I can hardly image it can be a problem.
This brings us to another issue. Your current setup will run multiple AJAX requests simultaneously. While it's probably OK in the example you posted which has two charts, it can bog down the performance if you you have, say, 30 charts you need to load data for.
The solution would be to daisy-chain the loading. Do not start loading of another chart, until the previous one finishes loading. I.e.:
var charts = [ {
"name": "chart1",
"div": "plot1",
"config": clone( chartConfigLineOne ),
"query": <? php echo json_encode( $db_query_1 ) ?>
}, {
"name": "chart2",
"div": "plot2",
"config": clone( chartConfigLineOne ),
"query": <? php echo json_encode( $db_query_2 ) ?>
} ];
// do whatever modifications to each chart's config you need here
// ...
// function that creates the chart
function processNextChart() {
if ( charts.length ) {
var chart = charts.shift();
$.ajax( {
type: 'POST',
url: "query_db.php",
data: {
'db_que': chart.query
},
dataType: 'json',
context: document.body,
global: false,
async: true,
success: function( data ) {
chart.config.dataProvider = data;
chartObj = AmCharts.makeChart( chart.div, chart.config );
setTimeout( processNextChart, 100 );
}
} );
}
}
// process first chart
processNextChart();
Please note how I simplified your whole chart array with a single array that holds all applicable data.
Please note, that the above code is not live-tested and is meant as a guiding point for your own implementation.
Do not make ajax calls inside the for loop. It's a burden on server. The less calls you make, the more responsive is your ui. So, the better way to implement what you want is to get all data for all graphs in one ajax call and on success to iterate through the data building your graphs with AmCharts.makeChart.
I am using the well known ajaxForm Jquery Form Plugin (http://jquery.malsup.com/form/). I 'll present to you my code:
HTML code:
<script type="text/javascript">
$(document).ready(function() {
$('#users_form1').ajaxForm({
dataType: 'json',
success: processJson
});
});
function processJson(data) {
$("#first").val(data[1].elem1);
$("#second").val(data[1].elem2);
}
</script>
PHP code:
...
$result=$db->query($query);
if ($result->num_rows>=1)
{
$counter=0;
while ($row = $result->fetch_assoc()) {
$counter++;
$data1=$row["req_created"];
$data2=$row["subject"];
$temp[$counter] = array(
'elem1' => $data1,
'elem2' => $data2,
);
}
echo json_encode($temp);
}
As you may see from the above code, $temp is passed to var data inside function processJson. I'd like to know if array $temp is accessible outside processJson? For example, I want to choose $temp[3]["elem2"] upon a button click, however is it possible to get this data without searching again the database? If yes, how?
Thank you very much
You can have the data in variable, this will be like temporary storage.
<script type="text/javascript">
$(document).ready(function() {
$('#users_form1').ajaxForm({
dataType: 'json',
success: processJson
});
});
var tem_data;
function processJson(data) {
$("#first").val(data[1].elem1);
$("#second").val(data[1].elem2);
tem_data = data;
}
// Use tem_data anywhere;
</script>
But only last requested data will be the tem_data.
If you want all data then do it in array with array push method