0

I have an ajax call and i get a json response from it, this is an example of the response

{"Title":"test", "price":"65.31"}

and here is my code

add_action('admin_head', 'apm_get_single_field');
  function apm_get_single_field() {
  ?>
  <script type="text/javascript" >
      function apm_get_single_field(field_name, requested_data, asin_field, amazon_domain) {
          $.ajax({
            type: "POST",
            url: ajaxurl,
            dataType: "JSON",
            data: {
                action: 'apm_get_single_field',
                postId: <?php echo get_post()->ID; ?>,
                field: field_name,
                requested_data: requested_data,
                asin: document.getElementsByName(asin_field)[0].value,
                amazon_domain: amazon_domain
            },
            success: function(Lookup_Data) {
              document.getElementsByName(field_name)[0].value = Lookup_Data.price;

              $('#apm_status_' + field_name).text("Retrived").css('color', '#04b600').fadeIn().delay(1000).fadeOut();
            }

          })
      };
      </script>
      <?php
    }

so as you can see on the above code i called the price value by using "Lookup_Data.price" which worked perfectly however what i need is to replace the ky 'price' by js variable 'requested_data' which you can see in the function arguments. i tried Lookup_Data.requested_data and Lookup_Data. + requested_data which didnt work.. guess because my pc try to search for an array key called requested_data which couldnt find because requested_data is not a key its a variable.

arabtornado
  • 63
  • 2
  • 9
  • What is your question? Yes, requested_data is a variable, not a key. requested_data is clearly not a property of the JSON response you receive from your AJAX call, so Lookup_Data.requested_data does not exist. – Casey Anderson Mar 01 '19 at 00:16
  • You should be able to reference `requested_data` within the scope of your `apm_get_single_field` function, and reference its "price" key with `requested_data.price`. Do you mean that you want to replace the "price" value in `Lookup_Data` with the "price" value in `requested_data`? – showdev Mar 01 '19 at 00:18
  • Actually what i try to do is to pass the key i wanna request from the response using the function arguments so i can use reuse the same function by changing the arguments but im wondering how to replace the key by a variable... for instance if i used php i will do it like this Lookup_Data.; but the problem is that i wanna use a js variable not a php variable. – arabtornado Mar 01 '19 at 00:23
  • 2
    You can use a variable for a key name by referencing `LookupData[myVariable]`. Here's an [example](https://jsfiddle.net/ehpf65wo/). Is that what you mean? – showdev Mar 01 '19 at 00:28
  • @showdev Thanks so much, this is exactly the answer i was looking for. – arabtornado Mar 01 '19 at 00:30

0 Answers0