How to use a div id as a php var - php

I have the following function that pass to the div with id = "window", the value dbdata from the database.
$(document).ready(function() {
setInterval(function () {
$('#window').load('crt.php');
)};
)};
How can I get the id value and use it in the php code below?
without refresh the page?
if ($id = $row["dbdata"]) { do something }
I added the rest of the code:
index.html
`<div id = "window"></div>`
`if ($id = $row["dbdata"]) {do something}`
`<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#window').load('crt.php')
}, 3000);
});
</script>`
crt.php
`<?php
$conn = new mysqli('localhost', 'root', '', 'user');
if ($conn->connect_error) {
die("Connection error: " . $conn->connect_error);
}
$result = $conn->query("SELECT id FROM data");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row['dbdata'] . '<br>';
}
}
?>`
Thank you in advance.

You can pass values in URL parameters.:
$('#window').load('crt.php?id=window')
Then in your php code you can retrieve the parameter using:
$id = $_GET["id"];

a simple way could be assign the GET param in your jquery load url and use it in your php code
$(document).ready(function() {
setInterval(function () {
$('#window').load('crt.php?id=window')
.
if ($_GET['id'] = $row["dbdata"]) { do something }
or you instead of load could use ajax get eg :
$.get( "crt.php?id=window", function( data ) {
alert( "Data Loaded: " + data );
});
in your crt.php
if ($_GET['id'] = $row["dbdata"]) {
return "hello!";
}

Related

Ajax + mysql reload page

i try to work on something but it's not realy working as i want, so first we have the index page with the ajax code :
function redirect(){
$(".redirect").load("redirect.php");
}
setInterval(function(){
redirect()
}, 3000);
</pre>
Of course in the body we have this :
<div class="redirect"></div>
In the redirect.php code, we have this :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['clientvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
//header('location: '.$_SESSION['redirect_url']);
}
}
}
Okay so, to start, when my client is on the index.php, the row redirect is on 0.
And on my web panel, i can set up the value to 1, if the value is on 1, i want the client to be redirected of the index page to my $_SESSION['redirect_url'].
But the problem is, of course, it redirect only in the class="redirect" div.
But i want him to be redirected from the index page, so i tried in the redirect.php code this :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['clientvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
$ok = 1;
}
}
}
And on the index.php page i added this below the class redirect div :
<?php
if($ok == 1) {
header('location: url');
}
?>
But it doesn't detect the $ok from the redirect.php.
Any idea how i could fix this problem ?
Thank !
Okay i resolved the problem, i don't know if it's the proper way to do it, but it's working as i want ! i did that :
redirect.php :
<?php
session_start();
include('db.php');
$query = "SELECT * FROM db WHERE client=".$_SESSION['ccvict']."";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
$redirect = $row["redirect"];
if($redirect == 1) {
echo '<div id="content"><div id="activity">1</div></div>';
}
else {
echo '<div id="content"><div id="activity">0</div></div>';
}
}
}
And the AJAX in index.php :
<script>
$(document).ready(function() {
function redirect(){
$.ajax({
url:'redirect.php',
type:'GET',
success: function(data){
var active = $(data).find('#activity').html();
if(active == 1) {
<?php echo 'window.location.replace("'.$_SESSION['redirect_payment'].'");'; ?>
}
}
});
}
setInterval(function(){
redirect()
}, 3000);
});
</script>
Hope it will help, thank #CBroe

How to get a single mysql value and output it to an ajax call?

I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.

How can i pass the jquery value to php function

Here i want to call the php function with some parameter that will be held in some jquery function.
I have php function that takes one parameter and executes the sql query.
and also i have a jquery function where i am getting different values when select item from dropdown box.
now i want to pass the value of dropdown box to php function, how can i do this?
here is what i have done
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
// here i want to pass this variable value to php function
});
php
function productManagement($procat){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT product_name,product_category,product_image_url FROM product_list where product_category='$procat'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["product_name"]."</td><td><a href=''><span class='glyphicon glyphicon-remove'></span>Remove</a></td><td><a href='edit-product.php'><span class='glyphicon glyphicon-edit'></span>Edit</a></td></tr>";
}
} else {
echo "No results found";
}
$conn->close();
}
How can i do this?
Another way is to use Ajax like :
Jquery code:
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
// here i want to pass this variable value to php function
-----------------------------------------------------
$.ajax({
url: 'newFunctionFile.php',
type: 'POST',
data: 'category='+category,
success: function(data) {
//you can add the code to show success message
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
});
and you have to create a file for php function let say file name is newFunctionFile.php as i have mention in ajax call:
if(isset($_POST['category'])) {
productManagement($_POST['category']);
}
function productManagement($procat){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT product_name,product_category,product_image_url FROM product_list where product_category='$procat'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["product_name"]."</td><td><a href=''><span class='glyphicon glyphicon-remove'></span>Remove</a></td><td><a href='edit-product.php'><span class='glyphicon glyphicon-edit'></span>Edit</a></td></tr>";
}
} else {
echo "No results found";
}
$conn->close();
}
How about something along these lines.
In your javascript:
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
location.href = location.href + "?val="+category; //reload the page with a parameter
});
And then in your PHP, add this code as your function call
if(isset($_GET['val'])) { //if 'val' parameter is set (i.e. is in the url)
productManagement($_GET['val']); //call function, with that parameter
}

Reload a div only if there is new data

