0

I want to manipulate the value that it is stored in this variable $result[]. Specifically i want to return that value from php file to my html file. What should i do? Can you give me some reference code when i want to return things from server side to client side for further manipulation?

My php file:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];

//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
  $result[]=$row['site_id'];
}

// Close connection
mysqli_close($link);
?>

My html file:

    <html>

    <head>
      <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
      <script>
        function load3() {
          var flag1 = true;
          do{
            var selection = window.prompt("Give the User Id:", "Type a number!");
                if ( /^[0-9]+$/.test(selection)) {
                flag1=false;
                }
            }while(flag1!=false);
        $("#user_id").val(selection)
          //$("#user_id").val(prompt("Give the User Id:"))

          var flag2 = true;
          do{
            var selection2 = window.prompt("Give the Book Id:", "Type a number!");
            if ( /^[0-9]+$/.test(selection2)) {
                flag2=false;
                }
            }while(flag2!=false);
        $("#book_id").val(selection2)
          //$("#book_id").val(prompt("Give the Book Id:"))

          var flag3= true;
          do{
            var selection3 = window.prompt("Give the Game Id:", "Type a number!");
            if ( /^[0-9]+$/.test(selection3)) {
                flag3=false;
                }
            }while(flag3!=false);
        $("#game_id").val(selection3)
          //$("#game_id").val(prompt("Give the Game Id:"))
       }    
var fieldNameElement = document.getElementById('outPut');
 if (fieldNameElement == 4)
 {
 window.alert("bingo!");
 }
      </script>

    </head>

    <body>
                      <form name="LoadGame" id="LoadGame" method="post" action="http://127.0.0.1/PHP/mine1.php" enctype="multipart/form-data">
                        <input type="submit" value="Load" id="load" onclick="load3()" class="button12" />
                        <input type="hidden" name="user_id" id="user_id">
                        <input type="hidden" name="book_id" id="book_id">
                        <input type="hidden" name="game_id" id="game_id">
                        <input type="hidden" name="site_id" id="site_id">
                      </form>     
    </body>
    </html>
JohnnyCage
  • 29
  • 1
  • 7

2 Answers2

0

First of all: remove the script tag from your php. Secondly: Why are you executing the sql statement two times?

To your question: You have to send a request to your PHP script via AJAX: (Place this inside <script> tags and make sure to include jquery correctly)

$(() => {

  $('form').on('submit', () => {

    event.preventDefault()

    $.ajax({
      type: 'POST',
      url: '<your-php-file>', // Modify to your requirements
      dataType: 'json', 
      data: $('form').serialize() // Modify to your requirements
    }).done(function(response){

      console.log(response)

    }).fail(function(){

      console.log('ERROR')

    })

  })

})

Your PHP-Script which needs to return JSON:

$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";

// Execute Query
$res = mysqli_query($link,$query) or die(mysqli_error($link));

// Get Rows
while($row = mysqli_fetch_assoc($res)){
  $result[] = $row['site_id'];
}    

// Return JSON to AJAX
echo json_encode($result);

Take a look at your developer console.

Haven't tested it.

T K
  • 578
  • 6
  • 19
  • @T K thank you for your important advices. now i will try to insert these lines and i will tell you if i will have any problems.. – JohnnyCage Oct 05 '18 at 09:14
0

Note that this answer is making use of jQuery notation, so you will need to include a jQuery library in your application in order to make this example work:

<script src="/js/jquery.min.js" type="text/javascript"></script>

Since you have your HTML and PHP in separate files, you can use AJAX to output your HTML in an element you so desire on your HTML page.

Example of jQuery AJAX:

<script>
function submitMyForm() {
    $.ajax({
        type: 'POST',
        url: '/your_page.php',
        data: $('#yourFormId').serialize(),
        success: function (html) {
            //do something on success?
            $('#outPut').html(html);

            var bingoValue=4;
            if( $('#outPut').text().indexOf(''+bingoValue) > 0){
                alert('bingo!');
            }
            else {
                alert('No!');
            }
        }
    });
}
</script>

Note that I encapsulated the AJAX function in another function that you can choose to call onclick on a button for example.

<button id="mySubmitButton" onclick="submitMyForm();">Submit form!</button>


Step-by-step:

What we do in our AJAX function, is that we declare our data type, just like you would do with a form element. In your PHP file I noticed that you used the POST method, so that's what I incorporated in the AJAX function as well.

Next we declare our URL, which is where the data will be sent. This is the same page that your current form is sending the data to, which is your PHP page.

We then the declare our data. Now, there are different ways of doing this. I assume you are using a form currently to POST your data to your PHP page, so I thought we might as well make use of that form now that you have it anyways. What we do is that we basically serialize the data inside your form as our POST values, just like you do on a normal form submit. Another way of doing it, would be to declare individual variables as your POST variables.

Example of individual variables:

$.ajax({
    type: 'POST',
    url: '/your_page.php',
    data: {
        myVariable : data,
        anotherVariable : moreData
        //etc.
    },
    success: function (html) {
        //do something on success?
        $('#outPut').html(html);
    }
});

A literal example of a variable to parse: myVariable : $('input#bookId').val().

The operator : in our AJAX function is basically an = in this case, so we set our variable to be equal to whatever we want. In the literal example myVariable will contain the value of an input field with the id bookId. You can do targeting by any selector you want, and you can look that up. I just used this as an example.

In the success function of the AJAX function, you can basically do something upon success. This is where you could insert the HTML that you wish to output from your PHP page into another element (a div for example). In my AJAX example, I am outputting the html from the PHP page into an element that contains the id outPut.

We also write a condition in our success function (based off comments to this answer), where we check for a specific substring value in the div element. This substring value is defined through the variable bingoValue. In my example I set that to be equal to 4, so whenever "4" exists inside the div element, it enters the condition.

Example:

<div id="outPut"></div>

If you make use of this example, then whatever HTML you structure in your PHP file, making use of the PHP values in your PHP file, will be inserted into the div element.

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("127.0.0.1", "root", "", "mysql3");
// Check connection
if($link === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}

$user_id =$_POST['user_id'];
$book_id =$_POST['book_id'];
$game_id =$_POST['game_id'];
$site_id =$_POST['site_id'];

//Attempt insert query execution
$query = "SELECT site_id FROM components WHERE user_id='$user_id' && book_id='$book_id' && game_id='$game_id' ORDER BY site_id DESC LIMIT 1";
$res = mysqli_query($link,$query);
$result = array();
$res = mysqli_query($link,$query) or die(mysqli_error($link));
while($row = mysqli_fetch_assoc($res)){
  $result=$row['site_id'];

  echo $result.' ';
}

// Close connection
mysqli_close($link);
?>

Your form also no longer needs an action defined as all of that is now taken care of by the AJAX function.

So change:

<form name="LoadGame" id="LoadGame" method="post" action="http://127.0.0.1/PHP/mine1.php" enctype="multipart/form-data">

to:

<form name="LoadGame" id="LoadGame" method="post" enctype="multipart/form-data">

And make sure that your button: <button id="mySubmitButton" onclick="submitMyForm();">Submit form!</button> is outside of your form tag, as buttons without a defined type attribute will have type="submit" by default inside a form tag.

If you need anything elaborated, let me know. :)

Martin
  • 1,849
  • 1
  • 11
  • 17