0

I want a PHP script to run on form submit and use Ajax to stop the page refreshing.

The JavaScript code successfully reaches the .done method and I put a console.log into the first line of my php script which doesn't seem to be getting triggered.

JS

$('.enquire-form').submit(function(e) {
  e.preventDefault();
  $this = $(this);
  $.ajax({
    type: "POST",
    url: "post.php",
    data: $this.serialize()
  }).done(function(data) {
    alert("done");
  }).fail(function( jqXHR, textStatus ) {
    console.log("Request failed: " + textStatus);
    alert( "Request failed: " + textStatus );
  });
});

PHP (originally it was console.log but have changed based on suggestions)

echo "hello world";

Folder directory (enquiry.html has the form in it) enter image description here

Thanks :)

Zain
  • 1,246
  • 4
  • 15
  • 26

1 Answers1

1

Unless something has changed, you can't execute JS that has been returned from an AJAX call. See this answer.

Make sure you are attempting to access the returned data via the data var inside your done function.

Chase
  • 3,009
  • 3
  • 17
  • 23
  • I changed it to echo "hello world" with no luck. – Zain Jul 16 '17 at 11:43
  • Is your PHP file running on a server? – Chase Jul 16 '17 at 11:44
  • uWamp local server – Zain Jul 16 '17 at 11:45
  • Try to call the PHP file via curl and see what happens. Or even call it from the command line with `php [your-file].php`. FWIW, your example code doesn't open with php – Chase Jul 16 '17 at 11:47
  • 1
    Also, your AJAX function only alerts "Done". If you want to see what was returned, you need to alert or console.log 'data'. – Chase Jul 16 '17 at 11:51
  • Woops, I added that in - I must have forgot to re-add it in; still no luck though :/. How do I call it from the command line? Just enter the path in? – Zain Jul 16 '17 at 11:51
  • Data does contain "hello world". As it was an echo normally I'd expect it to be on the page, does using Ajax change this? + can you please update ur post with what was wrong so i can mark it as correct – Zain Jul 16 '17 at 12:00
  • 1
    AJAX does change things. Since there is no page load, your only access to the output of the PHP script is through the `data` variable in your `.done` promise. – Chase Jul 16 '17 at 12:08
  • Thanks, think I'll spend more time learning Ajax later on today, it looks like I need to learn more about it in general :). – Zain Jul 16 '17 at 12:15