-4

its the code for posting a javascript variable into php... but its not working..sugesstion... i want to take value of id from javascript and post into a php.

<!DOCTYPE html>
<html>
    <body>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $( document ).ready(function() {
    $("form").submit(function() { 
        var id = $("input[type=submit]").attr('id');
        alert(id);
       $.ajax({
                type: 'post',
                url:('abcde.php')
                data: {id1: id},success: function(response){}
                alert(id1);
                  });
    });
     });
</script>
    </head>
        <form action="abcde.php" method="POST">
            <!-- other form fields -->
            <input type="submit" id="a" name="idVal" value="a">
        </form>
    </body>
</html>
<?php
if(isset($_POST['id']) ){
                            $id=$_POST['id'];
                        echo $id;
                        }
?>
MaNsHa QaRiB
  • 37
  • 1
  • 7
  • 4
    Possible duplicate of [How to pass JavaScript variables to PHP?](https://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php) – steros Aug 07 '18 at 06:00

1 Answers1

0

ohh boy, 1st: it's

data: {'id': id}

secondly, your code is really wrong on this part, you are not doing anything in success, and you just randomly put an alert() in, with a variable that doesn't even exist. So instead of success: function(response){}, it should be success: function(response){alert(response);} and forget about the alert(id1);

Other errors I saw from looking at it quickly: you are submitting your form from AJAX and HTML as well. You should block the default behavior with a function at the beginning of .submit(funcition() {...}. There already is a function for that, but I can't remember.

Lastly, you are sending the form data to the same page you are submitting from. You will get an answer from AJAX with the same page you are looking at. You should extract the php code to a different file and make abcde.php a simple abcde.html file.

One last thing: instead of alerts, you should use Console.log and watch the browser's console for debugging. You will see a bunch of errors, which makes debugging a lot easier.

You should, instead of blindly coding, be more mindful about what is responsible for what. You should be thinking more about the side-effects of you are introducing to your code. This will come with experience, we've all been there. Make sure one 'thing' is only responsible for ONE task.

László Stahorszki
  • 1,102
  • 7
  • 23