简体   繁体   中英

Why does my PHP not activate when I embed it with JavaScript?

I embedded a PHP file with JavaScript but the PHP didn't work. Here's what I did:

$.get("php/file.php");

In the PHP file:

<?php
    echo "Testing PHP File"
?>

I would really appreciate it if someone answered me!

you should used $.get() like this

$.get('php/file.php', function(data) {
                alert(data);//here is your "Testing PHP File" data
            });

Make sure: this will work on any event like click or other (i suppose you know about server side and client side)

$('.class_name').click(function() {
            $.get('php/file.php', function(data) {
                    alert(data);
                });
        });
$.get("php/file.php");

works on client side and since you are not doing anything after the request, it will look like its not working.

Always consider reading the Docs .

There its explained very nicely. Copying the code from there as an example.

  var jqxhr = $.get( "example.php", function() {
    alert( "success" );
  })
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

You need a callback function to make this work. In this case, that can be the second paremeter

$.get('php/file.php', function(data) {
    // do someting with your data
});

more on $.get

I will suggest you to read the jQuery Docs or read some stuff, but for you the really helpful content on that page is examples section, in that first example is same as your question which is as below:

$.get( "test.php" );

it will Request the test.php page(in your case php/file.php), but ignore the return results. If you want to alert the returned data then use function() in $.get() as below:

$.get( "test.php", function( data ) {
  alert( "Data Loaded: " + data );
});

You can also print it on html if you want , if you have any tag with id="output" in your html here i am taking it for example you can have any jquery selector(class,element etc) then you can print it as below:

$.get( "php/file.php", function( data ) {
  $('#output').html(data);
});
//output: Testing PHP File

you can do this to catch your data outside the $.get callback

var data_;
$.get('php/file.php', function(data
{ data_ = data});
alert(data_);

you can instead call the php file using php include instead of jquery $.get

<script>
<?php include 'php/file.php';?>
</script>

In the above example, whatever you echo inside the <script> tag must be a valid JavaScript syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM