1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Run a query through javascript with php

Discussion in 'JavaScript' started by jasperschellekens, Jan 7, 2019.

  1. #1
    How can i do this?
    This does not work:
    
      function HeadingNorth() {
          <?php
            $query = "UPDATE playerships SET HEADING = 'N' WHERE ID='$getshipid'";
            mysqli_query($conn, $query);
          ?>
      }
    
    Code (markup):
    I wanted it to make it like this so the page doesnt need a reload but instead would change it on a button click.
    The function does not run the code that it should. why?
    Is there another way to do this?
    SEMrush
     
    jasperschellekens, Jan 7, 2019 IP
    SEMrush
  2. hdewantara

    hdewantara Active Member

    Messages:
    437
    Likes Received:
    37
    Best Answers:
    19
    Trophy Points:
    80
    #2
    With that current scheme, $query is executed and will always be... by your PHP server to answer a webpage request (at page loading), while HeadingNorth() is... by your browser's javascript engine when a click happens. Two different timings, two different executors. Right?

    If your actual intention is a click to execute HeadingNorth() to execute $query in sequence, then try AJAX: https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
     
    hdewantara, Jan 7, 2019 IP
  3. sarahk

    sarahk iTamer Staff

    Messages:
    25,183
    Likes Received:
    3,428
    Best Answers:
    100
    Trophy Points:
    665
    #3
    I'm with @hdewantara - you don't appear to grasp the difference between php and javascript.

    If you use ajax - most commonly via the jQuery library - the javascript can call a php script to run the query and then return the result, usually as json, to the javascript that can then do something with the result.

    Your code, however, is running the query when the page is generated and creates an empty HeadingNorth function.

    It's not uncommon to use php to set constant values in javascript, and that may be what has confused you. I have code like this when I'm generating graphs
    <script>
    var data = <?php echo getGraphData(); ?>;
    </script>
    HTML:
    but that's not what you are trying to do.

    If you did a view source or "inspected" the page you'd have seen your empty function.

    Get used to using console.log() and debugging your work.
     
    sarahk, Jan 7, 2019 IP
  4. jasperschellekens

    jasperschellekens Greenhorn

    Messages:
    25
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    5
    #4
    Thank you for your replies. So i searched on how someone would update something using ajax.
    I have the following code but it doesn't work?
    
    <a href="javascript:void(0)" onclick="Add(N)">
          <div class="compass-north"><font size="6">N</font></div>
        </a> 
        <a href="javascript:void(0)" onclick="Add(S)">
          <div class="compass-east"><font size="6">E</font></div>
        </a>  
        <a href="javascript:void(0)" onclick="Add(E)">
          <div class="compass-south"><font size="6">S</font></div>
        </a> 
        <a href="javascript:void(0)" onclick="Add(W)">
          <div class="compass-west"><font size="6">W</font></div>
        </a> 
    
    <script src="jquery.js"></script>
      <script>
        function Add(ch)
        {
            jQuery.ajax({
    
             type: "POST",
    
             url: "changeheading.php",
    
             data: 'ch='+ch,
    
             cache: false,
    
             success: function(response)
             {
    
               alert("Heading Changed");
             }
           });
       }
      </script>  
    
    //changeheading.php
    $var = $_GET['ch'] ;
    $query = "UPDATE playerships SET HEADING = '$var' WHERE ID='$shipid'";
    mysqli_query($conn, $query);
    
    Code (markup):
    Can anyone of you spot the error i made?
     
    jasperschellekens, Jan 7, 2019 IP
  5. jasperschellekens

    jasperschellekens Greenhorn

    Messages:
    25
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    5
    #5
    So i have searched on how to update something in a database with ajax.
    I have the following code but it doesnt work.
    
    https://pastebin.com/Edu6a6LE
    Had to paste it there because forum detected it as spam somehow.
    
    
    Code (markup):
    What am i doing wrong?
     
    jasperschellekens, Jan 7, 2019 IP
  6. sarahk

    sarahk iTamer Staff

    Messages:
    25,183
    Likes Received:
    3,428
    Best Answers:
    100
    Trophy Points:
    665
    #6
    What are you seeing in the console?
    Is the function being called when you click?
    Typically with jquery you would use an event listener through javascript rather than an onclick attribute in the html
    If you run changeheading.php independently it works, right?
    edit: except that it won't, for starters in jquery you send the data as Post, but in php you look for a Get variable and you don't add the shipid to the data that is passed.

    jsfiddle is probably more useful than pastebin
     
    sarahk, Jan 7, 2019 IP
  7. jasperschellekens

    jasperschellekens Greenhorn

    Messages:
    25
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    5
    #7
    How can i turn on a log to see if the function is getting called?
    Could u show me an example of how you would use such an event listener instead of an onclick?
    I have changed GET to POST and im getting some results, but not exactly how it should..
    So when i load the page, imagine my ship is heading west. It now automatically changed the ships heading to north... really weird.
    Also while it changed the heading automatically, i can not alter it by clicking on the links.
    If it would be easier i can send login details and a link so u can see it?
     
    jasperschellekens, Jan 7, 2019 IP
  8. sarahk

    sarahk iTamer Staff

    Messages:
    25,183
    Likes Received:
    3,428
    Best Answers:
    100
    Trophy Points:
    665
    #8
    log: if you are using Chrome you can open "Developer Tools", click onto the console, anytime you do a console.log() of something that's where it'll turn up. If you go to elements you can test out changes to your html and css

    Have a look at this fiddle: http://jsfiddle.net/0t1g2ncz/
    I've simplified the html to make it easier to work with
    I've added some css to make the buttons look like buttons
    and here's the javascript:
    
    <script>
    var buttons = $(".compass");
    var direction = $('#direction');
    
    // handle click and add class
    buttons.on("click", function(){
      var cmd = $(this).html();
      direction.html(cmd);
    });
    </script>
    
    HTML:
    I'm using what is known as an anonymous function to handle the clicks and it's reading the value of the buttons and would then send it down as data to the php script to save to the database.
     
    sarahk, Jan 7, 2019 IP
  9. jasperschellekens

    jasperschellekens Greenhorn

    Messages:
    25
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    5
    #9
    Thanks for the example.
    Edit: Totally misunderstood u.
    I have added ajax, it changes the value on my screen when i click but it doesn't run the file changeheading.php

    
    <script src='https://code.jquery.com/jquery-1.10.2.min.js'></script>
    <script>
      // find elements
      var buttons = $(".compass");
      var direction = $('#direction');
    
      // handle click and add class
      buttons.on("click", function(){
        var cmd = $(this).html();
        direction.html(cmd);
        $(document).ready(function(){
        $.ajax({url:"changeheading.php",data: {"direction":direction}}).done(function(data){console.log(data)});
        });
      })
      </script>
    
    //changeheading.php
    <?php
        session_start();
          ob_start();
        require_once '../connect.php';
        $shipid = $_SESSION["SELECTEDSHIP"];
        $var = filter_input(INPUT_GET, 'direction', FILTER_VALIDATE_INT);
        $query = "UPDATE playerships SET HEADING = '$var' WHERE ID='$shipid'";
        mysqli_query($conn, $query);
    ?>
    
    Code (markup):
    Also i have checked the console log and it tells me the following:
    
    Failed to load resource: net::ERR_NAME_NOT_RESOLVED
    jquery.js:3818 jQuery.Deferred exception: Illegal invocation TypeError: Illegal invocation
        at add (https://censored.com/jquery.js:8463:5)
        at buildParams (https://censored.com/jquery.js:8450:3)
        at buildParams (https://censored.com/jquery.js:8444:4)
        at buildParams (https://censored.com/jquery.js:8444:4)
        at buildParams (https://censored.com/jquery.js:8444:4)
        at buildParams (https://censored.com/jquery.js:8444:4)
        at buildParams (https://censored.com/jquery.js:8444:4)
        at Function.jQuery.param (https://censored.com/jquery.js:8483:4)
        at Function.ajax (https://censored.com/jquery.js:9073:20)
        at HTMLDocument.<anonymous> (https://censored.com/play.php?grid=E9:336:7) undefined
    jQuery.Deferred.exceptionHook @ jquery.js:3818
    jquery.js:3827 Uncaught TypeError: Illegal invocation
        at add (jquery.js:8463)
        at buildParams (jquery.js:8450)
        at buildParams (jquery.js:8444)
        at buildParams (jquery.js:8444)
        at buildParams (jquery.js:8444)
        at buildParams (jquery.js:8444)
        at buildParams (jquery.js:8444)
        at Function.jQuery.param (jquery.js:8483)
        at Function.ajax (jquery.js:9073)
        at HTMLDocument.<anonymous> (play.php?grid=E9:336)
    
    Code (markup):
    What does it mean?

    Also, running changeheading.php works. It does empty the value so i assume the file doesnt even get called.
     
    Last edited: Jan 8, 2019
    jasperschellekens, Jan 8, 2019 IP
  10. sarahk

    sarahk iTamer Staff

    Messages:
    25,183
    Likes Received:
    3,428
    Best Answers:
    100
    Trophy Points:
    665
    #10
    It's probably failing because your document.ready is in the wrong place. You should use it (my example didn't, for brevity). Change your javascript to
    
    <script>
    $(document).ready(function(){
    // find elements
    var buttons = $(".compass");
    var direction = $('#direction');
    
    // handle click and add class
    buttons.on("click", function(){
       var cmd = $(this).html();
       direction.html(cmd);
       $.ajax({url:"changeheading.php",data: {"direction":direction}}).done(function(data){console.log(data)});
       });
    });
    </script>
    HTML:
     
    sarahk, Jan 8, 2019 IP
  11. jasperschellekens

    jasperschellekens Greenhorn

    Messages:
    25
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    5
    #11
    Thank you for your reply. Sadly it didn't do the trick. It doesn't execute changeheading.php
    Take a look at this screenshot. Below the compass you see the E? It went from None to E when i clicked east so that part works.
    Sadly it doesn't run the php file somehow while the file does work when i run it independently.
    I really wonder what the problem is.

    Screenshot:
    [​IMG]
     
    jasperschellekens, Jan 8, 2019 IP
  12. sarahk

    sarahk iTamer Staff

    Messages:
    25,183
    Likes Received:
    3,428
    Best Answers:
    100
    Trophy Points:
    665
    #12
    is changeheading.php in the same folder as the html file? you don't have a path so that's where it'll be looking.
    I just realised that in your ajax you are passing "direction" and not "cmd" and you still aren't sending "shipid"
     
    sarahk, Jan 8, 2019 IP
  13. jasperschellekens

    jasperschellekens Greenhorn

    Messages:
    25
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    5
    #13
    Yes it is in the same folder. shipid is stored in a session after character selection.
    I copy that one to shipid inside the changeheader.php file. Im confused right now about direction and cmd because they are both in the code.

    Okay so i tried this:
    
    <script>
        $(document).ready(function(){
        // find elements
        var buttons = $(".compass");
        var direction = $('#direction');
    
        // handle click and add class
        buttons.on("click", function(){
           var cmd = $(this).html();
           direction.html(cmd);
           $.ajax({url:"changeheading.php",data: {"cmd":cmd}}).done(function(data){console.log(data)});
           });
        });
        </script>
    
    //changeheading.php
    <?php
        session_start();    
          ob_start(); 
        require_once 'connect.php';
        $shipid = $_SESSION["SELECTEDSHIP"];
        $var = filter_input(INPUT_GET, 'cmd', FILTER_VALIDATE_INT);
        $query = "UPDATE playerships SET HEADING = '$var' WHERE ID='$shipid'";
        mysqli_query($conn, $query);
    ?>
    
    Code (markup):
    It works now but it doesn't store a letter but emptys the field. My guess is that i made an error with filter_input.
     
    Last edited: Jan 8, 2019
    jasperschellekens, Jan 8, 2019 IP
  14. sarahk

    sarahk iTamer Staff

    Messages:
    25,183
    Likes Received:
    3,428
    Best Answers:
    100
    Trophy Points:
    665
    #14
    You have a .done function on the ajax command that will show any output from the php script. Try doing a var_export of $query and see if the values are what you'd expect.
     
    sarahk, Jan 8, 2019 IP
  15. jasperschellekens

    jasperschellekens Greenhorn

    Messages:
    25
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    5
    #15
    I tried doing var_export but didn't really understand how it works...
    I have changed the code a little and i think cmd is empty?
    Because the $_POST responds true on a isset() and is still changing the value to nothing.
    Basically this:
    
    $var = $_GET['newheading'];
    
    Code (markup):
    Is doing this:
    
    $var = "";
    
    Code (markup):
    This is the code i have now:
    
        <div class="compass compass-north">N</div>
        <div class="compass compass-south">S</div>
        <div class="compass compass-east">E</div>
        <div class="compass compass-west">W</div>
        <div id='direction'>
        None
        </div>
    
        <script>
        // find elements
        var buttons = $(".compass");
        var direction = $('#direction');
    
        // handle click and add class
        buttons.on("click", function(){
           var cmd = $(this).html();
           direction.html(cmd);
           $.ajax({
                url: 'changeheading.php',
                type: 'GET',
                data : { newheading : cmd },
               
            });
           });
        </script>
    //changeheading.php
    <?php
        session_start();    
          ob_start(); 
          if(isset($_GET['newheading']))
          {
            require_once 'connect.php';
            $shipid = $_SESSION['SELECTEDSHIP'];
            $var = $_GET['newheading'];
            $query = "UPDATE playerships SET HEADING = '$var' WHERE ID='$shipid'";
            mysqli_query($conn, $query);
        }
    ?>
    
    Code (markup):
     
    jasperschellekens, Jan 8, 2019 IP
  16. sarahk

    sarahk iTamer Staff

    Messages:
    25,183
    Likes Received:
    3,428
    Best Answers:
    100
    Trophy Points:
    665
    #16
    what about if you do a var_export($_GET);
    and create a data variable in the javascript and do a console.log on that to double check that the data array is right.
     
    sarahk, Jan 8, 2019 IP
  17. jasperschellekens

    jasperschellekens Greenhorn

    Messages:
    25
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    5
    #17
    I finally got it to work. Had to do it like this:
    
    data : { "cmd" : cmd },
    
    Code (markup):
    Thanks for the help it's really appreciated.
     
    jasperschellekens, Jan 8, 2019 IP
    sarahk likes this.