0

I'm sending request by $.ajax method from test.php to ajax.php page. The console shows "200 ok" that means the request is ok. But return nothing, although the console doesn't show any error. My used pages are as following:

test.php

<div id="return-data">
    <ul class="return-lists">
    </ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$('.submit-form').click(function() {
    var name = "tanvir";
    var address = "Dhaka";

    var cData = "name=" + encodeURIComponent(name) + "&address=" + encodeURIComponent(address);

    $.ajax({
        url: "ajax.php",
        type: "POST",
        data: cData,
        success: function(data)
        {
            alert(data);
            $('#return-data .return-lists').append(data);
        }
    });
});
</script>

And ajax.php

<?php
    if( isset($_POST['name']) ) {
    $name = $_POST['name'];
    $address = $_POST['address'];

    $lists = '';
    $lists .= '<li>' . $name . '</li>';
    $lists .= '<li>' . $address . '</li>';


    return $lists;
    exit;
}

I also have tried by removing if( isset($_POST['name']) ) {} and by using echo instead of return in ajax.php

4
  • 1
    Is '.submit-form' a submit button in a form? Commented Aug 21, 2015 at 18:11
  • Yeah, it is a button. And on click it, the request is submitted. Commented Aug 21, 2015 at 18:18
  • you need to use echo in ajax.php Commented Aug 21, 2015 at 18:20
  • If you check the network tab you will see two requests. You have to stop the button from performing its default behaviour - namely submitting the form. api.jquery.com/event.preventdefault Commented Aug 21, 2015 at 18:21

2 Answers 2

1

Try this one. Change return $list for echo $list and no need to use exit at the end of ajax.php

 <?php
 if( isset($_POST['name']) ) {
  $name = $_POST['name'];
  $address = $_POST['address'];

  $lists = '';
  $lists .= '<li>' . $name . '</li>';
  $lists .= '<li>' . $address . '</li>';


 echo $lists;

 }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks henry, I tried to accept your answer immediately. But on my account your answer was disappeared after displaying for few minutes. Thanks again.
0

Yeah, I have solved the problem by normally putting "echo" instead of "return". Because the "return" return an string and echo print an string. Thanks to all.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.