Yii - ajax call on mouseover and get Data - javascript

Index File
<h4>Dates</h4>
<?php
foreach($dates as $date){
echo TbHtml::ajaxButton(date("D, d M" ,strtotime($date->date)),
array(
'matches/countryVenue'
),
array(
// 'dataType'=>'json',
'type'=>'POST',
'data'=>array('id'=>$date->id),
'success'=>'js: function(data) {
alert(data);
}',
'failure'=>'js: function(data) {
alert("error");
}',
),
array(
"id"=>$date->id,
"onmouseover"=>"date(this.id);"
)
);
echo "<br>";
}
?>
</div>
JS Code
<script>
function date(x){
//alert("Date " + x);
};
</script>
Matches Controller File :
public function actionCountryVenue(){
if(isset($_POST['id'])){
$id = $_POST['id'];
}
// echo $id;
$criteria = new CDbCriteria();
$criteria->select = "*";
$criteria->condition = "DATE = ".$id;
$countryVenue = Matches::model()->findAll($criteria);
if(!empty($countryVenue)){
echo CJSON::encode(array('countryVenue'=>$countryVenue));
}
}
My Question
I need help from someone to give an exact idea of callback and ajax.
Moreover what I plan to do is onmouseover of the ajaxButton, I want to make an ajax call sending the ID of the button to the controller and return json data from the controller and convert into php array.
Edit Info
I have managed to send the data from the controller to the index file but can not render json data in php.

Related

Convert PHP variable to JQuery

Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery
View:
<?php
foreach ($muziek as $ms)
{
if ($ms->id == 2) {
echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
echo '</audio>';
}
}
foreach ($muziek as $ms)
{
echo '<br>';
echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
}
?>
</div>
<script>
$("input").click(function () {
var test = $(this).attr("id");
console.log(test);
//Here needs to be the foreach muziek
});
</script>
Muziek variable:
This is how i fill the music variable
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
return $muziek;
}
Does someone has an idea or show me how this can be done?
I spent sometime trying to figure out what you want and from what i understood you want to return an array of all muzieks returned to your js to do whatever you wanna do with it, which you can simply get with a simple ajax request:
$.get( "base_url/your_controller/getAllMuziek" )
.done(function( muziek ) {
//Here needs to be the foreach muziek
$.each(muziek, function( index, value ) {
// whatever
});
});
with a simple modification to your method getAllMuziek:
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
header('Content-Type: application/json');
echo json_encode($muziek);
}
now when you make you ajax call you will get your result.
Convert $muziek into javascript array using json_encode
<script>
var myArray = <?php echo json_encode($muziek); ?>;
</script>

how to use lastInsertId() if the column called different

i have a function which insert my data into my database. But at the same time i want that my javascript add the content to my list #div.
my php file
function xhrInsertPost() {
// echo $_POST[''];
$title = $_POST['title'];
$msg = $_POST['msg'];
$sth = $this->db->prepare('INSERT INTO posts (post_title, post_content) VALUES (:title, :msg) ');
$sth->execute(array(
':title' => $title,
':msg' => $msg
));
$data = array( 'post_title' => $title, 'id' => $this->db->lastInsertId());
echo json_encode($data);
}
my js file
$('#postText').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.post(url, data, function(data) {
console.log(data);
console.log(data.msg);
$('#listMsg').append('<tr><td>' + data.post_title + '</td><td><a class="del" rel="'+ data.post_id + '" href="#"> delete</a></td></tr>');
}, 'json');
return false;
});
i think it didn't work because my column called different. my code works but my "data.post_id" is undefined.. in my other method (if i refresh the page) it works

Get JSON format from MySql to javascript using PHP