If I create a script like this, then it will reload the div every 2.5 seconds. I want a script that only displays if there is new data, if there is no new data it does not have to reload...
<script type="text/javascript">
function dispMsg() {
$("#displayMessage").load('load.php');
var newscrollHeight = $("#displayMessage").attr("scrollHeight") - 20;
$("#displayMessage").animate({ scrollTop: newscrollHeight }, 'normal');
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage"></div>
and here is the load.php:
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$query = mysql_query($sql);
while ($result = mysql_fetch_array($query)) {
$id = $result['id'];
$from = $result['user_01'];
$to = $result['to_usr'];
$message = $result['message_01'];
$date = $result['date_send'];
echo "<span class='from'> $from </span>"
. "<span class='message'> $message </span> <br/>";
}
use the parameters and call back of $.load()
$.load(url, {param1:value, param2:value}, function(result){
if(result >5){
//do something
}
)
Example:
<?php
if($_REQUEST['action'] == 'check'){
if($_REQUEST['lastId'] < 5 ){
echo $_REQUEST['lastId']+1;
die;
}
}
if($_REQUEST['action'] == 'load'){
echo 'some conntent!';
die;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var lastId = 0;
function dispMsg() {
$.get('tmp.php', {action:'check', lastId: lastId}, function(responce){
if(responce !== 0){
alert(responce);
$('#displayMessage').load('tmp.php', {action:'load'});
}
});
}
setInterval (dispMsg, 2500);
});
</script>
<div id="displayMessage">1</div>
You can send the last message id with each request. If the last message of your query is greater than the id sent, send the response. Otherwise send nothing.
function load_messages(){
var last = $('#messagewindow p:last').attr('id');
$.ajax({
url: base_url + "load.php",
type: "POST",
data: {
last: last
},
cache: false,
success: function(html){
//insert message
}
});
}
You can send the id as the id attribute in your HTML. Each message in the chat window is sent as a paragraph with some message id such as id="133".
Expanding on #Pé de Leão's solution, here's something more simple:
<?php
$sql = "SELECT * FROM message ORDER BY id DESC LIMIT 1";
$mysqli = new mysqli("host", "user", "pass");
if ($result = $mysqli->query($sql)) {
$msg = $result->fetch_assoc();
if (isset($_REQUEST['last']) && $msg['id'] != $_REQUEST['last']) {
echo "<span id='${msg['id']}' class='from'>${msg['user_01']}</span>";
}
}
And on the client side:
function dispMsg() {
var last = $('#displayMessages span.from').attr('id');
$.get(baseUrl + '/load.php', { last: last }, function(result) {
if (result) {
$('#displayMessages').html(result);
}
});
}
Note that this replaces everything in displayMessages.

jQuery code causing conflict in results

I would like to ask, is there a better way to run this code. I have a form with a select of #BA_customer which when selected populates a second menu with the address of the selected client. I also need to display a dept dropdown based on the customer selecetion. I think the code I have is causing a conflict where the customer is being passed twice in 2 seperate statements. What is the correct way to do this? Many thanks
<script language="javascript" type="text/javascript">
$(function() {
$("#BA_customer").live('change', function() { if ($(this).val()!="")
$.get("../../getOptions.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_address").html(data); });
});
});
</script>
<script language="javascript" type="text/javascript">
$(function() {
$("#BA_customer").live('change', function() { if ($(this).val()!="")
$.get("../../getDept.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_dept").html(data); });
});
});
</script>
+++++++ dept.php Code +++++++++++++++++++++
$customer = mysql_real_escape_string( $_GET["BA_customer"] ); // not used here, it's the customer choosen
$con = mysql_connect("localhost","root","");
$db = "sample";
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($db, $con);
$query_rs_select_dept = sprintf("SELECT * FROM departments where code = '$customer'");
$rs_select_dept = mysql_query($query_rs_select_dept, $con) or die(mysql_error());
$row_rs_select_dept = mysql_fetch_assoc($rs_select_dept);
$totalRows_rs_select_dept = mysql_num_rows($rs_select_dept);
echo '<label for="dept">Select a Department</label>'.'<select name="customerdept">';
echo '<option value="">Select a Department</option>';
while ($row_rs_select_dept = mysql_fetch_assoc($rs_select_dept))
{
$dept=$row_rs_select_dept['name'];
echo '<option value="dept">'.$dept.'</option>';
}
echo '</select>';
++++ SOLUTION +++++++++++++
mysql_select_db($db, $con);
$query_rs_dept = sprintf("SELECT * FROM departments where code = '$customer'");
$rs_dept = mysql_query($query_rs_dept, $con) or die(mysql_error());
$totalRows_rs_dept = mysql_num_rows($rs_dept);
echo '<label for="dept">Select a Department</label>'.'<select name="customerdept">';
echo '<option value="">Select a Department</option>';
while ($row_rs_dept = mysql_fetch_assoc($rs_dept))
{
$dept=$row_rs_dept['name'];
echo '<option value="dept">'.$dept.'</option>';
}
echo '</select>';
Remove the first $row_rs_select_dept = mysql_fetch_assoc($rs_select_dept); from the script and it works. Just posted solution in case some other soul needs help with problem like this.
Maybe you could send the two requests together?
$(function() {
$("#BA_customer").live('change', function() {
if($(this).val()!="")
$.get("../../getOptions.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_address").html(data);
});
$.get("../../getDept.php?BA_customer=" + $(this).val(), function(data) {
$("#BA_dept").html(data);
});
});
});

Categories