Calvin
Calvin

Reputation: 46

Using PHP file via JavaScript/Jquery using an HTML file only

I'm exploring several types of programming style in web designing. But it suddenly came to my mind. Can a PHP file be read using JQuery/JavaScript on a HTML file. An example. I would open login.php using $.ajax inside the index.html page. Take note about the extensions in the example

Upvotes: 0

Views: 151

Answers (2)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

Calvin!, your question really is unclear!
And is denoting very few efforts...

Based on the reading of all comments, I can answer this with examples:

In a test.html file:

<span>TEST</span><br>
<?php
echo "PHP works.";
?>

outputs:

TEST

But the exact same code in a test.php file outputs:

TEST
PHP works.


NOW using jQuery in an test2.html file to access a separate PHP file asynchronously.

Assuming this basic ajax-requested-file.php which content is:

<span>Ajax content!</span>

If you call it from a test2.html file like this:

<span>TEST#2 using Ajax</span><br>
<div id="ajaxResult"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script>
$.ajax({
  url:"ajax-requested-file.php",
  data:"",
  method:"post",
  success:function(html){
    $("#ajaxResult").html(html);
  }
});
</script>

It outputs:

TEST#2 using Ajax
Ajax content!

Note that, if you are really attentive...
You will notice a milliseconds delay between the appearance of the first line and the second one.
Like here : https://www.bessetteweb.com/SO/43795339/test2.html

Upvotes: 1

Oswin Noetzelmann
Oswin Noetzelmann

Reputation: 9545

Technically you can send a PHP file to a client, but a browser cannot execute PHP code, so there is no point in serving a php script to the client side.

If you are looking for the right web site architecture you should look into the single page architectural style. With it you just create a single HTML page for your site and load any additional content via ajax requests. For changing the page content you rely on js frameworks that manipulate the html DOM tree dynamically in place.

Note that you don't have to be strict on the single page. You can apply the same style for say a handful of logically different pages in your application as well.

To read more see this article and this answer.

Upvotes: 0

Related Questions