Is it possible to get jQuery function in a JSON response? - php

I have a form which i'm sending with jQuery post function to a php script.
The in the php script i do some checkings and send back a response with a formate like so:
$output = json_encode(array('type'=>'error', 'text' => 'your id is wrong!'));
die($output);
in the page where i have the form i can use a simple way to fire some functions based on the response. for example:
if(response.type == 'error'){
output = '<div class="clienConError">'+response.text+'</div>';
$(".results").hide().html(output).slideDown();
}
which means if it is the response is set as error type one do this and that...
My question is:
Is it possible to send back a jQuery function? so instead of saying: if it's a response set as error type do this. i say never mind what response is it, just do what the response tell you (for example hide some element, inject some html some where and so on... all kinds of jQuery functions).
If it is possible it will give me a few advantages. one of them is the ability to actually hide some jQuery functions (in the php script).

Although this is generally not recommended, it is possible to return JavaScript code from a PHP script, preferably with the appropriate Content-Type: text/javascript header.
At client side, you may execute the generated code using eval or injecting it in the page via a newly created <script> tag.
Dynamic scripts are discouraged for several reasons:
Harder to maintain: the generated code is –by essence– not static, and thus you can never see and edit the whole code as with a static file.
At best sloppy from the security point of view: allowing execution of arbitrary code is never a good idea, and attackers will more than certainly try to leverage this to perform client side attacks such as XSS.
Not friendly towards optimizers: contrary to a whole static script which can be parsed and optimized as soon as the file has finished loading, multiple fragmented bits of script cannot benefit from optimization.
Moreover, attempting to hide client code is a battle already lost. If the code is executed client side, then it is visible client side, period. Any user, and I insist, any user, can open the F12 debugger of their browser and place breakpoints or use step-by-step mode. More savvy users might overwrite the eval function or hook the beforescriptexecute event to inspect what’s going on. And there are even more ways.
The best you can do is obfuscate your code, with possible loss in performance and complexification of your workflow.

The only way you could really do this is by returning a javascript expression in text (wrapped in double quotes) in a JSON object. You would then need to eval() the response which isn't great for a variety of reasons - injection, performance, debugging.
I'd suggest against this approach anyway as you are overlapping the boundaries of what a client and server should be doing - tightly coupling both layers.

It is possible using eval() but it is not recommended due to performance and security reason. eval() executes the argument passed to it. So you can send the jquery function as a string and pass it to eval() to execute it on client side.
Sample Code:
var command= 'var output = \'<div class="clienConError">Here is the response</div>\';$(".results").hide().html(output).slideDown();'
eval(command);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='results'></div>

Related

Execute a javascript function from PHP and return the response

I am trying to execute a javascript function from a PHP script by sending a variable over to my javascript function and then it will return the response. I want the PHP script to only echo out the response from the javascript function, so when a client views the source code of my php file, he ONLY sees the response from the javascript function and not the javascript source code.
for example,
I have a javascript function called validate(), and a PHP file called check.php. The client calls the function using the GET method like so,
www.myserver.com/check.php?value=test
I then want check.php to send the variable $value over to my javascript function validate(), to perform the following,
response=validate($value)
then the javascript to return the value response to my PHP script and store it within a variable $response, and then it will echo $response. So when I view the source, I will only see the contents within the variable answer.
I can't find a simple way to do this :S. If I use AJAX I will need to use a div within HTML, but it's important that ONLY the contents of $response is displayed within the source code?
Could someone point me into what PHP functions I should be using ? Thank you!
PHP normally runs server-side, and Javascript normally runs client side (in the browser).
In the normal model, the client makes requests to the server, and the server responds. In this case it is not possible for the PHP code to "invoke" the Javascript function directly.
So what is the solution to your problem?
In order of preference:
The first, best option is to re-architect so that you do not need to call the javascript validate() function from within PHP. For example, port the Javascript logic to PHP.
If you cannot port, run Javascript on the server side. Node.js runs on server-side on Linux and Windows; if you have Windows/IIS, the easier option is to serve Javascript via ASP classic, which, yes, is still available on current Windows Servers. The PHP program can simply request a local Javascript resource probably via curl; the server invokes the logic and returns the result. In the general case the Javascript need not run on the same server.
Finally, if that's not an option, you could have the browser execute the validate() on behalf of the server. The PHP can emit the validation function, in a javascript script block, to the browser. PHP can also emit the thing that needs to be validated - a data packet, or whatever it is. The browser can then validate() on that object, and post a message to PHP via AJAX to report the result. But, there's a security issue here - keep in mind that the client is outside of your control, so there's a possibility that someone will subvert the client-side validation logic and cause the client to report false results to the PHP server. You cannot count on tihis.
Therefore you'd need to embed some sort of data integrity check in the transaction - some way that you could insure that the client-side javascript has not been modified. This will be hard.
You shouldn't be suing any functions :P
However, while it is a seemingly horrible way to do a validation, you could do the following:
Have the javascript output to the HTML file. (Put it somewhere where it will be easy to find)
Use fopen to open a URL with your parameters in the URL that will be picked up by the js function.
Have your PHP function parse the HTML file (that you used fopen to get) for output and search for the specific output you want.
Really though, you should just do the validation in the PHP script itself. Much safer, much easier and much easier to work with later if you want to change something.

