$ .post does not send data to PHP script

Well, I do not understand what is happening. I am trying to transfer form data to my PHP script from a simple jQuery script, but for some reason when I try to access $ _POST the PHP data says $ _POST is empty?

Here we go, so I have the following jQuery and php scripts

JQuery

var post = $('#cform').serialize(); console.log("POST DATA: " + post); $.post(action, post, function(data){ document.getElementById('message').innerHTML = data; $('#message').slideDown('slow'); $('#cform img.contact-loader').fadeOut('slow',function(){$(this).remove()}); $('#submit').removeAttr('disabled'); if(data.match('success') != null) $('#cform').slideUp('slow'); }); 

Php

 $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $phone = $_POST['phone']; $comments = $_POST['comments']; 

The var message console log looks like this

 POST DATA: fname=Daniel&lname=Jarvis&email=test%40gmail.com&phone=4444444444&comments=hello 

And var_dump $ _POST says it

 array(0) { } 

I do not know why this gives me so many problems, so any help would be greatly appreciated.

PS I also tried just doing this for post data, but it still didn't work.

 var post = {fname: $('#fname').val(), lname: $('lname').val(), ...} //you get the idea 

The .log console looked like this:

 {fname: "Dan", lname: "Jarvis", ...} 

But when I var_dumped the $ _POST variable, it still said

 array(0) { } 
+4
source share
1 answer

* There are several problems in the code,

1.Add event that ajax will trigger.

2. Your php script does not transmit any data.

3.Do not return false or disable defaul to stop submitting the form manually (I think this is the main problem)

check solution: *

HTML:

  <form id="form"> <input type="text" name="fname"> <input type="text" name="lname"> <input type="text" name="email"> <input type="text" name="phone"> <input type="text" name="comments"> <input type="submit" name="submit" value="submit"> </form> <span id="message"></span> 

JavaScript:

  $("#form").submit(function(){ var post = $('#form').serialize(); console.log("POST DATA: " + post); $.post('target.php', post, function(data){ document.getElementById('message').innerHTML = data; $('#message').slideDown('slow'); $('#cform img.contact-loader').fadeOut('slow',function(){$(this).remove()}); $('#submit').removeAttr('disabled'); if(data.match('success') != null) $('#cform').slideUp('slow'); }); return false; }) 

PHP (I assume your php script is target.php):

  $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; $phone = $_POST['phone']; $comments = $_POST['comments']; echo $fname.$lname.$email.$phone.$comments; 
0
source

All Articles