简体   繁体   中英

Php does not echo the data from a jQuery Ajax submit

I am fiddling with jQuery.ajax() and php, and I need some pointers in order to make everything work:

Here is the php code:

if(!empty($_POST["fname"])){
        $firstName = $_POST["fname"];
        echo $firstName."<br />";
    }
    if(!empty($_POST["id"])){
        $age = $_POST["id"];
        echo $age;
    }

Here is the jQuery code:

jQuery("#ajaxForm").submit(function(event){
    event.preventDefault();

    var firstName = jQuery("#firstName").val();
    var age = jQuery("#age").val();

    // jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
    jQuery.ajax({
        type: "POST",
        url: "http://localhost/profiling/index.php",
        data: {fname:firstName, id:age}
    }).done(function(result){
        alert("Your data has been submitted!" + firstName);
    });
    var result;
    console.log(result);

});

The values from jQuery exist, I get the alert, telling me the data has been submitted, firebug shows the Ajax post as working.

Why doesn't php gets my data and echo it?

You need to get the returned data by the php and do something with it. See the added line of code below.

jQuery("#ajaxForm").submit(function(event){
event.preventDefault();

    var firstName = jQuery("#firstName").val();
    var age = jQuery("#age").val();

    // jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
    jQuery.ajax({
        type: "POST",
        url: "http://localhost/profiling/index.php",
        data: {fname:firstName, id:age}
    }).done(function(result){
        alert("Your data has been submitted!" + firstName);
        alert("This is the data returned by the php script: " + result)
    });

});

You have to use the success callback function to process the response from the POST to your Php page.

As stated in this thread

Your code could look similar to the following:

  /* Send the data using post and put the results in a div */
$.ajax({
  url: "test.php",
  type: "post",
  data: values,
  success: function(returnval){
      alert("success");
       $("#result").html('submitted successfully:' + returnval);
  },
  error:function(){
      alert("failure");
      $("#result").html('there is error while submit');
  }   
}); 

So, you have to somehow append the response from your Php to an HTML element like a DIV using jQuery

Hope this helps you

The correct way:

<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>

Then the jquery script:

<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM