John
John

Reputation: 13

How to use a div id as a php var

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.

Upvotes: 1

Views: 100

Answers (2)

ScaisEdge
ScaisEdge

Reputation: 133360

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!";
}  

Upvotes: 0

Ricky Mo
Ricky Mo

Reputation: 7618

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"];

Upvotes: 4

Related Questions