Is it possible to write ColdFusion statement within Javascript? [duplicate] - javascript

Can I use ColdFusion tags in JavaScript? For example:
<script language="javascript" type="text/javascript">
function validateUser() {
var userName = document.getElementById("username");
<CFQUERY DATASOURCE="mydatasourcename" NAME="getUser">
select USER_ID,COUNT(*) from user u
where u.firstname=userName;
</CFQUERY>
<cfif getUser.recordCount EQ 0>
<!--- Show eroor message --->
<cfelse>
<!--- Assign userId to hidden field --->
document.getElementById("userid").value=#USER_ID#
</cfif>
}
</script>
<input type='textbox' name='username' id='username' onblur=validateUser()/>
<input type='hidden' name='userid' id='userid'/>
When the end user enters their username, I would like to check in a database if this username exists or not. If it exists, I have to keep the userid in the hiddenfield or else throw an error.
Am I doing this correctly? If it is wrong, could you suggest the correct way?

Long version: http://blog.adamcameron.me/2012/10/the-coldfusion-requestresponse-process.html
Short version: no, you're not doing it right.
Mid-sized StackOverflow-friendly version: CFML code runs on the server side of a request; JavaScript runs on the client browser. And to be clear: the ColdFusion server never communicates with the browser directly at all: there's a web server in between. The client browser requests a file, the web server is configured to pass .cfm requests to the ColdFusion server, and it runs its code, returning the resulting string (eg: an HTML web page) to the web server which then returns that to the browser. That HTML might include JavaScript (inline or as external requests) which the browser will then execute.
Hopefully from that you can see that there's no direct interaction between server-side code and client-side code.
You have two facilities at your disposal to get the two communicating asynchronously though. Firstly: CFML code writes out text, but that text can be JS which the browser then runs when it finally receives it. Something like:
<cfset msg ="G'day world">
<script>alert("<cfoutput>#msg#</cfoutput>");</script>
Once the CFML server has processed that, what gets sent back to the browser is:
<script>alert("G'day world");</script>
In this way server-side code data can be used in client-side process if the server-side code "writes out" the data as part of its response. The example above is very trivial and not a "good practice" way of going about this, but it demonstrates the technique.
If you need to use JS code on the client to communicate back with the server, your only (real) recourse is to make an AJAX request back to the server to pass it client-side information for further server-side processing and for the server to respond with something. It is outwith the scope of your question to explain how best to do this, but there is a tonne of information out there to do this.
CFML provides some "wizards" to write HTML and JS out for you to facilitate this, but on the whole this is a bad approach to achieving this end, so I will not recommend it. However I will point you to a project which offers HTML/JS/CSS solutions to the inbuilt CFML wizardry: https://github.com/cfjedimaster/ColdFusion-UI-the-Right-Way
Back to the short answer: no, you cannot do what you are setting out to do for very good reasons, but if you revise your approach, you can achieve the ends that you want.
What you need to look at is passing the form fields back to the server via AJAX (jQuery makes this very easy), and run your <cfquery> code in a separate request.
If you read that blog article I mention from the outset (discloure: I wrote it, but I wrote it specifically for situations like this), then you'll understand why.
If you get stuck when working on part of your solution: raise another question more focused on whatever part you are stuck on.

Related

Smarty Variable in Javascript

