-2

I have a php function that simply get me the value of an array given the key.

Example:

<?=__('mykey')?>

Return the value of my array.

I would to call this function after an ajax jQuery call, with a param. The POST give me a json array, and I need to use the previous funct like this

$.ajax({
    url: myfile.php',
    type: 'POST',
    data: $('#contact_form').serialize(),
    dataType: 'json',
}).done(function(data) {
    str = '';
    $.each(data, function(index) {
       $('#message').html(" <?=__('"+index+"')?> ");
    });
})

The problem is that the index value inside the $.each function is not passed to php...there is a way to solve it or i have to do something like this?

 $.each(data, function(index) {
     switch(index):{
         case 1: $('#message').html(" <?=__('1')?> "); break;
         case 2: $('#message').html(" <?=__('2')?> "); break;
         case 3: $('#message').html(" <?=__('3')?> "); break;
             ...
     }

 });
Danilo
  • 2,016
  • 4
  • 24
  • 49
  • 2
    I'm fairly certain the answer can be found here: http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php – Thomas Riley Aug 21 '13 at 18:32
  • p.s. the short tags are a no-no up above, save your self some refactoring when you upgrade PHP versions in the future and use the full tags. – xXPhenom22Xx Aug 21 '13 at 18:46

2 Answers2

1

I've had to do something similar and actually used jQuery to set the value on a hidden input for me to grab later.

 $('#some-hidden-input').val(yourvalue)

Make sure this hidden field exists and is in the rendered HTML

Then the PHP can simply grab that input value on POST.

$myVar = $_POST['some-hidden-input'];
xXPhenom22Xx
  • 1,265
  • 5
  • 29
  • 63
  • 1
    You could also use $.data(), which is meant for this sort of thing. `$('#message').data('name', value)`. And you retrieve it: `$('#message').data('name')` – Ringo Aug 21 '13 at 18:37
1

To pass variables to PHP via Javascript, the only reasonable way is to use AJAX, but you do it only when you are posting something. If not, the best way is to have a hidden input field.

Based on different conditions you define, you can set the hidden input field to carry the value you want to apply it to.

To assign the value to <input name="A" id="B">

$("Input[name='A']").val(data);

or

$('#B').val(data);

Both will assign the value of data to the input field

Sasanka Panguluri
  • 3,058
  • 4
  • 32
  • 54