i want to get the json format from my SQL database using PHP
here is a capture of mySql database
data.php
<?php include("include/connexion.php");
$requete = "SELECT * from statistika";
$resultat = mysql_query( $requete ) or die( mysql_error() );
$rows = array();
$total_vue = 0;
here is the php code to get the data
while( $data = mysql_fetch_assoc( $resultat ) ) {
$total_vue+=$data['temps'];
$rows[] = array(
"date" => strtotime( $data['date']) * 1000,
"value" => $data[ 'temps' ]
);
}
?>
json_encode.php
<?php
include("data.php");
echo json_encode($rows);
?>
The content of json_encode is valid and i get the json format successfully
[{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
Now i want to pass the JSON format to javascript , i am using this code
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo.toString);
the problem is that when printing foo.toString i get this
function () { return [{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
i don't want function () { return to appear in the output !!!
Any hints ?
thanks .
Change this line in your JS code
From
foo.toString = function () { return <?php echo json_encode($rows);?> };
To
foo.toString = '<?php echo json_encode($rows);?>';
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo());
You are creating foo as function so call like this you will get only json.

Why my php array return only recent/last post activities

I create a jquery which sent data to a php file and after query(If any data found at sql) php return data to jquery by json_encode for append it.
Jquery sent two type data to php file:
1st: page id
2nd: post ids (a jquery array sent them to php file)
If I used print_r($_REQUEST['CID']); exit; on php file for test what he get from jquery, Its return and display all post ids well.
But if I make any reply on particular post, Its only return recent post reply.
That means, if I have 3 post like: post-1st, post-2nd, post-3rd ; my php return only post-3rd activities.
I want my script update any post reply when it submitted at sql.
my wall.php
// id is dynamic
<div class="case" data-post-id="111"></div>
<div class="case" data-post-id="222"></div>
<div class="case" data-post-id="333"></div>
//Check for any update after 15 second interval by post id.
<script type="text/javascript" charset="utf-8">
var CID = [];
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});
function addrep(type, msg){
CID.forEach(function(id){
$("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul>"+ msg.detail +"</ul></div>");
});
}
var tutid = '<?php echo $tutid; ?>';
function waitForRep(){
$.ajax({
type: "GET",
url: "/server.php",
cache: false,
data: {
tutid : tutid,
CID : CID
},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(
waitForRep,
15000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(
waitForRep,
15000);
}
});
}
$(document).ready(function(){
waitForRep();
});
</script>
server.php (may be problem in my array or something else)
while (true) {
if($_REQUEST['tutid'] && $_REQUEST['CID']){
foreach($_REQUEST['CID'] as $key => $value){
date_default_timezone_set('Asia/Dhaka');
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE post_id =".$value." AND qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
} // array close
$rows = mysqli_fetch_assoc($res);
$row[] = array_map('utf8_encode', $rows);
$data = array();
$data['id'] = $rows['id'];
$data['qazi_id'] = $rows['qazi_id'];
//ect all
// do something and echo $data['detail'] = $detail;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} // request close
sleep(5);
} // while close
Try to declare CID array like this:
var CID = new Array();
It looks like you're looping through the CIDs and running an SQL query for each one, but you're only retrieving the results once, outside of the loop. You'll only get the last query's results if you run
$rows = mysqli_fetch_assoc($res);
outside of the CIDs foreach loop.
#koc:
Unfortunately, it won't be as simple as moving the closing loop bracket. If you're trying to retrieve multiple datasets in one AJAX call, then you'll need to handle multiple datasets in your AJAX's success callback, or in your addrep() function. Here's one way to do it, but you can do it many different ways depending on what you're ultimately trying to do:
while (true) {
if($_REQUEST['tutid'] && $_REQUEST['CID']){
$data = array();
foreach($_REQUEST['CID'] as $key => $value){
date_default_timezone_set('Asia/Dhaka');
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"
SELECT *
FROM comments_reply
WHERE post_id =".$value."
AND qazi_id=".$_REQUEST['tutid']."
AND date >= '$datetime'
ORDER BY id DESC LIMIT 1
") or die(mysqli_error($dbh));
$row = mysqli_fetch_assoc($res)
$data[] = array_map('utf8_encode', $row);
} // array close
//$rows = mysqli_fetch_assoc($res);
//$row[] = array_map('utf8_encode', $rows);
//$data = array();
//$data['id'] = $rows['id'];
//$data['qazi_id'] = $rows['qazi_id'];
//ect all
// do something and echo $data['detail'] = $detail;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} // request close
sleep(5);
} // while close
then in your Javascript:
...
success: function(data){
for (var i=0, len=data.length; i<len; i++) {
addrep("postreply", data[i]);
}
setTimeout(waitForRep, 15000);
},
...
But again, that's just an example. I don't really know what your datasets look like or how you want the data to be passed around and used. This is just an idea that hopefully gets you going in the right direction.

How can i add a variable in AJAX URL

I have a function in php that need an id and i need to add a variable in my ajax url the id
PHP Code:
function get_json_selected($purpose)
{
//echo $this->input->post("ids");
$ids = explode(",", $this->input->post("ids"));
$site_url = site_url($this->router->class);
if ($purpose == "EQUIPEMENT"){
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get("equipments a")->result_array();
echo json_encode(array("spares" => $result));
} else {
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get($this->active_table." a")->result_array();
echo json_encode(array("spares" => $result));
}
}
Ajax Code:
this is just example of the variable of id.
$purpose = "EQUIPMENT"; // how can i add this php variable to ajax url
url: "<?=site_url('equip_request/get_json_selected');?>", // this is the current code how can i add id in this url
or is this code right?
url: "<?=site_url('equip_request/get_json_selected/'.$purpose);?>"
var purpose = '<?php echo json_encode($purpose); ?>';
url: 'example.php?=' + purpose;
+ is the concatenator in javascript. hope this helps. spend plenty of time and add plenty of security to echoing that var into javascript. else you could find yourself viction of xss.

Categories