I need to print this variable:
{$array}
And i have this code:
<script type="text/javascript">
function write() {
writing = document.getElementById('box_user');
if(writing.innerHTML == ""){
writing.innerHTML = "{$array}";
}else{
writing.innerHTML = "";
}
}
</script>
When I click here, i dont get the result of the variable:
<td><button name="ver" onclick="write()"></td>
And the result must be here:
<div class="col-lg-12" id="box_user">
</div>
Content of variable:
while($array = mysqli_fetch_assoc($resultado)){
if($tabla1 == ""){
$tabla1 = "<table>
<thead>
<tr>
<td><strong>ID Formador</strong></td>
<td><strong>Nombre</strong></td>
<td><strong>Apellidos</strong></td>
<td><strong>Email</strong></td>
<td><strong>Teléfono</strong></td>
<td><strong>DNI</strong></td>
</tr>
<tr>
<td><strong>".$array['ofca_idFormador']."</strong></td>
<td><strong>".$array['daco_nombre']."</strong></td>
<td><strong>".$array['daco_apellido1']." ".$array['daco_appelido2']."</strong></td>
<td><strong>".$array['usrs_mail']."</strong></td>
<td><strong>".$array['daco_telefono']."</strong></td>
<td><strong>".$array['daco_dni']."</strong></td>
</tr>";
}else{
$tabla1 .= "<tr>
<td><strong>".$array['ofca_idFormador']."</strong></td>
<td><strong>".$array['daco_nombre']."</strong></td>
<td><strong>".$array['daco_apellido1']." ".$array['daco_appelido2']."</strong></td>
<td><strong>".$array['usrs_mail']."</strong></td>
<td><strong>".$array['daco_telefono']."</strong></td>
<td><strong>".$array['daco_dni']."</strong></td>
</tr>";
}
}
$tabla1 .= "</thead></table>";
I'm using a .tpl and all of controllers a model work great the problem is here.
I´m starting on smarty, this is my first project.
I'm not hugely familiar with Smarty, but I've done some PHP in my day, and I'll take a shot at an answer here. Forgive me if this answer is overly simplistic and sounds unnecessarily patronizing; I'm going to answer in a way that even a beginner could understand, since I don't know your skill level or familiarity with these concepts.
The main problem you're having has to do with the separation between the server and the client. PHP is a server-side language; JavaScript and HTML are client-side. The server is what hosts your website for the client, usually your web browser, to request and read.
The interaction usually goes something like this: your browser asks the server for a certain webpage, the server does some stuff to build that webpage up from the templates, and the server hands the completed webpage to your browser. From that point on, the server no longer has any access to your webpage, and server-side code won't do anything, because your browser doesn't know what it means, so if any server-side code is left as part of the webpage, it's just going to be rendered directly as text. Your browser does understand client-side code, however, and that will still work just fine.
Of course, sometimes you need information from the server after the page has loaded. The way your client-side code running in the browser gets new data from the server is generally through AJAX requests; essentially, the browser talks to the server again and asks for some data, the server again runs some server-side code to build up the data you're asking for, and it hands it back to the browser. This usually won't be in the form of another webpage, but will instead be in a data format like JSON or XML, which your client-side code can then process and use to add content to the page. But notice that the server-side code never touches the page; all it does is hand over some data that the client-side code can use to update the page.
If you're familiar with C and similar languages, think of PHP-style templates as preprocessor code. The preprocessor code can, in effect, add and remove sections of the C code at compile time, but once the build is complete, that preprocessor code doesn't exist anymore, and the preprocessor can't do anything at runtime; at that point it's all C. Similarly, PHP can build up client-side code, generate bits of HTML or JavaScript, etc., but once that page is handed off to the browser, PHP doesn't exist anymore as far as that page is concerned.
Based on the code I'm reading above, I think you have two options, depending on what you're trying to do. I can't quite tell whether you mean for that table code to be generated dynamically at runtime when the user requests it, based on some user input, or whether the table exists completely and is just waiting to be displayed.
If the table code already exists, I recommend moving it out of a PHP variable and into the page. If you don't want it to show immediately, you should use CSS to hide it initially and use that button click function to show it, something like this (assuming the Bootstrap .invisible class based on some other Bootstrap classes you used):
<div class="col-lg-12" id="box_user">
<div id="table-wrapper" class="invisible">{$tabla1}</div>
</div>
<script>
function write(){
document.getElementById('table-wrapper').classList.remove('invisible');
}
</script>
If you need to dynamically generate the table based on some user-generated info and MySQL queries, which it looks like you're using, then you have a little extra work to do. You need to look into how to set up a REST interface for your server, whether through PHP or something else, and you need to look into how to make AJAX calls. You should return data from the server as a JSON object, then convert that PHP code you're using to generate the table into a JavaScript function and pass in the JSON you get back.
Hope that helps! Please feel free to ask for any clarification you might need.

