-1

I am trying to use a combination of javascript and php to update a column within a sql database when a form gets submitted. The name of the sql database is "answers," the name of the column within the database is "FunctionsConsistency," and the form's id is "easytohard." I'm not sure, however, if it's possible to include the php (noted below by the asterisks) within this javascript code.

 <script type='text/javascript'>
 $(document).ready(function () {
$('#easytohard').on('submit', function(e) {
    e.preventDefault();
    $.ajax({
        url : $(this).attr('action') || window.location.pathname,
        type: "POST",
        data: $(this).serialize(),
        success: function (data) { 

******THIS IS THE PHP CODE*********
  $stmt = $db->prepare("UPDATE answers SET FunctionsConsistency = 1
                      WHERE id = ? AND FunctionsConsistency = 0") or die($db->error);
$stmt->bind_param("i", $id);
$stmt->execute();
 ******************     

        },
    });
});
 });
 </script>

Thanks!

1 Answers1

3

You can't mix Javascript and PHP like that.

Php should be executed on the server side while javascript meant to be executed on the client side.

You can put the Php file on your server, and just send the request to it using ajax or whatever.

Something like:

<script type='text/javascript'>
 $(document).ready(function () {
    $('#easytohard').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url : $('http://path/to/your/php/file/on/server'),
            type: "POST",
            data: {id: 'your desired id here'},
            success: function (data) { 
                // if it reach this line, it means script on the php file is executed
            },
        });
    });
 });
 </script>

And your php file should be on your server (path: http://path/to/your/php/file/on/server), containing proper includes to work.

<?php

$stmt = $db->prepare("UPDATE answers SET FunctionsConsistency = 1
              WHERE id = ? AND FunctionsConsistency = 0") or die($db->error);
$stmt->bind_param("i", $_POST['id']);
$stmt->execute();

Notice you can access to post parameters using $_POST in php.

There are still a few things you should consider, for example when the requests don't reach to server or what if server fail to execute php file ..., but you got the idea.

Also, take a look at this and this. Hope this helps.

Community
  • 1
  • 1
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
  • Thanks! I'll give it a try. For the portion that says "your desired id here," I assume I can't use $id=$SESSION['id'], as that would be php. How do I indicate that I want the id associated with the current session/user? – user3666954 Jan 15 '16 at 04:17
  • @user3666954 So, you don't need to put anything, just remove the parameter. Session information will be sent automatically and you can use `$_SESSION['id']` on your php file with no problems. – Aᴍɪʀ Jan 15 '16 at 04:24