webmasters
webmasters

Reputation: 5831

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?

Upvotes: 0

Views: 5355

Answers (3)

T.Todua
T.Todua

Reputation: 56351

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>

Upvotes: 0

chuckieDub
chuckieDub

Reputation: 1835

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)
    });

});

Upvotes: 1

juanreyesv
juanreyesv

Reputation: 853

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

Upvotes: 0

Related Questions