PHP - Insert to database without refresh page ( OOP )

I am trying to find a way how can I insert something to my MySQL database without refreshing the page and also don't make a security hole.
After some hours of trying and searching I have this:
<form name="form1" action="">
Enter Name <input type="text" name="t1" id="t1"></td> <br>
Enter City <input type="text" name="t2" id="t2"></td> <br>
<input type="button" name="button1" value="Insert to DB" onClick="aa()">
</form>
<div id="d1"></div>
<script type="text/javascript">
function aa()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "insert.php?name=" + document.getElementById("t1").value + "&city=" + document.getElementById("t2").value, false);
xmlhttp.send(null);
document.getElementById("d1").innerHTML=xmlhttp.responseText;;
}
</script>
Which is simple form, which call JS , and that JS redirect info to .php file where is SQL command for inserting things to database.
But I'm not sure if this is "secure" and also I would prefer to call some method which will insert (using MVC) or something like that.
Is here anybody who can give me some knowhow?
Your question is legitimate. A lot of websites are using this technique this day where a page communicates with a server without reloading the whole page, without sending full headers and reloading all resources. Is a very useful technique, pioneered by Microsoft some years ago and then adopted and supported by all browsers, with the advantage of being more user-friendly and faster. You can use your own code, like you did to create an AJAX request or use a library (like jQuery, DOJO, mootools, YUI, etc) that solve for you a lot of differences between browsers. In my opinion you should start by using a library as they have examples and will help you a lot at the beginning.
The infrastructure of an AJAX request is still the HTTP verbs: GET and POST mainly, used to get a new chunk of information or to save some input. This JavaScript part is like any other Javascript executed on clients side, in the client browser, which makes it insecure by default. The security rule is:
always check user input and distrust humans by default :) - filter it, sanitize it, do a thousand checks before trusting it to be saved in your database or before using it anywhere.
This you have to do it on PHP side. Again, you can, filter yourself or you can use libraries or MVC that can help you with that. Here is a little more tricky in my opinion to recommend something. Sometimes those come with a lot of extra information and may introduce more headaches.
Learn how the things work by experimenting with a JS library and a simple PHP script and later you can move from there.
What you want is called a 'ajax' request. If you google for that term you will find some interesting examples.
You might wanne consider using a library, for example jquery, which basicly abstracted it to a nice function
I guess that what you are asking for is security. As said before, if you don't want to reload the page your option is AJAX, but if your main issue is security, then you have to implement CSRF (Cross-Site Request Forgery). To avoid csrf, you should check this link.

javascript security: prevent user from calling function from console? [duplicate]

I allow my users to favorite an update or a forum topic.
So when a user tries to favorite one of these i will send via Ajax 2 things, the item_id(update or topic) as id(ex. 1321313213) and its type("update" or "topic") as string.
However lets say someones tries to favorite an update with the id untouched but the type is changed to "topic"(via firebug or whatever else)...
This should not procceed since this combination is not correct... how can i assure that the item_id being sent is an update or a topic since this ID might co-exist in both tables???
Current solution:
Create a hidden input element and add as value 5 random characters (a-zA-Z0-9) and md5 type name(update or topic)
like:
$random_str = $this->my_model->generateRandomString(5);
<input type="hidden" value="<?php echo $random_str.md5("update"); ?>" id="type" />
so when i try to validate the data to check if it is an update or topic i split the type on the first 5 characters and later and check if the later characters are md5 hashed are update or topic and continue validation
I would like some help in case this can be altered as well...
Your server side script (PHP) must always assume it's getting bogus data. Never rely solely on javascript to handle any sanitization / verification.
If your javascript can determine if the job should be "update" or "topic", I'm sure your PHP can do that as well. Probably using a few more DB queries or some such, but that's the price you've got to pay.
Your are looking at the problem from the wrong perspective. Especially from You server side (PHP) code.
Your server gets data. It gets data which is something like that: user (from session), id and type. Your server needs to ask a question: is it valid data? If it is -- save it to DB; If it is not -- do not save it to DB. It is that simple.
You can look from this perspective: Your client side code is just one way to communicate with Your server. Another way is using web browser + firebug. It is perfectly valid usage of Your server side application. And Your PHP code should not care how request reaches it.
So if Your current code does not allow You in Your PHP code feel comfortable and freely decide if is it update or topic creation than Your need to change Your server side code (and perhaps DB schema) as well.
Your current solution is not good, because if I know how to use firebug I would probably find out that "9d9b68ac2b1de18d3712096354b3c3a5" means "topic" and "3ac340832f29c11538fbe2d6f75e8bcc" means "update".
I think Your are trying to invent Your own CSRF protection. So go on Internet and read about it.

