Home > Software engineering >  How to send data using jQuery ajax
How to send data using jQuery ajax

Time:03-21

this is my html

<!-- <form action="view.php" method="post">  -->
        <input type="text" name="text" id="name">
        <input type="submit" value="submit">
    <!-- </form> -->

I don't want to send the data by using form Couse it only send named attribute data that's why I am sending data by $.ajax() method and this is script

$(document).ready(function () {
    var details = {};
    $('input[type="submit"]')
        .click(function () {
            details = { name: $('input[type="text"]').val() };
            $.post({
                url: "view.php",
                method: "post",
                data: details,
                success: function (result) {
                    console.log("done")}
             });
           window.open('view.php','_self');
});});

after all this thing i want to retrieve the data on view.php file but i am fail to achieve it on that file it is showing the array is empty

<?php
var_dump( $_POST);
//the array is empty
?>

suggest me something please.

CodePudding user response:

The ajax request and the request made from window.open are two different requests. Think of it like two different phone calls that you'd receive... And having absolutely no "memory" of the conversation at the end. You would need a database for that "memory" and it's something else.

To send some data to the backend (to process it) and want to have a result back into the original page, use the success callback.

HTML in original page:

<input type="text" name="text" id="name">
<input type="button" value="submit">
<div id="backendResult"></div>

JS in original page:

$(document).ready(function () {
  var details = {};
  $('input[type="submit"]').click(function () {
    details = { name: $('input[type="text"]').val() };
    $.post({
      url: "view.php",
      method: "post",
      data: details,
      success: function (result) {
        console.log("done")
        $('#backendResult').html(result)
      }
    });
  });
});

view.php:

<?php
$name = $_POST['name'];
echo 'Hello '.$name.'!';
?>

CodePudding user response:

You can do like this.

$(document).ready(function () {
    var details = {};
    $('input[type="submit"]')
        .click(function () {
            details = { name: $('input[type="text"]').val() };
            $.post({
                url: "view.php",
                method: "post",
                data: details,
                success: function (result) {  // {name : 'the text you typed'}
                    console.log("done")
                    $("body").load('view.php', function(){
                       $("#name").val(result.name);
                    });
                }
             });
});});
  • Related