Is a good idea use template function in my site that retrieve HTML generated with PHP Smarty and display with ajax response?

My PHP framework
public static function insertAction(){
.......
\MVCApplication::getSmarty()->display('common/inserted.tpl');
}
Show to user using Ajax response: (JQuery)
success: function(response){
$("body").html(response);
}
I want to make a site where all actions don't refresh the page (i.e., I want a dynamic site with just one page index.php).
My question is about security! I've read some articles on the web about the concern around script injection and my fear is that any malicious guy intercepts the response from the server and adds bad code to my server response! How do I improve my framework security?
(Eventually I will need execute script in my .tpl smarty templates and this will be outputted to ajax response too...)
Depends on whose security you're are talking about, the webserver or the client.
From what you have listed in the code, the server only sends data to the AJAX client, so it is not susceptible to a script injection attack since it is not acting on received scripts. (Although it is probably parsing a GET/POST response, but that is a different topic)
The fact that you use smarty doesn't make a difference with security, it is only a templating tool.
Javascript on the client is inherently insecure. If you're that worried about script injections coming back to the client, don't use javascript. As an alternative, you can try to strip any of the returned AJAX data to remove HTML or embedded scripts.
use something like: var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
from: http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/

Building web pages on the server-side or client-side?

I've always wondered how to decide on choosing between using server-side code versus client-side code to build HTML pages. I'll use a very simple php vs javascript/jquery example to further explain my question. Your advice and comment is very much appreciated.
Say I'm about to present a web page to a user to select a type of report in my web page. Which makes more sense?
For server-side creation, I'd do this:
<div id="reportChoices">
<?php
// filename: reportScreen.php
// just for the sake of simplicity, say a database returns the following rows
// that indicates the type of reports that are available:
$results = array(
array("htmlID"=>"battingaverage", "htmlLabel"=>"Batting AVG report"),
array("htmlID"=>"homeruntotals", "htmlLabel"=>"Home Run Totals report"),
);
foreach ($results AS $data)
echo "<input type='radio' name='reportType' value='{$data['htmlID']}'/>{$data['htmlLabel']}";
?>
</div>
Using client-side code, I'd get the javascript to build the page like the following:
<!-- filename: reportScreen.html -->
<div id="reportChoices">
</div>
<!-- I could put this in the document.ready handler, of course -->
<script type="text/javascript">
$.getJSON("rt.php", {}, function(data) {
var mainDiv = $("#reportChoices");
$.each(data, function(idx, jsonData) {
var newInput = $(document.createElement('input'));
newInput
.attr("type", "radio")
.attr("name", "reportType")
.attr("value", jsonData["htmlID"])
mainDiv.append(newInput).append(jsonData["htmlLabel"]);
});
};
</script>
All I would need on the server is a data dump php script such as:
<?php
// filename: rt.php
// again, let's assume something like this was returned from the db regarding available report types
$results = array(
array("htmlID"=>"battingaverage", "htmlLabel"=>"Batting AVG report"),
array("htmlID"=>"homeruntotals", "htmlLabel"=>"Home Run Totals report"),
);
echo json_encode($results);
?>
This is a very simple example, but from this, I see pros and cons in different area.
1 - The server-side solution has the advantage of being able to hide most of the actual programming logic behind how everything is built. When the user looks at the page source, all they see is the already-built web page. In other words, the client-side solution gives away all your source code and programming logic on how certain things are built. But you could use a minifier to make your source look more cryptic.
2 - The client-side solution transfers the "resource load" onto the client system (i.e. the browser needs to use the client's computer resources to build most of the page) whereas the server side solution bogs down, well, the server.
3 - The client-side solution is probably more elegant when it comes to maintainability and readability. But then again, I could have used php libraries that modularize HTML controls and make it a lot more readable.
Any comments? Thanks in advance.
Con (client solution): The client-side solution relies on the client to execute your code properly. As you have no control over what client system will execute your code, it's much harder to ensure it will consistently give the same results as the server-side solution.
This particular problem doesn't really seem to need a client-side solution, does it? I'd stick with the server-side solution. The only extra work there is a foreach loop with one echo and that's not really so resource heavy is it (unless you've profiled it and know that it IS)? And the resulting code is all in one place and simpler.
I'm sceptical that moving the report generation on to the client side really saves any resources - remember that it's still doing an HTTP request back to your (?) server, so the database processing still gets done.
Also, giving away your database schema on the client side could be a recipe for database attacks.
Perhaps you should use a model-view-controller pattern to separate the business logic from the presentation on the server? At least this keeps all the code in one place but still lets you logically separate the components. Look at something like Zend Framework if this sounds useful to you.
Typically, it's best not to depend on Javascript being enabled on the client. In addition, your page will not be crawled by most search engines. You also expose information about your server/server-side code (unless you explicitly abstract it).
If you want to transform data into the view, you might want to take a look at XSLT. Another thing to read up on if you have not already, is progressive enhancement.
http://alistapart.com/articles/understandingprogressiveenhancement/
In the first client-side solution you presented, it's actually less efficient because there's an extra HTTP request. And the second one is possibly not very efficient as well, in that all the data must be processed with json_encode.
However, if what you're working on is a rich web application that depends on Javascript, I see no problem with doing everything with Javascript if you want to.
You can maintain a better separation of concerns by building it on the client side, but that can come at a cost of user experience if there is a lot to load (plus you have to consider what FrustratedWithForms mentioned). To me it's easier to build it on the server side, which means that becomes a more desirable option if you are on a strict timeline, but decide based on your skill set.

what is safe way to send php data to js?

I want to know what is the safe method to send php data to js. I found by search to start php tags in js and pass data by this way.
var jsVar = "<"+"?php echo $phpVar;"+"?"+">";
But it seems a dangerous way to pass data exposing threats. I want to know whats alternative way to do same that is safe.
I'm not entirely sure what you mean by "safe", but if I understand your question correctly, you can inject data from PHP directly into your JavaScript using json_encode:
var jsVar = <?php echo json_encode($phpVar) ?>;
If all you want to do is to inject actual PHP source code into your script, then just print it as a string:
var jsVar = "<?php echo '<?php echo $phpVar ?>' ?>";
I can't imagine this is what you mean though, as I can't think of a reason for wanting to do this :)
I want to know whats alternative way to do same that is safe.
I'm not sure what you mean by "safe", but you have to assume that any data you send to the client's browser can and will be viewed by a sufficiently-motivated user. You can secure the data from prying eyes in transit (by using SSL, e.g., https), but the client user's browser needs to be able to read the data, which means the client user can too.
You can raise the bar slightly (for instance, by obfuscating the data you embed in the page, by supplying it only in response to an Ajax call, etc.), but with today's 'net and web tools (which are increasingly just embedded in browsers) a sufficiently-motivated user will get around the precautions you take (by stepping through your code and looking at the variable you store the de-obfuscated data or the data from the Ajax response in, for instance).
If you want to raise the bar further, you can require a plug-in like Flash or Java and send obfuscated (or even encrypted) data to your flash app / Java applet and de-obfuscate / decrypt it within the app / applet. But that just raises the bar to the level of someone with debugging tools for Flash or Java.
Probably not worth the bother, I bet you have better things to do. :-)
If you don't want the user to see the data in question, don't send it to them, keep it on your server where it's safe and have the browser ask for only the information it's actually allowed to show the user.
json_encode is the best way to sent back.
echo json_encode($phpVar)
If its your data coming from your database this is pretty safe.
The problem occurs when you are storing and re-displaying data entered by the user. In which case you need to ensure that there is no possibility of executabe javascript being embedded in the data. Removing or escaping '"{}();+-/* and thier hex equvalents should do it.
You could use json_encode as suggested in answer this

