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

I do not want to refresh the page when I browse the database, for example. at the post office, so I helped in using a call $.postthat works to send information. There is a line .done(function( data ){that I have not used yet.

I also came across this question, which I am not sure if this is related to my question.

Returns $ .get data in a function using jQuery

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

So, I have two parts, the page on which I am included, and a separate PHP page that processes the call when it is created.

How do I create a bridge on which I can return data? Or is there an easier way to do this?

+4
source share
2 answers

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

On the server side, execute all the requests and prepare the material in a jsoned array, for example:

// 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 the 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 contents of the class .content-container. You can send as many as you want, even the prepared view displayed in the container. It depends on you.

EDIT:

, someFunc() - , ? , :

<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
    ]));
?>
+2

docs Ajax, , .

, - :

  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();
  });
+2

All Articles