skip to Main Content

I can’t pass my keys properly to my PHP server.
Here’s an example of my code

ajax: {
   url: "<?= base_url("items/getTableData") ?>",
   type: "POST",
   dataType: "json",
   data: {
     table: "users",
     select: "users.*, ut.name as user_type",
     join: {
        ["user_type as ut"]: "ut.id = users.user_type"
     },
     where: "users.status = 1"
   }
},

And within my PHP, it will only give me $_POST[‘join’][0] instead of $_POST[‘join’][‘user_type as ut’]

Anyone else having this issue? Is this even possible on jQuery?

Expected result: In my PHP, I should receive $_POST[‘join’][‘user_type as ut’] instead of $_POST[‘join’][0].

I tried

join: {
   [escape("user_type as ut")]: "ut.id = users.user_type"
},

And,

join: {
   [encodeURIComponent("user_type as ut")]: "ut.id = users.user_type"
},

2

Answers


  1. Chosen as BEST ANSWER

    It's been brought up to me that putting your SQL queries in your Javascript code is very vulnerable to hacking attacks (oops!) so I'll have to redo the code eliminating the problem.

    Although, if anyone is looking for an answer to this problem:

    I just brute-forced it by replacing my space with double underscores (__)

    join: {
       ["user_type__a__ut"]: "ut.id = users.user_type"
    },
    

    And putting my $_POST into this function:

    function fixArrayKeys($arr)
        {
            $newArr = array();
            foreach ($arr as $key => $val) {
    
                if(is_array($val)) $val = fixArrayKeys($val);
    
                if (strpos($key, "__")) $key = str_replace("__", " ", $key);
    
                if (strpos($key, "_p_")) $key = str_replace("_p_", ".", $key);
    
                $newArr[$key] = $val;
            }
    
            return $newArr;
        }
    

    This simply replaces the double underscores (__) in the key and give it spaces, "solving" the issue. It doesn't look as good of a solution.

    You can edit what alternative keywords you want, mine is double underscores for my space (__) and double underscores with a "p" (_ p _) in the middle to represent a period (.)

    Hope this helps someone!


  2. Square brackets represent an array in JSON struct. This syntax looks incorrect to me, it’s not a valid JSON object. What are those brackets around "user_type as ut" for?

    Just remove the brackets, it should work then

    join: {
        "user_type as ut": "ut.id = users.user_type"
    },
    

    By the way, spaces are allowed in JSON keys, but the key should be quoted as you did.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search