I'm doing an calendar, and i created a page to show the events from a certain day.
I'm using Ajax because i dont want my users to reload the page everytime that a new event is created.
So, i'm using Json encode to get the values from an array, and everytime that i print a day with two events, i receive this:
[{"event_day":"9","event_name":"test"}, {"event_day":"9","event_name":"test2"}]
But when i try to print the elements in JQuery to put inside an element, i receive [object Object]
I inserted the array inside a while loop because i'm getting multiple rows from my database table.
PHP function
function eventPrint($list_day, $month, $year){
$select = mysql_query("SELECT * FROM events WHERE event_day = '".$list_day."' AND event_month = '".$month."' AND event_year = '".$year."'") or die(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($select)) {
$event_day = $row['event_day'];
$event_name = $row['event_name'];
$data[] = array('event_day' => $event_day,
'event_name' => $event_name
);
}
echo json_encode($data);
}
Ajax
$.ajax({
type: 'get',
url: "modules/groups/new.php",
data: {
'list_day': getday,
'month': getmonth,
'year': getyear,
'action': 'selection'
},
success: function (response) {
var obj = jQuery.parseJSON(response);
$('.' + getmonth).html(obj.event_day);
}
});
Your code should be:
success: function( response ) {
var obj = response[0] ? response : jQuery.parseJSON(response);
$('.' + getmonth).html(obj[1].event_day);
Related
I've got a php script with collects data from a server and displays it in an array and after that as a json with the function.
echo json_encode($result);
Now I want to access that array with my javascript and display it. It should be saved in a var as an array so it should look like:
data = [ "xxxx" , "ssss",];
But I guess I can simply put in my function which gets the array data instead so it'd be:
data = myfunction ;
What I've tried so far:
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
};
oReq.open("get", "http://myserver.com/myscript.php", true);
oReq.send();
and
function getdata(url) {
jQuery.ajax(
{
type: "GET",
url: "http://myserver.com/myscript.php/",
dataType: "text",
success: function (response) {
var JSONArray = jQuery.parseJSON(response);
connsole.log(JSONArray);
}
});
}
But none seems to work and I get displayed 'undefined' instead of my arrays.
Would be really great if somebody has some ideas on that and can help me out.
Edit:
Since we are getting nowhere here's my php code:
<?php
error_reporting(0);
$html = file_get_contents("url here");
$dom = new DOMDocument();
$dom->loadHTML($html);
$tbodyRows = $dom->getElementsByTagName( 'tbody' )
->item( 0 ) // grab first tbody
->getElementsByTagName( 'tr' );
$result = array();
foreach( $tbodyRows as $tbodyRow )
{
$result[] = $tbodyRow->getElementsByTagName( 'td' )
->item( 2 ) // grab 3rd column
->nodeValue;
}
echo json_encode($result);
?>
Try this code:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "text",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
Open the browser's console, and let me know about its contents. If you don't see Error or Success, your code isn't actually executing
I have done a similar thing earlier. I will describe it and I wish it will help you.
In the following code (get_categories.php), I am retrieving data from the database and add them to an array. Then return it by encoding as a JSON.
$sql = "SELECT category_name FROM category;";
$dataArray = [];
$result = $connection->query($sql);
if ($result) {
while ($row = $result->fetch_assoc()) {
$dataArray[] = $row;
}
echo json_encode($dataArray);
}
Then in my Javascript code, I can get the data as follows.
$.ajax({
url: "/get_categories.php",
type: "GET",
dataType: "json",
success: function (categories) {
for (var i = 0; i < categories.length; i++) {
console.log(categories[i]);
}
},
error: function (jqXHR, textStatus, errorThrown) {
// Error handling code
}
});
I want php file to return data (from the database) on ajax call. Ajax call returns an error alert everytime. I tried everything, but have no idea how to return array from PHP to ajax call
So far, I made this..
ajax call
function dohvatiPrveTriAkcije(id){
var url = 'http://localhost/ljekarna/model/akcija.php';
$.ajax({
type: "POST",
url: url,
cache: false,
data: { "kategorija": id},
dataType: "json",
success: function (data) {
document.getElementById("kat_id").innerHTML += 'aaa';
},
error: function () {
alert('Pojavila se greška pri dohvacanju akcija za odabranu kategoriju');
}
});
return null;
}
php class
<?php
require_once 'baza_model.php';
$akcija = new Akcija();
if (isset($_GET['kategorija'])) {
echo $_GET['kategorija'];
$akcije = $akcija->dohvatiPrveTriAkcijeZaKategoriju($_GET['kategorija']);
echo $akcije;
}
class Akcija{
private $baza;
static function dohvatiPrveTriAkcijeZaKategoriju($kategorija){
$baza = new Baza();
$akcije = array();
$upit = 'SELECT lijek.naziv, akcija.postotak, akcija.datum_zavrsetka FROM akcija join lijek on akcija.lijek = lijek.id
join kategorija on lijek.kategorija = kategorija.id
where akcija.datum_zavrsetka > CURDATE() AND kategorija.id = ' . $kategorija . ' AND akcija.status = 1
ORDER BY akcija.datum_zavrsetka ASC LIMIT 3';
$rez = $baza->selectDB($upit);
while($red = $rez->fetch_assoc()){
echo "id: " . $red["id"];
$akcije[] = $red;
}
return $akcije;
}
}
I also tried this...
You need a json formatted string returned by the server. Use json_encode() instead of trying to echo out your array (which is what's giving you your array to string error).
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);
}
Hi I was able to display a json data(List of conversation result) but I want to display them just like how I display records from database like this:
foreach(res->fetchAll(PDO::FETCH_ASSOC) as result):
$username = $result['username'];
$message = $result['message'];
endforeach;
are there any similar procedure like this but with json_encode() ?
here is my php script
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT * FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$rows = $stmt7->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
This php script are getting its data from my ajax script below
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.ajax({
url: "includes/getChat.php",
type: "GET",
data: data,
dataType: 'json',
success: function(result){
var container = $("#clog");
$.each(result, function(i, message) {
$.each(message, function(key, value) {
container.append($('<p />').html(key + ':' + value));
});
});
}
});
The php and javascript are working fine the JSON are being displayed.. But I'm trying to figure out if there is a way that I can display only the username and the message just how I use the foreach statement that I mentioned above...
I may be misunderstanding, but you should be able to filter what is displayed by adding a condition with an if
$.each(result, function(i, message) {
$.each(message, function(key, value) {
if (key == "username" || key == "message")
container.append($('<p />').html(key + ':' + value));
});
});
I have a page like this:
Basically, I pick 2 dates and hit the button, then the data below will change without refreshing this page.
Here is the code in controller:
if( $this->request->is('ajax') ) {
$this->autoRender = false;
//if ($this->request->isPost()) {
print_r($this->request->data);
// get values here
echo $from=( $this->request->data('start_time'));
echo $to= $this->request->data('end_time');
Debugger::dump($from);
Debugger::dump($to);
//$this->layout = 'customer-backend';
$this->Order->recursive=-1;
$this->Order->virtualFields['benefit']='SUM(Product.product_price - Discount.product_discount)';
$this->Order->virtualFields['number']='COUNT(Order.order_id)';
$option['joins'] = array(
array('table'=>'discounts',
'alias'=>'Discount',
'type'=>'INNER',
'conditions'=>array(
'Order.discount_id = Discount.discount_id',
)
),
array('table'=>'products',
'alias'=>'Product',
'type'=>'INNER',
'conditions'=>array(
'Discount.product_id = Product.product_id'
)
)
);
$option['fields']= array('Discount.product_id','Product.product_name','benefit','number');
$option['conditions']=array('Discount.start_time >='=>$from);
$option['group'] = array('Discount.product_id','Product.product_name');
//$option['limit']=20;
$products = $this->Order->find('all',$option);
//Debugger::dump($products);
$this->set('products',$products);
//}
}
else
{
$from='27 November 2012';
//$this->layout = 'customer-backend';
$this->Order->recursive=-1;
$this->Order->virtualFields['benefit']='SUM(Product.product_price - Discount.product_discount)';
$this->Order->virtualFields['number']='COUNT(Order.order_id)';
$option['joins'] = array(
array('table'=>'discounts',
'alias'=>'Discount',
'type'=>'INNER',
'conditions'=>array(
'Order.discount_id = Discount.discount_id',
)
),
array('table'=>'products',
'alias'=>'Product',
'type'=>'INNER',
'conditions'=>array(
'Discount.product_id = Product.product_id'
)
)
);
$option['fields']= array('Discount.product_id','Product.product_name','benefit','number');
$option['conditions']=array('Discount.start_time >='=>$from);
$option['group'] = array('Discount.product_id','Product.product_name');
//$option['limit']=20;
$products = $this->Order->find('all',$option);
$this->set('products',$products);
}
If the request is ajax, it gets 2 values $from and $to from the POST and pass them to the SQL query. If the request is not ajax (mean the access this page for the first time when the dates havent picked yet), $from and $to are assigned default values.
Here is my ajax in view:
<script>
$(function(){
$('#btnSubmit').click(function() {
var from = $('#from').val();
var to = $('#to').val();
alert(from+" "+to);
$.ajax({
url: "/project/cakephp/orders/hottest_products",
type: 'POST',
data: {"start_time": from, "end_time": to },
success: function(data){
alert("success");
}
});
});
});
it gets data from 2 date picker then send it to the controller as a POST method.
My problem is that after I choose 2 dates and hit the button, nothing happens. the data doesnt change according to the dates.
Any thoughts about this. Thanks in advance.
When opening your page and running the following in the console:
$(".tab_container").html("loaded from ajax");
The products table now only shows "loaded from ajax". If the content of the products table is generated by it's own template you can have cakephp render that template only when it's an ajax call: http://book.cakephp.org/2.0/en/controllers.html
$this->render('/Path/To/ProductTable/');
If your cakephp will output only the product table when an ajax call is made you could try to run the following code:
var from = "2000-01-01";
var to = "2014-01-01";
$.ajax({
url: "/project/cakephp/orders/hottest_products",
type: 'POST',
data: {"start_time": from, "end_time": to }
}).then(
function(result){
$(".tab_container").html(result);
},function(){
console.log("fail",arguments);
}
);