Including a php file dynamically with javascript and jquery - php

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.

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');
});

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

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/

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

Related

how to pass full page from php to jQuery. and send some data back

Is there any way i can load a page in php, pass it to jQuery , extract data then send that data back to php script.
see : How to find number of <ul> inside each div
this is lab experiment work. file is on my prof's personal site.
trying to do this using phpQuery but seem's not possible . so a possible approach is
as i mentioned above.
It sounds to me like there is one extra step in the process you have described. Unless there is some reason you specifically want your PHP to load the actual file and send it to your jQuery script you would be better off just loading the page directly with jQuery.
You could use the $.get() function to load the desired page.
Once you have the content, you could insert it into your DOM in a hidden element. Now you can use normal jQuery to extract/manipulate the data.
You might even be able to skip inserting the data into the DOM and just manipulate it as is.
Once completed, send the data back to PHP using $.post() or $.get()

How do you write a value returned by external javascript to a file using php?

I have a table with a button which onClick calls an external javascript file, which calculates some values and returns them to the table. I need to then write that value back to a file using PHP without leaving the current page. Is there any way to do this? I thought about trying onChange, but I wasn't sure how ot make that work with php since it's usually a javascript call.
PHP is executed on your server
the javascript file, even if external, is run on the client machine.
You can't use PHP on the client machine! You must use javascript to call a php script, stored in your server, that do what you need to.
You're on the good track, you need to use AJAX calls in your javascript.
don't use onclick, search for unobtrusive javascript;
you'd be using jQuery, so you can use its ajax handler;
find out a good reading about the whole topic, before going heads down on writing code.
This sounds like something you could solve by using AJAX. Basically you would communicate with your server in the background, send the data to it so it can process it. You send a separate request in the background which happens without reloading the page.
Please be aware of the distinction between the client (where the JavaScript is run) and the server (where PHP generated the page run by the client).
If you want to use jQuery, that library has some decent functions that makes it easier to implement cross-browser AJAX requests. However I would suggest first researching the topic.

Execute Javascript server side

I was interested in obfuscating my JS code, but I realized arround forums that it is useless. I would like to obfuscate my code anyway. So I was wondering, is that possible to execute JS code on server side (with an app in node.js for example), and just call via Ajax function with context (like dom, or something else), execute on server side, then give back result to page.
It could be very usefull for me, that could permit to just show basic JS functions, but not core of my app...
Perhaps a solution already exists, but I found nothing on Web...
EDIT :
I thought that with node.js, a solution was existing. I meant for example a simple JS function in client side like : call_func('function_name', context); that call a server side JS dispatcher function with ajax, that returns JS object containing results.
Perhaps I am dreaming ? :)
Thanks for your help.
You can either rewrite your calculations in PHP or if you need to use them dynamically/get access to the DOM, you can use AJAX to calculate on the server side using PHP and then recieve the ouput of the PHP script without reloading the page.
You can read about AJAX here (I would recommend using jQuery for it as it is much simpler than trying to understand HTTP requests):
http://api.jquery.com/jQuery.ajax/
While I agree that you should probably use a serverside language and get the information that you need from the dom via ajax, it is not true that you have to do that. You can simulate a dom on the server using e.g. jsdom which you will find here https://github.com/tmpvar/jsdom for nodejs. Similar packages exist for other languages.
That dispatch thingy you were dreaming about could be achieved using nowjs http://nowjs.com/.
I dont have experience with either tool, so I cannot comment on how well they work.
AJAX is the way to go. Send function name in xhr.send('func=myfunc').
First create a dummy div.
<div id="dummy"></div>
Then create a switch case in the js code and call the function:
switch(<?echo $_POST['func'];?>){
case 'myfunc':
document.getElementById("dummy").innerHTML=myfunc();
break;
}
Then just use xhr.responseText.

php: Get page contents with AJAX loaded

the page that i want to get from my php-script contains ajax. So when i do something like:
file_get_contents($url);
i receive just the contents with javascript.
is it possible to get the page with all ajax executed?
To run javascript contents from javascript coming in through AJAX, you would have to run eval on the script, but you better make absolutely sure the javascript isn't "user-input", otherwise using that, you could have some serious security issues on your hands.
It's also not good practice to use eval - better to load a js file when you pull the contents through AJAX and have your AJAX success activate a function in the js file.

Does php load BEFORE the 'html body'?

Difficult to explain this Question, but im currently passing variables in a php page to some html hidden inputs.
Im fetching those values from the hidden inputs with a javascript function. This function gets called like this:
<body onload="function();">
It works on my system now, but is there any chance that the value passed from php might not get through because body has called the function BEFORE the php code sets the input type hidden?
Thanks
You have may have mixed up which part does what.
PHP generates the HTML page on the server side. When the HTML page arrives at the browser, PHP has done its job. There is no way for PHP to do something after it has rendered the HTML.
Javascript is executed in the user's browser after the page has been generated and loaded. (Or during; as theraccoonbear points out, Javasript can run in the browser before the page has loaded completely.)
A Javascript command can not communicate with the PHP script rendering the page, because when Javascript comes into play, PHP is already gone.
So the answer to your question is: No, the JS function can not execute before PHP is done. As several commentators point out, that is not entirely true. A Javascript could come into action before the input HTML elements have been rendered. In your example however, the Javascript triggers only when the document is completely loaded. In that constellation, the answer is no, it can't happen.
That shouldn't be an issue, as you are using the body's onload property, which will ensure the dom and all images etc have loaded.
Using jQuery to it like below would be better in my opinion, fires as soon as the dom is ready, rather than waiting for all images etc.
$(document).ready(function() {
// do stuff here
});
This is also easily done from an external JS file if required, which helps you logically separate your code.

Categories