ndAR
ndAR

Reputation: 371

Troubles passing string to ajax via javascript function

I'm getting some issues with a function, where i'm passing 2 arguments, one of them contains a string "12345.00" the main problem is that on console.log(string) this return only "12345".

Is there a way to get the entire string?

$data = array(
  array(
    'arg1' => '1', 
    'arg2' => '123'
  ),
  array(
    'arg1' => '2', 
    'arg2' => '12345.00'
  )
);

<button id="openTab">Test</button>

foreach($data as $item){
  <script>                          
    $('#openTab').click(function(e){
      e.preventDefault();
      getValues(<?php echo $item['arg1'](); ?>, <?php echo $item['arg2']; ?>);
    });                         
  </script>
}

function getValues(arg1, arg2){
  console.log(arg2);
  new Ajax.Request("<?php echo $this->getUrl('getValues') ?>", {
    method: 'POST',
    type: 'json',
    parameters: { arg1: arg1, arg2: arg2},
    onComplete: function(transport) {
      var result = JSON.parse(transport.responseText);         
      console.log(result);     
    }
  });
}

Upvotes: 0

Views: 45

Answers (1)

Dave Newton
Dave Newton

Reputation: 160181

getValues(<?php echo $item['arg1'](); ?>, <?php echo $item['arg2']; ?>);

This renders:

getValues(2, 12345.00);

You need to quote them if you want JS strings:

getValues("<?php echo $item['arg1'](); ?>", "<?php echo $item['arg2']; ?>");

Which renders:

getValues("2", "12345.00");

This can be verified by looking at the rendered JS.

You should also code defensively and assume the data that comes back might have quotes in it, e.g., it should be JavaScript-escaped before rendering it into JS.

It's important to understand that your file is basically a template. What happens on the client side is entirely dependent on how it's rendering. You can inspect the rendering by viewing source or inspecting elements to validate what's actually coming across to the browser.

Upvotes: 1

Related Questions