Bobby Bobby - 3 months ago 15
PHP Question

Get ID from URL and send it to PHP via Ajax

So I have a page

index.php?packageID=153
. That page has a form which when submitted is sent to PHP via Ajax call

<script type="text/javascript">
$(document).ready(function()
{
$(document).on('submit', '#form_name', function()
{

var data = $(this).serialize();


$.ajax({

type : 'POST',
url : 'phpfile.php',
data : data,
success : function(data) {
$('.result-modal').html(data);

},
error: function (request, status, error) {
alert(error.responseText);
//or console.log(request.responseText), or status or error;
}
});
return false;
});

});
</script>


I want to get that ID from the URL. I usually just do
$_GET['PackageID']
(in my PHP file) to get the ID from the URL when I'm not using Ajax, but it doesn't work with ajax (from what I'm experiencing). How do I get That ID in my PHP file?

Answer

Two possibilites:

  1. You insert the PackageID as a GET parameter into the url:

    url   : 'phpfile.php?PackageId=<?php echo $_GET['PackageID']; ?>',
    
  2. You insert the parameter into the JavaScript data object like:

    var data = $(this).serialize();
    data.PackageId = <?php echo $_GET['PackageId']; ?>;
    
    $.ajax({
    [...]
    

However you do it, at some point you have to output text from PHP inside your JavaScript code.