lulu
lulu

Reputation: 3

failed to pass jquery array to php variable in same page

on this page (rolemanage.php), I have button when it clicked it will trigger the script to give the array data

button code (rolemanage.php) :

a href="<?= base_url('admin/roleaccess/') ?>" data-toggle="modal" data-target="#aksesModal" class="badge badge-warning aksesModal" data-id="<?= $r['id_lvl']; ?>" class="badge badge-warning">Akses</a>

onclick script (rolemanage.php)

$('.aksesModal').on('click', function() {

    const id = $(this).data('id');

    $.ajax({
        url: "<?= base_url('admin/getMenuid'); ?>",
        data: {
            id: id
        },
        method: 'post',
        dataType: 'JSON',
        success: function(data) {
            var strData = JSON.stringify(data);                
        }
    }); });

so the variable data success get the array back from admin/getMenuid and the result arrays in console like this :

(1) […] ​ 0: Object { id: "4", menu: "Barang Habis Pakai" } ​ length: 1

then after that I tried to make that object to string using json.stringify in success: function

and the result like this :

[{"id":"3","menu":"Menu"}]

the question is : when I tried call strData in this page (rolemanage.php) using

var_dump(json_decode($_POST['strData']));

it shows undefined index strData.

how to get the strData value then ?

Upvotes: 0

Views: 83

Answers (2)

Donny
Donny

Reputation: 487

You should perform anothere AJAX request in which you pass strData as parameter.

Furthermore, if you want to keep everything in the same file (rolemanage.php) you should write an if statement that checks whether strData exists or not and do something based on the result

Upvotes: 0

Quentin
Quentin

Reputation: 943163

You can't.

  1. rolemanage.php runs
  2. The HTTP server sends the result to the browser
  3. The browser runs the JavaScript
  4. roleaccess runs
  5. The HTTP server sends the result to the browser
  6. You can process the result with JavaScript

Ajax doesn't involve time travel. You can't change what happened at step 1 with data you don't get until step 4.

Do your processing with JavaScript in step 6 (and modify the DOM with the new data), or don't use Ajax and use a regular form submission instead.

Upvotes: 1

Related Questions