janicehoplin
janicehoplin

Reputation: 397

How to get data back from a $.post call?

I don't want to refresh a page when I am searching through a database eg. on post, so I had help in using a $.post call which works for sending information. There is a .done(function( data ){ line which I haven't used yet.

I also came across this question which I'm not sure if this ties to my question.

Return $.get data in a function using jQuery

I'm trying to search through a database, string match, and return the rows with matching strings. But I want to do this without refreshing the page so I would think that I am using the $.post call and using the .done(function( data ){ which is triggered by javascript (a button).

So I have two parts, the page I'm on and a separate PHP page that processes the call when made.

How do I make the bridge where I can return the data back? Or is there an easier way to do this?

Upvotes: 4

Views: 2737

Answers (2)

AmBeam
AmBeam

Reputation: 332

The method .done(function(){}) is exactly what You would like to use, but You can also take a look at third argument (callback) of $.post function.

On server side, do all the queries and prepare the stuff in jsoned array like:

// set up data to send
$contentArray = [
    'content' => 'Some content',
    'foo' => 'bar',
];

$jsonResults = json_encode($contentArray);
// you can always send header('Content-Type: application/json'); instead of using simple die function.
die($jsonResults);

Then on client side:

<div class="content-container"></div>
<script type="text/javascript">
    function someFunc() {
        (...)
        $.post(addr, values, function(res) {
            var response = $.parseJSON(res);

            $('.content-container').html(response.content);
        });
    }
</script>

This should update the content of the .content-container class only. You can send as much as you want, even prepared view to be displayed in the container. This is up to You.

EDIT:

Just to be sure, you're calling someFunc() on some button click event, right? If not, do it as follows:

<div class="content-container"></div>
<a href="someScript.php" class="callMe" data-content-id="1">Click here</a>
<script type="text/javascript">
    function changePageContent(addr, contentId) {
        $.post(addr, {contentId:contentId}, function(res) {
            var response = $.parseJSON(res);
            $('.content-container').html(response.content);
        });
    }

    $('.callMe').on('click', function() {
        changePageContent($(this).attr('href'), $(this).attr('data-content-id'));

        return false;
    });
</script>

someScript.php:

<?php
    // you should force your script to allow only XML HTTP request here
    if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die('AJAX requests only..');
    }

    // always remember to escape somehow your post values before you use them
    $contentId = is_numeric($_POST['contentId']) ? intval($_POST['contentId']) : null;

    if (null == $contentId) (...) // throw exception or return status=false

    // do your mysql query like: "SELECT * FROM content WHERE id=".$contentId;

    // well, it would be better to send headers instead of that
    die(json_encode([
        'status' => true, // this is a good practice to send some info, if everything is fine, if mysql row has been found etc..
        'result' => $result, // mysql row, this is just in case you need other values to display
        'content' => $result['content'], // I assume you have 'content' column in your mysql
    ]));
?>

Upvotes: 2

Michael Doye
Michael Doye

Reputation: 8171

Take a look at the docs for Ajax, there really is a lot of info there which will help.

In short, you could do something like this:

  function myPost() {
      // Set the data 
      var data = {
        'key'   : 'value',
        'key_2' : 'value_2' 
      };
      // Do the post
      $.post( '/your-url/', data, callBack );
  }

  function callBack( data ) {
      // If the $.post was successful
      success: function( data ) {
          // do stuff
          console.log( data ); // returned from your endpoint
      },
      // If there was an error
      error: function( jqXHR, textStatus ) {
          // do stuff
          console.log( "Request failed: " + textStatus );
      }
  }

  // On click of your element, fire the post request
  $('#element').on('click', function() {
      myPost();
  });

Upvotes: 2

Related Questions