-3

how can i work similarly with database instead of using localStorage in the below code. I am aware that javascript is client side language and php is a server side. I want to store retrieve data from database instead of localstorage. Any ajax jQuery json code to help out will be helpful

<div id="timer">timer</div>
<div id="countr">count</div>
<script>
var count=localStorage.getItem("count")? localStorage.getItem("count"):0;
var timeleft = localStorage.getItem("timeleft")? localStorage.getItem("timeleft"):60;
var downloadTimer = setInterval(function(){
timeleft --;
document.getElementById("timer").innerHTML = timeleft;
if(timeleft == 0)
setInterval(timeleft=60) && setInterval(count++);
document.getElementById("countr").innerHTML = count;
localStorage.setItem("timeleft",timeleft);
localStorage.setItem("count",count);
if(count==20)
setInterval(count=0); },100);
</script>

ajax code

<script>
    $(document).ready(function){
        $.ajax({url:"savedata.php",success:function(result){
            $("#timer"),html(result);
        }});
    };
    const data= new fdata();
    data.append("count","count");
    data.append("timeleft","timeleft");
    const xhr= new XMLHttpRequest();
    xhr.open("POST","savedata.php",true);
    xhr.send(data); 
</script>

Php code (savedata.php)

      <?php
      $db = mysqli_connect("localhost","root","","vidswapp");
      $timer=$_POST['timeleft'];
      $counter=$_POST['count'];
      $mysqli="insert into table1(timer,counter)values('$timer','$counter')"; 
      ?>
Patrick Q
  • 6,373
  • 2
  • 25
  • 34
semi colon
  • 21
  • 11
  • Please take some time to do some basic research on your own and make an attempt. If you get stuck on something _specific_, feel free to post a question that includes the code that you tried, the expected result, the actual result, and what debugging you've already done to narrow down the problem. As it stands, this is _far_ to broad. – Patrick Q Jan 27 '20 at 18:49
  • The above code is working fine. It's like i want to perform the same with the help of MySQL database. I tried ajax but i am not even close. Hence opted not to make it vague here. Simply want to put the value of id=timer and id=countr into database @PatrickQ – semi colon Jan 27 '20 at 18:54
  • We can't help you fix what you don't show us. If you include your ajax-based attempt in your question (along with what is currently happening that makes you think it is "not even close"), we might be able to spot your error. There are plenty of guides/tutorials out there for using ajax + PHP + MySQL to get you off to a good start. – Patrick Q Jan 27 '20 at 18:59
  • My problem is with the data that is stored and retrieved in localStorage. i want to do that using database. however i have also included the ajax+mysql+php code. thank you @PatrickQ – semi colon Jan 27 '20 at 19:09
  • if thats what youd like to know, then ask or search for the question "how do i insert data into a php table from javascript" – oldboy Jan 27 '20 at 19:09
  • um ty @oldboy. i did that now looking for a suitable and to the point help ty. – semi colon Jan 27 '20 at 19:13
  • @Tariquekhatri Anything that you put inside `$(document).ready(function){` runs immediately when the page loads. This means that your `.ajax()` call is being run on page load. Is that really what you want? Even if it is, you are using a `url` variable that I don't see defined anywhere. You're also not sending any data with that request. – Patrick Q Jan 27 '20 at 19:13
  • [This](https://stackoverflow.com/questions/5143191/inserting-into-mysql-from-php-jquery-ajax) and [this](https://stackoverflow.com/questions/16707648/using-jquery-ajax-to-retrieve-data-from-mysql) might be good questions for you to look at. – Patrick Q Jan 27 '20 at 19:18
  • @PatrickQ yes i want it to run immediately when the page loads. However the URL is the php code written below. I suppose. I don't have much idea about sending data. I am a new bee learner. Ty – semi colon Jan 27 '20 at 19:19
  • @Tariquekhatri "I don't have much idea about sending data" A basic tutorial on using jQuery and ajax, as has been suggested, would give you an idea. Or if you read through the [documentation](https://api.jquery.com/jquery.ajax/). Doing these would also show you how to set the function to do a POST instead of a GET. – Patrick Q Jan 27 '20 at 19:26
  • @PatrickQ most of the suggestions are to fetch the information from database and not just store the way it is working currently in localstorage. However certain data that are being sent to sever using ajax in ur recommendations are form. Whereas the code I have shown is a live timer. Aslong as localstorage is concerned my code is 100% working fine. I am trying to make is dynamic. Storing in to database may solve it – semi colon Jan 27 '20 at 19:38
  • youre likely going to want to use the following [superglobal variables](https://www.w3schools.com/PHP/php_superglobals.asp), [`$_POST`](https://www.php.net/manual/en/reserved.variables.post.php) or [`$_GET`](https://www.php.net/manual/en/reserved.variables.get.php). you use AJAX to pass data to a `process-data.php` page which then uses those variables to access the data – oldboy Jan 27 '20 at 23:16
  • @oldboy could you please come up with the code syntax?? I think i have used $_POST up there in savedata.php. would love if you could help me with correction to my code – semi colon Jan 28 '20 at 03:36
  • It will still be fine if i could just store the value of count in the database. If not timeleft.@oldboy @patrickQ – semi colon Jan 28 '20 at 03:38
  • ok, i added a working example to your question – oldboy Jan 28 '20 at 06:56
  • Ty so much @oldboy for coming up with the code. It still isn't working for me. Is there any problem in my ajax code?? Do i need to make any changes in my ajax code?? – semi colon Jan 28 '20 at 10:26
  • @oldboy Please do not put answers in questions like that. That's not how things work here. I am going to edit it out of the question. This was closed for a reason. If you think it deserves to be re-opened, cast a re-open vote. – Patrick Q Jan 28 '20 at 13:02
  • Open to receive any systematic syntax code to get it done. Seeking positive response help. Thanks @PatrickQ – semi colon Jan 28 '20 at 18:19
  • I have been trying hard to get it done. Looking for a proper result oriented explaination and code correction. Ty all – semi colon Jan 28 '20 at 18:21

1 Answers1

-1

This is how it works at the most basic level. The rest is up to you to figure out.

<?php
  if ($_SERVER["REQUEST_METHOD"] === "POST"){

    // 1. Connect to database.
    $dbhost = "localhost";
    $dbuser = "yourUsername";
    $dbpass = "yourPassword";
    $dbname = "yourDatabase";
    try {
      $connection = new PDO("mysql:host=$dbhost; dbname=$dbname; charset=utf8", $dbuser, $dbpass);
      $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      echo "Connected to database successfully!"; 

      // 2. Prepare your statement with placeholders.
      $pdo = $connection->prepare("INSERT INTO theTableName (theColumnName1, theColumnName2) "
        + "VALUES (:placeholderForColumn1value, :placeholderForColumn2value)");

      // 3. Execute your statement with actual values.
      $pdo->execute([
        ":placeholderForColumn1value" => $_POST["actualValue1"],
        ":placeholderForColumn2value" => $_POST["actualValue2"]
      ]);

      // 4. Close your connection to the database.
      $connection = null;

    } catch(PDOException $e) {
      echo "Failed to connect to database: " . $e->getMessage() . ".";
    }
  }
?>
oldboy
  • 5,729
  • 6
  • 38
  • 86