0

I am learning AJAX and I am trying to log all the data parameters in the console in case of success and in case of a failure to throw an alert. My code works and I can successfully dump the data I send, but nothing shows up in the console, even though I explicitly put console.log within the Javascript to register that. this is my code. Html page

<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <h2>Send JSON</h2>
  <form action="postrequest.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
  <input type="text" name="param1"/>
  <input type="text" name="param2"/>
  <input type="text" name="param3"/>
  <button type="submit">Submit</button>
</form>


</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
  $("document").ready(function(){
    $(".js-ajax-php-json").submit(function(){
     var param1 = $("#param1").val();
     var param2 = $("#param2").val();
     var param3 = $("#param3").val();
    $.ajax({
  url : 'postrequest.php',
  contentType: "application/json",
  dataType: "json",  
  type : 'POST',
  data: JSON.stringify({ 
    param1: param1,
    param2: param2,
    param3: param3
  }),
  success: function(data) {
            console.log(data);
        },
  error: function (data) {
    alert(data.param3);
  }       
       });
  });
});

</script>
</html>

postrequest.php

<?php 

var_dump( $_POST);

What am I doing wrong?

  • can you add postrequest.php please and Change : `contentType: "application/json", dataType: "json",` to only `dataType: "JSON",` –  Jan 19 '20 at 21:00
  • postrequest.php is already there – Ancient Hero Jan 19 '20 at 21:03
  • is this all you have in that page ? `var_dump( $_POST);` –  Jan 19 '20 at 21:04
  • Yes, that is all. – Ancient Hero Jan 19 '20 at 21:06
  • See this post as an example How to get response from php : https://stackoverflow.com/a/59490784/12232340 –  Jan 19 '20 at 21:09
  • You need to return data as json from postrequest.php response Try use echo json_encode($_POST) instead of var_dump( $_POST) – Nerjuz Jan 19 '20 at 21:14
  • That doesn't change anything. It will still dump the data on the page but nothing will show up in the console. I had that before. – Ancient Hero Jan 19 '20 at 21:18
  • @Dilek I don't see how that resolves my problem? – Ancient Hero Jan 19 '20 at 21:30
  • @AncientHero `$_POST['param1'];` you need to have something in `postrequest.php` to return as data. that post https://stackoverflow.com/q/59489824/12232340 has everything you need, CHECK the QUESTION in link, not the answer. or simply add `` if you are posting data. –  Jan 19 '20 at 22:05
  • You've used name attributes in the html and ID selectors in the JavaScript – Djave Jan 20 '20 at 07:53

2 Answers2

2

Error 1: Remove the form tag. It will work because it contains action="postrequest.php". You are doing 2 things at the same time.

  1. Submitting the form via PHP using the form tag.
  2. You are performing ajax and submitting the form.

Error 2: You are writing var param1 = $("#param1").val(); Where is the param1, param2,param3 you defined?

Error 3: You are giving the jquery link, you don't have closed the script tag.

Error 4: You are sending the data in ajax and outputting the ajax response again with the same variable

Error 5: Ajax error block you have created is wrong.

 <!DOCTYPE html>
    <html>
    <body>
      <input type="text" name="param1" id="param1"/>
      <input type="text" name="param2" id="param2"/>
      <input type="text" name="param3" id="param3"/>
      <input type="button" value='Submit' class="js-ajax-php-json" />

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script type="text/javascript">
         $(document).ready(function() {
            $(".js-ajax-php-json").click(function() {

                var param1 = $("#param1").val();
                var param2 = $("#param2").val();
                var param3 = $("#param3").val();
                $.ajax({
                    url: 'postrequest.php',
                    dataType: "html",
                    type: 'post',
                    data: {
                        param1: param1,
                        param2: param2,
                        param3: param3
                    },
                    success: function(rsp) {
                        console.log(rsp);
                    },
                    error: function(jqXHR, status, err) {
                        console.log("Error");
                    },
                });
            });
        });
      </script>
      </body>
    </html>

postrequest.php page

<?php
  print_r($_POST);
?>

I have just rewritten your code with a very simpler one. You can change it as per your requirement.

Amanjot Kaur
  • 2,028
  • 4
  • 18
  • 33
  • Good answer, except a) should not remove the `form` - just use [`event.preventDefault()`](https://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false); and b) don't use `click()`, stick with `submit()` to maintain standard accessibility, eg so return can submit the form as usual. – Don't Panic Jan 20 '20 at 09:58
  • @Don'tPanic I was not able to do that with form. Can you give me an example how to submit without removing the form, that would be very helpful. – Amanjot Kaur Jan 20 '20 at 10:02
  • Search for `preventDefault()`, it is the standard way to do this. [Here's a super-simple jsFiddle](https://jsfiddle.net/dont_panic/zj0kn7vy/) demonstrating it. Open devtools and watch the console. Comment out the `e.preventDefault()` line to see the normal behaviour (normal html form submission). – Don't Panic Jan 20 '20 at 10:08
  • I used it earlier. I don't know why it didn't work earlier. That's why I removed form. Anyways, Thanks @Don'tPanic – Amanjot Kaur Jan 20 '20 at 10:11
0

I think the root cause is that the page is reloading once you hit submit. Hence you cannot see anything in the console. Try the following steps.

  1. Remove the 'action' and 'method' attributes from the form tag. This is already handled in ajax request.
  2. Add onsubmit="return false;" attribute to the form tag. This will prevent reloading of the page.
  • I made these changes and now this is what is reloading the page and I don't even see the output on the php page, it just keeps reloading the form. – Ancient Hero Jan 19 '20 at 22:17
  • Can u try to echo something in the php file after var_dump? You should get the echoed text back in ajax success handler. – Abdi Shaikh Jan 19 '20 at 22:33