I currently have this function exactly how I want it except for the jQuery at the bottom in which I am only alerting and not creating a real variable. It all works but I am stuck on how I can take all of the data from the jQuery script and then make it into a variable so that I can bring it to another page? Any ideas, NEED HELP!
function getGrade($id, $grades_array) {
$counter = 0;
$sql = "Select grade FROM grades";
$result = mysql_query($sql) or die (mysql_error());
echo '<select name="grades_selected" multiple="multiple" id="grades_selected">';
while ($row = mysql_fetch_array($result)) {
if ($row['grade'] != $grades_array[$counter]) {
echo "<option>" . $row['grade'] . "</option>";
} else {
echo "<option selected=" . $row['grade'] . ">" . $row['grade'] . "</option>";
$counter = $counter + 1;
}
}
mysql_free_result($result);
echo '</select>';
$_SESSION['test'] = $grades_array;
?>
<script>
$(document).ready(function() {
$('#grades_selected').change(function() {
alert($(this).val());
});
});
</script>
<?
}
You need to use ajax within on change function:
$(document).ready(function() {
$('#grades_selected').change(function() {
var variable = $(this).val();
$.ajax({
type: 'post',
url: 'target_page.php',
data: {variable : variable},
success: function (res) {
alert(res);
}
});
});
});
On target_page.php:
echo $_POST['variable'];
Related
Passing a table cell value from javascript variable into php variable.
<script>
$(document).on('ready',function(){
$('#business_list_table').on('click','.view_btn',function (){
$.ajax({
url: "test.php",
method: "POST",
data:{business_id : "6510-1"},
success: function (data){
$('#business_permit_table').html(data);
}
});
});
});
<?php
$business_id = $_GET["business_id"];
echo $business_id;
You cannot use JS variable directly to PHP like that. use ajax instead:
JS
$("#business_list_table").on('click', '.view_btn', function post() {
// get the current row
var currentRow = $(this).closest("tr");
var Business_id_value= currentRow.find("td:eq(1)").text(); // get current row 2nd T;
$.post('', {Business_ID: Business_id_value}, function(result){
$('table tbody').html(result);
});
});
PHP
if (isset($_POST['Business_ID'])) {
$Business_ID = $_POST['Business_ID'];
$conn = mysqli_connect("localhost", "root", "", "bpsystem");
if ($conn->connect_error) {
die("Database connection failed:" . $conn->connect_error);
} else {
$sql = "SELECT * FROM business_tb WHERE Business_ID='$Business_ID';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
echo "<tr >";
echo "<td>BUSINESS NAME</td>";
echo "<td>" . $row['Business_Name'] . "</td>";
echo "</tr>";
echo "<tr >";
echo "</tr>";
}
}
}
}
You can use the query string to pass the variable to PHP. Like this,
$("#business_list_table").on('click', '.view_btn', function post() {
// get the current row
var currentRow = $(this).closest("tr");
var Business_id_value= currentRow.find("td:eq(1)").text(); // get current row 2nd T;
window.location.href = 'http://your_url?b_id=' + Business_id_value;
});
Now you can access the Business_id_value varible in your PHP script using $_GET['Business_id_value']
I'm working on a project for work, and I've run into some issues.
I'm creating dynamic elements based on PDO queries and ajax, and I've searched and searched to resolve my specific issue. Basically, I have two select boxes that are dynamically added from a database response, and regardless of which option is selected, all of the dynamically created buttons are made exactly the same. Selected Rack_G
I've also created timers for each Rack/Tray, and the same issue arises for the timers. There is only a record for Rack H Tray 8.Rack H Tray 8
My db_connect.php
$first = "odbc:TIMERODBC";
$user = "exampleuser";
$pass = "examplepass";
$pdo = new PDO($first,$user,$pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Below is my class.db.php file that queries my database
public function selectOven()
{
try{
$stmt = $this->conn->query("SELECT sub.equipName FROM STR_EquipSubCategory sub LEFT JOIN STR_EquipCategory category ON category.categoryID = sub.categoryID GROUP BY sub.equipName");
$data = $stmt->fetchAll();
foreach($data as $row)
{
echo "<option value=" . $row['equipName'] . "><strong>" . $row["equipName"] . "</strong></option>";
}
}
catch(PDOException $e) {
return $e->getMessage();
}
}
public function selectRack($oven) {
try{
$sth = $this->conn->prepare('SELECT storageBayName FROM STR_EquipSubCategory WHERE equipName =:oven');
$sth->bindParam(':oven',$oven,PDO::PARAM_STR);
$sth->execute();
$data = $sth->fetchAll();
echo "<select id='rack' class='custom-select mb-2'>Rack";
echo "<option value ='Select Rack'></option>";
foreach($data as $row)
{
echo "<option id=".$row['storageBayName']." value=". $row["storageBayName"] . ">". $row["storageBayName"] . "</option>";
}
echo "<select>";
}
catch(PDOException $e) {
return $e->getMessage();
}
}
public function selectRackTray($oven,$rack) {
try{
$sth = $this->conn->prepare("EXECUTE STR_GetTimerOpenTraysSp ?, ?");
$sth->bindParam(1,$oven,PDO::PARAM_STR);
$sth->bindParam(2,$rack,PDO::PARAM_STR);
$sth->execute();
$data = $sth->fetchAll();
foreach($data as $row)
{
if(($row['material'] != 0) ) {
echo "<div class='row'>";
echo "<button type='button' id='tray".$row['storageBayName']." ". $row['sublevelID'] ."' class='btn btn-danger' data-toggle='popover'>Tray " .$row['sublevelID'] . "</button>";
echo "</div>";
}
else {
echo "<div class='row'>";
echo "<button type='button' id='emptyTray".$row['storageBayName']. " ".$row['sublevelID'] ."' class='btn btn-success'>Tray " .$row['sublevelID'] . "</button>";
echo "</div>";
}
}
}
catch(PDOException $e) {
return $e->getMessage();
}
}
And now my ajax jQuery & Ajax
$(document).ready(function(){
$("select#oven").change(function(){
var selectedOven = $("#oven option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { oven : selectedOven }
}).done(function(data){
$("#rackResponse").html(data);
});
});
});
$(document).on('change', "select#rack", function() {
var selectedRack = ($(this).val());
var selectedOven = ($("#oven option:selected").text());
$.ajax({
type: "POST",
url: "process-a-request.php",
data:
{
rack: selectedRack,
oven: selectedOven
},
}).done(function(data){
$("#tResponse").html(data);
});
});
If anyone can help me out, I would greatly appreciate it. Note, I'm not super experienced with PHP, but everything else seems to be working correctly.
My problem wasn't with ajax, php, or the PDO statements. I ran some tests on my stored procedure that I was calling, and found the problem there. Thanks for attempting to help me out.
I have a problem in showing the alert box. This code for the rating star.
rating.js
$(document).ready(function(){
$('.post li').mouseout(function(){
$(this).siblings().andSelf().removeClass('selected highlight')
}).mouseover(function(){
$(this).siblings().andSelf().removeClass('selected');
$(this).prevAll().andSelf().addClass('highlight');
})
$('.post li').click(function(){
$(this).prevAll().andSelf().addClass('selected');
var parent = $(this).parent();
var oldrate = $('li.selected:last', parent).index();
parent.data('rating',(oldrate+1))
data = new Object();
data.id = parent.data('id');
data.rating = parent.data('rating')
$.ajax({
url: "add_rating.php",// path of the file
data: data,
type: "POST",
success: function(data) {
}
});
})
/* reset rating */
jQuery('.post ul').mouseout(function(){
var rating = $(this).data('rating');
if( rating > 0) {
$('li:lt('+rating+')',this).addClass('selected');
}
})
})
add_rating.php
<?php
include("dbconnection.php");
session_start();
$myid = $_SESSION['id'];
// echo "".$myid;
$sql_notification ="SELECT * FROM table_user_skills where user_id='$myid' and rating=5";
$result = $conn->query($sql_notification);
$count = 0;
while ($row=$result->fetch_assoc()) {
if ($row['rating']==5) {
$count = $count +1;
}
}
// echo "Count: ".$count;
if(!empty($_POST["rating"]) && !empty($_POST["id"])) {
$myrate=$_POST["rating"];
if($count<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Less than 5");';
print '</script>';
} else if($myrate<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Rate Less than 5");';
print '</script>';
}else if($count>5){
print '<script type="text/javascript">';
print 'alert("Lpas 5 stars");';
print '</script>';
}
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE skills_id='" . $_POST["skills_id"] . "'";
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE user_id='" . $_POST["userid"] . "' and skills_id='" . $_POST["id"] . "' and category_id='" . $_POST["category"] . "'";
}
?>
My problem is that the alert box is not showing. I have to limit the number of 5 stars being updated. If anyone could help me figure out what's wrong with my code, I would appreciate it.
Look at the success callback function for your AJAX call - it's empty. You're having PHP print out the alert box code in the ajax call and then never doing anything with that output.
To make the alert show up, you would have to append the code your AJAX call returns to the DOM. However, it would probably be better to just return just the message and let the JavaScript code take care of raising the alert box. Just a simple alert(data) should do the trick.
So, what im doing is searching for records stored in a database using AJAX, but when it prints the callback data, the first record is duplicated:
My code:
$gUser = $_GET['q'];
$connect = mysql_connect("localhost", "root", "") or die("Could not connect to the server");
mysql_select_db("socialj") or die("Could not connect to the database");
$result = mysql_query("SELECT fullname, email FROM users WHERE fullname LIKE '%$gUser%' ");
while($array[] = mysql_fetch_array ($result))
{
foreach($array as $r)
{
echo $r['fullname'].' | '.$r['email'].'<br>';
}
}
?>
JavaScript Code:
$(document).ready(function (){
$('#searchh').on('submit', function (e){
e.preventDefault();
var sVal = $('#search').val();
$.ajax({
type: 'get',
url: 'profile.php',
data: {q : sVal},
success: function (data) {
alert(data);
}
});
});
});
Could you guys help me? I don't know whats happening... Thanks.
Replace this
while($array[] = mysql_fetch_array($result)) {
foreach($array as $r) {
echo $r['fullname'] . ' | ' . $r['email'] . '<br>';
}
}
with this
while($row = mysql_fetch_array($result)) {
echo $row['fullname'] . ' | ' . $row['email'] . '<br>';
}
I dont know how to use ajax in my problem:
I have a function in php (assign) that update a temporary table in database, I want to when user user click on a button (feedback function that is defined in javascript) this function (assign) run, what should I do?
<script>
function feedback(){
var boxes = document.getElementsByClassName('box');
for(var j = 0; j < boxes.length; j++){
if(boxes[j].checked) {
assign(1);
}
else{
assign(0);
}
}
}
</script>
<?php
$con = mysql_connect("localhost", "root", "")
or die(mysql_error());
if (!$con) {
die('Could not connect to MySQL: ' . mysql_error());
}
mysql_select_db("project", $con)
or die(mysql_error());
$result = mysql_query("select * from words");
echo "<table border='1'>
<tr>
<th>word</th>
<th>meaning</th>
<th>checking</th>
</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['word'] . "</td>";
$idd= $row['id'] ;
echo "<td>". "<div class='hiding' style='display:none'>".$row['meaning']."</div>"."</td>";
echo "<td>";
echo "<input class=\"box\" name=\"$idd\" type=\"checkbox\" value=\"\"> ";
echo "</td>";
echo "</tr>";
}
echo "</table>";
function assign($checkparm){
//mysql_query("update words set checking=$checkparm ");
mysql_query("create TEMPORARY TABLE words1user1 as (SELECT * FROM words) ");
mysql_query("update words1user1 set checking=$checkparm ");
}
mysql_close($con);
?>
<button onclick="ShowMeanings()">ShowMeanings</button>
<button onclick="feedback()">sendfeedback</button>
There is only one way to call a php function after the page is loaded:
1.ajax:
function callPHP() {
$.ajax ({
url: "yourPageName.php",
data: { action : assign }, //optional
success: function( result ) {
//do something after you receive the result
}
}
in your PHP, write
if ($_POST["action"] == "assign")
{
assign(your parameters); //You need to put the parameters you want to pass in
//the data field of the ajax call, and use $_POST[]
//to get them
}
There are many great guides on the internet. I will however suggest you get too know JQuery. It will help you on your learning curve.
function ajaxCall(){
$.ajax({
type: "GET",
url: "scripts/on/serverside.php"
});
};