0

I'm trying to call php function from my JavaScript script. I've read several questions on how to call a php function using jQuery ajax. I simply copied most of the content and adapted it to fit my script, but somehow it's not working.

Here's my code:

    var var1 = document.getElementById("tag").value;
    var id = tag.id;
    var var3 = tag.checked;
    var test = $.ajax({
        url: '../PHP/phpFunc.php',
        type: 'GET',
        data: {param1: var1, param2: id, param3: var3},
        complete: function() {
            if(window.console) {
                console.log("success");
            }
        },
        error: function() {
            if(window.console) {
                console.log("Error");
            }
        }
    })

and the php code:

<?php

echo "<script>
     console.log(\"test\")
     </script>";
    $var1= $_GET['param1'];
    $var2 = $_GET['param2'];
    $var3 = $_GET['param3];
    $var4 = '../XML/user/'. $var1.'.xml';
   
    

?>

the "success" is being printed when the JS function is executed, but php code never returns the desired output.

  • Your PHP doesn't return anything, because you've not written the code to do it - or if you have then you've accidentally removed it from your sample so we can't debug it. Also, you're using the `complete` callback of `$.ajax()` . If you want to receive data it makes more sense to use `success` and then accept the response as an argument to that handler function. See the documentation for more details: https://api.jquery.com/jQuery.ajax/ – Rory McCrossan Jul 08 '22 at 16:30
  • [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) So you cannot execute PHP code in the browser – RiggsFolly Jul 08 '22 at 16:30
  • For example: `$.get( "../PHP/phpFunc.php", function( data ) { console.log(data); });` Also your php code seems to be missing a closing quote symbol before closing the php code block. `$var4 = '../XML/user/'. $username .'.xml'; ";` – George G Jul 08 '22 at 16:45
  • 2
    You never do anything with the response back in the Ajax call. calling the php does not magically do anything in the browser. – epascarello Jul 08 '22 at 17:04

0 Answers0