Use javascript variable in php in jquery function

I want to use javascript variable in php function .. my code is below

$(document).ready(function() { 
    $("#btn_url").on('click', function() {
        var video_val = $("#video_url").val(); alert(video_val);
        alert('<?php echo getYoutubeDurationV3("<script>document.write(video_val);</script>"); ?>');
    });
 }); 

I want to use the video_val variable in a php function .. how can I do this?

+4
source share
2 answers

yes, you can do it with ajax post method.

$(document).ready(function() { 
$("#btn_url").on('click', function() {
    var video_val = $("#video_url").val(); alert(video_val);
   $.ajax({
      url: 'ajax_file.php',
      data: {duration: video_val},
      type: 'POST',
      success: function(data) {
          alert(data);
      }
   });
});
}); 

And in ajax_file.php write below code ..

<?php
$duration = $_POST['video_val'];
return $duration ;
?>
+1
source

You can use Ajax for this solution. When you place a PHP function getYoutubeDurationV3in a file .php.

$(document).ready(function() { 
$("#btn_url").on('click', function() {
    var video_val = $("#video_url").val(); alert(video_val);
   $.ajax({
      url: 'yourphpscript.php',
      data: {duration: video_val},
      type: 'POST',
      success: function(data) {
          alert(data);
      }
   });
});
}); 

And in your PHP file, you can get a value similar to this:

<?php
$duration = $_POST['video_val'];

//rest of your logic, in your case your function

//return your response back to your webpage.
return $response;
?>
+2
source

All Articles