简体   繁体   中英

send array from js to php

I'm doing some assignment for school, and I'm stuck at passing array from js to php.

I have to say I'm not some expert and I'm still learning. I can't figure out what am I missing. Hope someone will help me.

I try like this.

 if(bets.length > 0) {
    $.ajax({ 
       url: "mybet.php", 
       method: "POST", 
       data: { bets : JSON.stringify( bets ) }, 
       success: function(res) { 
              console.log(res);
        } 
    }); 
  }

and php file

if (isset($_POST['bets'])) {
  $bets = json_decode($_POST['bets'], true);
  print_r($bets);

}

bets is an array in js.. and I want if I click on button proceed to collect that array and pass to php so I can work with it. I'm getting undefined index for bets on line $bets = json_decode($_POST['bets']);

print_r($_POST) is empty

You are not sending a 'proceedBet' variable in your ajax request, either you send that variable by changing the data like this:

if(bets.length > 0) {
    $.ajax({ 
       url: "mybet.php", 
       method: "POST", 
       data: { bets : JSON.stringify( bets ), proceedBet: 'Some Value' }, 
       success: function(res) { 
              console.log(res);
        } 
    }); 
  }

Or you have to change your condition to check if the bets exist like so:

if (isset($_POST['bets'])) {
  $bets = json_decode($_POST['bets'], true);
  print_r($_POST['bets']); // use print_r to check the data in the array
  //  User::redirect("ticket.php");
}

Hi here is an example I made for you:

first the html part is a simple modal to display data from request.php if the data I send from my js array is okay:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script
    src="http://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  </head>
  <body>
    <div class="container">
    <h2>Modal Example</h2>
    <!-- Button to Open the Modal -->
    <button type="button" class="btn btn-primary" id="btnDisplayModal" >
      Open modal
    </button>

    <!-- The Modal -->
    <div class="modal" id="myModal">
      <div class="modal-dialog">
        <div class="modal-content">

          <!-- Modal Header -->
          <div class="modal-header">
            <h4 class="modal-title">Modal Heading</h4>
            <button type="button" class="close" data-dismiss="modal" >&times;</button>
          </div>

          <!-- Modal body -->
          <div class="modal-body">
          <br>
          <div id="add-takeout-messages">

          </div>
          </div>

          <!-- Modal footer -->
          <div class="modal-footer">
            <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
          </div>

        </div>
      </div>
    </div>

  </div>
  </body>

the javascript part is an ajax call which display data inside the modal when the request is done:

$(document).ready(function() {
  var formData = {id:"1",name:"stan",lastname:"chacon",color:"blue"};
  function _ajaxMessage(formData){

  return $.ajax({
        url: "request.php",
        type: 'POST',
        data:{data:JSON.stringify(formData)},
        dataType: 'json'
      })

  }


  $("#btnDisplayModal").on('click', function(){
    _ajaxMessage(formData)
    .done(function(response){
      console.log(JSON.stringify(response));
      $('#add-takeout-messages').empty();
      $.each(response.messages,function(index,value){
        console.log(index,value);
      $('#add-takeout-messages').append('<div class="alert alert-success">' +
        '<button type="button" class="close" data-dismiss="alert">&times;</button>' +
        '<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> From: '+ value.from + '<br>' +  ' msg: ' + value.msg +
        '</div>')
      })
      $("#myModal").modal();
    })
  })

})

The request.php file is simple like the request file you are already using, so I guess the problem you have is your array, maybe it has an invalid format and thats why it goes empty.

if (isset($_POST["data"])) {
  $data = json_decode($_POST["data"],true);
  if ($data["name"] == "stan") {
    $array = [
      "status"=>"success",
      "messages"=>  [
        array('date' => "2019-04-11", 'msg'=>'Love you', 'from'=>'Annie' ),
        array('date' => "2019-04-10", 'msg'=>'Have a nice day', 'from'=>'Annie' )
      ]

    ];
    echo json_encode($array);
  }
}

check your array ant let us know if that was the problem =)

Hiope it helps

Simple working example you can change the logic if needed.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    let bets = [1,2,3]; // This must come dynamically.
    if(bets.length > 0) {
        $.ajax({url: "server.php", method: "POST",  data: { bets : JSON.stringify( bets) }, success: function(result){
            $("#div1").html(result);
        }});
    }
  });
});
</script>
</head>
<body>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>

<button>Send Ajax Request</button>

</body>
</html>

Server side

<?php 
if (isset($_POST['bets'])) {
    $bets = json_decode($_POST['bets'], true);
    print_r($_POST['bets']);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM