how to pass a php string by a java script parameter

1

I'm creating a click counter on the link this way:

<a href="#" onclick="return chamarPhpAjax();"></a>

That when clicking the link calls the function:

function chamarPhpAjax() {
    var so = "";
    var name = "";
   $.ajax({
      url:'/assets/classes/meuajax.php',
      type: 'post',
      data: { 'so': so, 'name': name }
  });  

  return false;
}

For Ajax, the data is sent via POST to the page "myajax.php":

<?php
function testeOnclick() {
    $so = $_POST['so'];
    $name = $_POST['name'] ;

     include_once "../config/Config.inc.php";

      $pdo->query("UPDATE '$so' SET downloads = downloads +1 WHERE name = '$name' ");

}
testeOnclick();
?>

The problem is that I can not get the data to put in var so = ""; var name = ""; of Ajax per parameter. How do I pass the data in onclick , going something like this:

<a href="#" onclick="return chamarPhpAjax(<?php $dados->so;?> , <?php $dados->name;?> );"></a>

And receive these parameters in Ajax?

    
asked by anonymous 06.09.2017 / 04:52

3 answers

0

Use data-attributes in your tag.

function chamarPhpAjax() {
    var so = event.target.dataset["so"];
    var name = event.target.dataset["name"];
    console.log("so: ", so, "name: ", name);
    //seu ajax     
    return false;
}
<a href="#" data-so="<?php echo $dados->so ?>" data-name="<?php echo $dados->name ?>" onclick="return chamarPhpAjax();">Clique</a>
    
06.09.2017 / 06:45
0

I solved this way

function chamarPhpAjax() {
   
    var so  = $('.icon-dwl').attr('data-so');
    var name = $('.icon-dwl').attr('data-name');
   $.ajax({
      url:'/assets/classes/meuajax.php',
      type: 'post',
      data: { 'so': so, 'name': name }
  });  

  return false;
}
    
06.09.2017 / 07:23
0

You are passing the parameters in

<a href="#" onclick="return chamarPhpAjax(<?php $dados->so;?> , <?php $dados->name;?> );"></a>

but its function

function chamarPhpAjax() {

 var so = "";
 var name = "";
 $.ajax({

      url:'/assets/classes/meuajax.php',
      type: 'post',
      data: { 'so': so, 'name': name }
 });

return false; }

You are not getting any parameters. Try to put

 function chamarPhpAjax(so,name) {

 var so = so;
 var name = name;
 $.ajax({

      url:'/assets/classes/meuajax.php',
      type: 'post',
      data: { 'so': so, 'name': name }
 });

return false; }
    
06.09.2017 / 13:21