Using Hidden Iframes to run PHP scripts - good? bad? opinions?

I am a little bit new to the PHP/MYSQL arena, and had an idea to be able to interact with my Database by using a hidden Iframe to run PHP pages in the background(iframe) on events without having to leave the current page?
Good? Bad? Common Practice? Opinions?
This is most of the time bad, but sometimes inevitable.
The common practice to do it is to use AJAX, it's so common that even W3School has an article about it.
The advantages of using AJAX over IFrame is that AJAX can be multi-threaded. You can send several requests in a row, which is more troublesome to implement with IFrames. Moreover, AJAX supports status code so you can detect errors, where with IFrames you'd have to rely on scraping the page's HTML and hope you've determined the correct status by looking at the error page's HTML code.
AJAX is more JavaScript idiomatic and event driven, which means your callback will get notified automatically when there is a response. With IFrame you'd have to setTimeout() and keep polling the IFrame for a response, which may break easily.
IFrame is sometimes inevitable in cases like where you want to upload a file without leaving the current page. But that's probably not your scope since you mentioned only database interactions.
Learn to use XMLHttpRequest, which is the foundation of AJAX. After you've become familiar with that, try making it fun by using a JavaScript framework such as jQuery, Dojo, etc.
I'd guess something is supposed to happen when your database does something, right? I.e. your page should give some sort of feedback, maybe update a number or some text.
So you're going to use Javascript anyway. In that case, skip the iframe and just send off AJAX requests.
This is commonly accomplished using AJAX. The jQuery javascript library makes this easy
I don't think using iframes is a good way to accomplish this. You would still need javascript enabled to change the location of the iframe, and if javascript is available, why not just use AJAX?
If you use the iframe, you wouldn't be able to receive a response from the server in any meaningful way without doing a lot of workarounds. For example -- using jQuery, you could submit some information to the server with a single function call, and then when that request completes, a callback function can be invoked with response information from the server:
$.post("ajax.php", { var1: "data", var2: "moredata" },
function(data){
alert("Server says: " + data);
});
In this example, when the request completes, an alert box appears with the output of ajax.php.
With an iframe, you might do something like change the location of the iframe to server.com/iframe.php?var=data&var2=moredata&var3=moredata, then wait for a bit, and grab the contents of the iframe (if this is even possible) and do something with that.
Not to mention, when you run into problems doing this, you'll probably ask for advice on SO. and each time, people will probably say "drop that and use jQuery!" :) may as well skip all the pain and suffering and do it the Right Way to begin with
The hidden iframe method was used before the adoption of XMLHttpRequest api (Maybe you have heard of it as Ajax).
Years ago I was using a former implementation using rslite but nowadays this technique has, to me, just an historical value.
You can get directions on using Ajax techniques in plain javascript at http://www.xul.fr/en-xml-ajax.html or, better, you can choose to use a common library, jquery or mootools among others, to deal with the different implementations in different browser.

Categories