Get PHP variabile in div from ajax call [duplicate] - php

This question already has answers here:
jQuery UI Datepicker onchange event issue
(19 answers)
Closed 5 years ago.
I have this code in default.php:
jQuery(document).ready(function() {
jQuery(function($) {
var $from = jQuery("#from"),
$to = jQuery("#to");
$from.datepicker({
numberOfMonths: 1,
minDate: 1,
dateFormat: 'dd-mm-yy',
onClose: function(selectedDate) {
$to.datepicker("option", "minDate", selectedDate);
}
});
$from.change(function() {
jQuery.ajax({
url: 'index.php?option=com_vehiclemanager&task=default2',
type: 'POST',
data: {
datepicker_value: $(this).val()
},
success: function(data) {
$('#result').html(data);
}
});
});
...
This is the php script:
<?php
$database = JFactory::getDBO();
$datepicker_value = isset($_POST['datepicker_value']) ? $_POST['datepicker_value'] : NULL;
$month = date("m",strtotime($datepicker_value));
$selectstring = "SELECT * FROM #__vehiclemanager_rent_sal WHERE fk_vehiclesid = 128 AND monthW = '$month'";
$database->setQuery($selectstring);
$string = $database->loadObject();
header('Content-Type: application/json');
$array[] = array(
'deposito'=>$string->deposit,
'spese'=>$string->cfee,
);
echo json_encode($array);
?>
I have a jquery datepicker in a table and i want to pick the variable from the php script via a database query with an ajax call, i can see the json object [{"deposito":"300","spese":"100"}]
but the single php variabile shows me undefined.
I inserted the task in the ajax url because the filename sends me back to the index.php, the homepage, as this is an external plugin.
I hope I explained myself and thanks for your help.

Instead of $(this).val(), try referencing the actual element. Something like this: $('#from').val().

Related

Updating (refreshing) PHP variable without refreshing website

I am trying to make updating variable called $online without refreshing site.
Theres is my try:
data.php
<?php
include("steam.php");
$data = $online;// obtain current value of data from somewhere
echo $data; // should be an integer
?>
refresh.js
$(document).ready( function () {
var data = []; // data is empty
var graph = Morris.Bar({
element: 'graph',
data: data
labels: ['random label']
});
function update () {
$.getJSON( "data.php", function (newv) {
data.push( { x: newv, y: "Today" } ); // store new value
graph.setData( data ); // update the graph
});
}
update();
setInterval( update, 1000 );
});
I just ran this through so I know it works. My previous comment will do the job. I know $.getJSON is similar so I don't know what conflicts you will have there, but the below will update your php variable.
<script>
$.post( "data.php", { online: "UpdatedData" } );
</script>
data.php
$online = $_POST['online'];

Find data attribute and insert it to database using ajax

I need a correct script for iserting data attribute to database onclick using ajax.
HTML:
<li><a data-cat="random name">Button</a></li>
jQuery:
$('li a').click(function() {
$(this).data('cat');
// Dont know how correctly use ajax here.
});
PHP:
$cat = HERE MUST BE DATA ATTRIBUTE;
$timer = time();
$something = NULL;
$stmt = $db->prepare("INSERT INTO table (cat, timer, something) VALUES(:cat, :timer, :something)");
$stmt->execute(array(':cat' => $cat, ':timer' => $timer, ':something' => $something,));
Sorry for bad english, and thanks for any answers.
More info at about jQuery.post()
$('li a').click(function() {
var category = $(this).data('cat');
$.ajax({
type: "POST",
url: '/script.php',
data: {'cat': category}
});
});
PHP
$cat = $_POST['cat'];

ajax code stops running when I pass a string from PHP

php
$sortBy = array('upload_date','wall_views','wall_downloads');
$sort = 'upload_date';
if(isset($_GET['sort']) && in_array($_GET['sort'], $sortBy)){
$sort = $_GET['sort'];
}
ajax script
<script type="text/javascript">
var per_page = <?php echo $per_page;?>; //$per_page = 3
var last_page = <?php echo $last_page;?>; //$last_page = 4
var sort = <?php echo $sort;?>; //$sort = upload_date
$(function(){
$('.more').live('click', function(){
var page = $(this).attr('id'); //get the last id
$.ajax({
type: 'GET',
url: 'pagination.php',
data: {page: page, per_page: per_page, last_page: last_page, sort: sort},
success: function(data){
$('#itemContainer').append(data);
}
}); //ajax code end
}); //live end
}); //function end - when DOM is ready.
</script>
the problem occurs when I try to pass a string (upload_date) variable to ajax, I'm not sure if I'm passing the string correctly, this code works fine if only integers/digits are passed into the code. What I'm I doing improperly here? please help.
You'll have to add quotes around string variables. otherwise your generated javascript will look like variable names rather than string literals.
Like so:
var sort = "<?php echo $sort;?>"; //$sort = upload_date

PHP: Unable to get the json output into my javascript page as a variable value [duplicate]

This question already has answers here:
php : how to pass database value into a javascript/jquery function
(3 answers)
Closed 9 years ago.
i have to get output in this format
var sampleTags = ['c++', 'scala'];
My javascript function is:
<script>
$(document).ready(function(){
$(function(){
var sampleTags;
$.ajax({
url:"<?php echo base_url('ajax_get_tags/gettags'); ?>"
}).done(function(data) {
if (data) {
sampleTags = data;
}
});
......................
.......................
$(function(){
var sampleTags = <?php echo json_encode($query) ?>;
My php controller is
function gettags(){
$json_array=$this->tagsmodel->get_all_tags();
echo json_encode($json_array);
}
My model is
//-------------------------------Function get all tags--------------------------------
function get_all_tags() {
$this->load->database();
$this->db->limit('10');
$this->db->select('tags_name');
$res = $this->db->get('tags');
$ret = array();
foreach ($res->result_array() as $row) {
$ret[] = $row['tags_name'];
}
return $ret;
}
How can get the json output from ajax request to be display its value for a javascript variable?
Please help me to solve this issue..
You're using an older version of jQuery, so .done won't work. It looks like you want to add a key to your request object called complete, with the anonymous function as its value:
$.ajax({
url: "<?php echo base_url('ajax_get_tags/gettags'); ?>",
complete: function(data) {
if (data) {
sampleTags = data;
}
}
});
I found this out by googling your error message. One of the results was this question: Object #<XMLHttpRequest> has no method 'done'. You could have just googled the error message and figured this out yourself.
I would like to give a few suggestions
Check for the return value form the server side by printing it with die or exit.
check the http response in firebug net tab.
3.

jquery datepicker ui with ajax and php issue

i want to use jquery datepicker to pick a date then when select it to do select query from the database according to the selected date
i've seek about that and found this question
jQuery datepicker with php and mysql
they say i should use ajax to do it
but i can't understand the implementation they do!
can anybody help please
i try to do something like that
<script>
$(function() {
$( "#datepicker" ).datepicker({minDate: 0, showAnim: "bounce",
onSelect: function(dateText, inst) {<?php mysql_select_db($database_conn, $conn);
$query_time = "SELECT reservation.R_time FROM reservation WHERE reservation.R_date='"?>dateText<?php "'" ;
$time = mysql_query($query_time, $conn) or die(mysql_error());</script>
Change your JS to send an ajax call in the onSelect, passing the dateText.
$( "#datepicker" ).datepicker({
minDate: 0,
showAnim: "bounce",
onSelect: function(dateText, inst) {
$.ajax({
type: 'POST',
url: 'select_time.php',
data: {date : dateText},
success: function(resp){
if(false !== resp){
alert(resp);
}
}
});
}
});
Then in select_time.php
<?php
if(!empty($_POST['date'])):
$mysqli = new mysqli('connection info'); //mysqli connection
$stmt= $mysqli->prepare('SELECT reservation.R_time FROM reservation WHERE reservation.R_date = ?'); //prepare the statement
$stmt->bind_param('s', $_POST['date']); //bind our parameters
$stmt->execute(); //execute our query
$stmt->store_result(); // store result so we can check rows
$stmt->bind_result($resTime); //we only want the reserveration time
$stmt->fetch(); //fetch the rows
if($stmt->num_rows() > 0):
echo $resTime; //return the time from the database
$stmt->close(); //close the statement
else:
return false; //row doesn't exist, return false
endif;
endif;
?>
This is untested, but I don't see any reason why it shouldn't work.
I think you're confusing a couple of things:
First, the PHP will always run before the page is loaded (and therefor the jQuery), so calling the PHP on the jQuery selector will never work.
What you need to do is create an ajax function that will fire on the jQuery's onSelect (and I generally use the onClose event if it is a popup calendar).
Javascript:
$( "#datepicker" ).datepicker({
minDate: 0,
showAnim: "bounce",
onClose: function(dateText, inst) {
$.post('select_time.php?dateText=' + dateText, function(queryResult){
// do something with the return query
});
}
});
PHP page:
$connection = mysqli_connect("localhost","username","password","db");
$sql = "SELECT reservation.R_time FROM reservation WHERE reservation.R_date={$_post['dateText']}";
if ($result = mysqli_query($connection , $sql))
{
while ($getData = mysqli_fetch_field($result))
{
echo $getData->R_time;
}
mysqli_free_result($result);
}
mysqli_close($connection);

Categories