Comparison of simple User Regeistration by PHP and Javascript

A simple user registration may be completed by PHP (framework: Codeigniter,etc..) and Javascript.Following is simple flow:
PHP
A registration view with form input(user_name,e-mail,password)
post the data to an controller to validation
-Pass, redirect to a completion view
-Failed, go back to the registration view with some alert strings.
Javascript
A registration html with input text(user_name,e-mail,password)
Validation could be done by Javascript directly before submit; Alert strings could be
generated by Javscript. Even submission could be done by ajax. Then redirect to the
completion page.
I found myself code more javascript less PHP. Even the user registration could be done without the "form" tag,right? I am afraid of some parts I had miss or ignore.
Could someone gives me an simple comparison of good/bad parts about these two methods?
User registration details have to be stored on the server. You can use any language you like there, JavaScript (node.js is the current preferred way to achieve that), Perl (PSGI/Plack), Python (WGSI), C# (ASP.NET), PHP (mod_php), whatever. If you did it entirely with client side JavaScript, then the registration would exist only for a particular browser (which makes it rather pointless for almost anything on the WWW).
You can do a lot of things with client side JavaScript.
You can test if the data enter by the user conforms to the requirements you've set (such as "usernames contain only ascii alphanumeric characters").
You can't stop data that doesn't conform to those requirements being submitted to your server though - everything outside your server is beyond your control. Users can edit your pages in their browser as much as they wish. Client side validation is a convenience to the user (giving feedback without a server round trip and page reload), nothing more.
You can use Ajax instead of an HTML form … but there is no reason to do that. It just adds an unnecessary dependancy on JavaScript. That doesn't mean Ajax can't be useful, you could use it to ask the server if a username was already taken while the user is filling out the rest of the form.

gwt javascript checking php

i am using gwt.
i need to check some input data.
all checking functions are located in PHP server check.php
i am not using javascript checking executed from locally.
all i am doing is to send user input to server by ajax and validate in that place
and error message comes from server to client's gwt widget.
is it best approach??
i can do all checking from locally.but not doing.because server side is importent.
all checks must be resides in server so i am doing all checking from server.
if i do check locally and serverside two times ,then will it be best approach??
What you'll want to do is:
Use this account the next time you come back, or any of the others you've created, instead of creating an account each time you come to the site. Avoid this mess.
Create a .php page that accepts JSON-encoded data that you'd like to verify, and respond with some text like "OK" if it's valid. (I'm no PHP expert, but I'm sure there are plenty of them here)
Use GWT's RequestBuilder to send this data to the .php page, and call the RequestCallback's Response's getText() method. Check if the text is "OK" -- if so, the result is valid!
If you need more detail on any of the specifics, just let me know and I'll edit to clear things up.
Generally I agree with Jason (especially the with the first point :D).
I'd like to add that you should do validation on the client side first. Why? Because it allows you to weed out some obviously wrong inputs => less load on the server. But never accept the values from the client, just because your JS code said so - the general rule is to never trust the client side (because, well, it's the client side and the client can change the way your code works).
So in summary, I usually take these steps in my apps, they offer security and lower the load on your server, but may require a bit more work to write and maintain (especially if your client side and server side use different languages):
Validate input client side. If it doesn't pass, don't bother sending it to the server, just show an appropriate message.
If it does pass, send it to the server, but you must rerun the validation on the server side too.
If the server side validations report an error, send it back in some form (JSON with the error message and/or error code, set a HTTP response code, etc).

Categories

Resources