Skip to content Skip to sidebar Skip to footer

How To Send Variable To Php From Javascript And Return The Result Back To JS

I have this code. var book = document.getElementById('txtBook').value; switch(book.toUpperCase()) { case 'GEN': var bk = '101'; break; case 'EXO': var bk = '101

Solution 1:

You need to use ajax.

$.get('getbook.php', {book: $('#txtBook').val()}, function(data) {
  // here you get your data and deal it 
});

Solution 2:

The simplest way is applying ajax.

Serve script(getbook.php):

$bookId = $_POST['book'];
//do some search stuff
$rows = getBookInfo($bookId);
$result = array('searchResult' => $rows);

header('Content-Type: application/json');
echo json_encode($result);

Client script(remeber to include js for jquery):

postData = {book: bookId};
$.ajax({
     type: 'POST',
     url: '/getbook.php',
     data: postData,
     dataType: 'JSON',
     success: function (jsonObj) {
        //use jsonObj.serachResult as array
     }
   });

Post a Comment for "How To Send Variable To Php From Javascript And Return The Result Back To JS"