Ravi Shanker Gowda
Ravi Shanker Gowda

Reputation: 111

Passing sql string variable into javascript function

I am trying to pass a string from a query into a javascript function.

An integer will pass into the function but string will not.

echo "<a href='#' onclick='delete_game({$title});' 
class='btn'>Delete</a>";

<script type='text/javascript'>
function delete_game(title){
    var answer = confirm('Really?');
    if(answer){
        window.location = 'delete.php?id=' + title;
    }
}
</script>

I expected the javascript function to be executed, but instead nothing happens.

Upvotes: 1

Views: 826

Answers (2)

Peter
Peter

Reputation: 9113

A few things:

I would change window.location to window.location.href
Change your echo to:

echo "<a href=\"#\" onclick=\"delete_game('" . $title . "');\" class=\"btn\">Delete</a>";

Check if $title is set

var_dump($title);

If you'd like to make it a bit cleaner and are prepared to use jQuery:

<a href="#" class="btn delete" data-title="<?= $title ?>">Delete</a>
<script type='text/javascript'>
$(document).on('click', '#delete', function () {
   var title = $(this).data('title');
   var answer = confirm('Really?');
    if (answer){
        window.location.href = 'delete.php?id=' + title;
    }
});
</script>

Upvotes: 0

Leonardo Silva
Leonardo Silva

Reputation: 21

Why don't you use ajax for this? As mentioned in comments mix PHP/JS isn't good.

In your HTML, you can do something like

I'm assuming that you are using Blade.

<a href="#" onclick="return deleteGame({$title})">Delete Game</a>

Then in your javascript, you do this using jQuery:

function deleteGame(title){
    var answer = confirm('Really?');
    if(answer){
        $.ajax({
          url : "your-php-file.php",
          type : 'post',
          data : {
               title : title
          }
     })
     .done(function(msg){
          $("#result").html(msg);
     })
     .fail(function(error){
          console.log(error);
     }); 
    }
}

In your PHP you process receiving the data from post $_POST

$title = $_POST['title'];

You can understand better the Ajax function of jQuery here.

Upvotes: 1

Related Questions