Jan Jan - 3 months ago 16
PHP Question

how to call a javascript function from php

I am trying to read selected option (month) from mysql database via tabela.php (php then selects only users and their hours for he month selected). At this moment when i select a option i get results but it is shown in new site which is tabela.php. How can i make ajax or script to show me results on my HTML site.

For example: table on html is first empty, user then selects Januar and below that selection table should autofill with correct results.
HTML:

<form action="tabela.php" method="post">
Mesec: <select name="meseci", onchange="this.form.submit()">
<option value="o"> </option>
<option value="1">Januar</option>
<option value="2">Februar</option>
</select><br><BR>
</form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#results').load('tabela.php');
}, 3000); // the "3000" here refers to the time to refresh the div. it is in milliseconds.
});


php:

$conn = new mysqli($servername, $username, $password, $dbname);
$x = (isset($_POST['meseci']) ? $_POST['meseci'] : null);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, "SELECT ime, stevilo_ur FROM smart_ure WHERE mesec = '$x ' ");
echo "<table border='1'>
<tr>
<th>ime</th>
<th>stevilo_ur</th>
</tr>";
while ( $db_v = mysqli_fetch_assoc($result) ) {

echo "<tr>";
echo "<td>" . $db_v['ime'] ."</td>";
echo "<td>" . $db_v['stevilo_ur'] ."</td>";
echo"</tr>";
}
echo "</table>";

mysqli_close($conn);

if (isset ($_GET['update']))
{
echo $tbl;
die ();
}


EDITED:

<form method="post" id="test_form">
Mesec: <select id="meseci">
<option value="o"> </option>
<option value="1">Januar</option>
<option value="2">Februar</option>
</select><br><BR>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
$(document).on('change','select[#meseci]',function(){
$post('tabela.php',$('#test_form').serialize()).done(function(results){
$('#results').html(results);
});
});
></script>
<div id="results"</div>

Answer

Consider you have div in your current page with id=result. Now, in your script file you can use onChange() on the select tag to get the data using ajax. JS script:

$(document).on('change','select[name="meseci"]',function(){
    $.post('tabela.php',$('#test_form').serialize()).done(function(result){
        $('#result').html(result);
    });
});

Add id to your form, in above script I have used id=test_form.

<form action="tabela.php" method="post" id="test_form">

Update your form tag:

<form method="post" id="test_form">

Also, remove onChange from your select tag.

<select name="meseci">