Ave
Ave

Reputation: 83

Including a php file dynamically with javascript and jquery

I want to include a php file later(dynamically), rather than at the top. All this file does is get some contents from server and stores it in a javascript variable that i later use in jquery.

basically when you click the link, i get the info, then display it to save resources because there are many links that may not be used.

Should i just do $("body").load("phpfile.php"); ? this should work but I am trying to find a more proper way because it has nothing to do with html tag like body.

Upvotes: 1

Views: 2931

Answers (4)

Fredefl
Fredefl

Reputation: 1381

Simply, you can't. Php is ran server-side. But you could use AJAX or Jquery AJAX

Upvotes: 0

Rene Pot
Rene Pot

Reputation: 24815

Always expect the worst from your visitors. If it where possible to include a php file with javascript, it would be a huge risk.

PHP is a server side language, and is not present in the browser. Javascript is a clientside language, and does not know anything about the PHP, only about the outputted HTML.

Use an AJAX call instead, check this page for more info: http://api.jquery.com/jQuery.ajax/

Upvotes: 0

Jess
Jess

Reputation: 8700

You are approaching the problem in an odd way. Not to say it wouldn't work, just that you would have a hard time getting to. I would recommend using jquery's ajax with json.

Something like:

<div id="output"></div>

$(function ()
{
    //$.json('urltoRequestfrom?variable1=value1');
    $.post('/echo/json/',
           {json: '{"name":"test"}'},
           function (data)
           {
               $('#output').html(data["name"]); //first json object
           },'json');
});

Upvotes: 1

hypervisor666
hypervisor666

Reputation: 1275

Why would you want to do this?

jQuery does indeed have a load function where you can fetch a page fragment, which is an ajax call, just use AJAX to fetch the data dynamically whenever you want, javascript can be configured to handle the data fetched however and whenever you want.

Also include a better description of your objective, as what you have described is very unclear.

Thanks and good luck,

h

Upvotes: 1

Related Questions