Smarty Variable in Javascript - 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.

Related

How to get the values of session using js

I want to know if the user has logged in or not and then display different elements of the navigation based on the username (login by email and password Not username). However, I have no idea how to deal with session. If php and html is separated in two documents, how can I store the required values using session in php document and then get them using javascript in html document? Or should I use cookies instead?
There are a several approaches to do this.
1) You can make a PHP file which will format your $_SESSION data, and all the other data you want as a JSON string (json_encode function in PHP lang). Then use echo to return it. Then use an AJAX request to get this file from javascript or JQuery, and you will receive the data you want. That's a bad approach for this purpose, from my point of view, because after loading the page you send another request to receive a static data, which will not change on the page like email or username.
2) Better approach: PHP is preprocessor hypertext. You can make an php file and write html tags in it, with php output(example: <div><?=$_SESSION['email']?></div>). Search for more info in google ("php inside html").
3) Much better. In modern web programming world its a mistake to use php inside html because you should think not only about how to make something work, you should think how you will maintain it after 3, 6, 12 months later, too. If you use just php inside html in a big project, then, with time, you realize that your code is hard to read and looks ugly. There are plugins that can make your view more readable and maintainable (Twig, Blade, Volt and others). I recommend you use one of them.
The session is a server side thing, you cannot access it using javascript. You can write an Http handler (that will share the sessionid if any) and return the value from there using AJAX

Simple php script fetching visitor details like screen resolution, country of origin etc

First a little bit about me because it might help:
I am NOT a professional coder, I write HTML and CSS by hand with notepad++ because i like the lightweight and effective code + I have total control and clue of what is going on in my files/website.
I don't like WP. Its too much hassle and yes i know it's "easier" but since I know nothing about php, except that it's a server side language, it's not easier for me to get the look of the website that I want with it. (recently I found out I can INCLUDE a part(s).html in actual.html and compose actual.html - not up for that right now as it makes a new connection for each part.html (when i get to more complex web-developing, as my sites are static, etc...)) Tried multiple times, ended up deleting everything and writing my own code from scratch. I don't like to learn the (php) code from WP editing (extremely time-consuming and messy), I prefer learning it by using the code when i need it. That's how i remember and learn. That's how I learned C#.
I like one-file type of web pages as they are pretty much static. Any pics that i might use i DON'T create any links, I convert them in base64 and paste the code where i need it. So as minimalistic as possible with fewer requests as possible with least kb as possible - but resemble WP by look and behavior (responsivness).
I reserve one request for style.css and one for favicon.ico; #1 it's neater, #2 can't be base64-ed nor CSS loaded.
Anyway, a php contact form that I used in one of my sites was working perfectly, with just contact.php file on the server and a little bit of js in html. Therefore i ASSUME that fetching user data such as IP, time of access, screen resolution and OS would be easy similarly as the contact form was.
What I would like to know is next:
fetch device.useragent + device.resolution + time + IP;
write fetched to log.txt
Then i ftp the log.txt to my pc and investigate.
Thank you for reading and considering to help :)
The user agent, time, and IP address can be stored in variables as follows:
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$time = date('Y-m-d H:i:s');
$ip = $_SERVER['REMOTE_ADDR'];
For resolution, you'd have to determine it with JavaScript and send it to the server with an AJAX request or as part of the request body. All of this can then be written to a log.txt file using file_put_contents('path/to/log.txt', $data);.
Note, that there are usually simpler ways of achieving this if using a framework (e.g. Symfony, Laravel, Zend), or there may even be a plugin for your CMS of choice.
Check this post, PHP's get_browser, and also this post is very helpful. For the resolution, like Sheraz said, you need JS or any JS library that can read the device resolution. If you want to use jQuery, check this post. To fetch user time of access, you can create a $_SESSION variable and use time. For the ip, check this. And for file handling, fopen, file_get_contents, file_put_contents and fclose will help you.

how to update content automatically without reloading webpage using php/ajax?

I'm trying to create an auction tool using PHP. The problem I'm having (and I appreciate its a basic one but I need clarification) is that I don't understand how to update the "auction price" automatically on each users screen without them having to take any action or without causing a full reload of the page.
So far I understand that Ajax is used to do this but if anyone could point me in the right direction or to any useful materials. My plan for my project so far is to use PHP and JavaScript so any solution would need to be compatible with these languages.
Note: I'm using a MySQL database.
Ther question you asked has so much possible answers, they could fill a whole book.
The simplest way to do this is to make an ajax call every few seconds using a combination of the setInterval() function and AJAX calls. You basically make an AJAX request every few seconds:
setInterval(function(){
$.get( "anyChanges.php", function( data ) {
//do something with the returned data. Maybe update a table or something
});
}, 3000);
On server side anyChanges.php returns some data immediately, like confirmation that something has changed and the new data.
Long polling is how Google and others do it. It's the same as the example above. The difference is on the server side. anyChanges.php would not return immediately, the script would keep the connection open until there is some new changes and return them. If you use long polling, you usually set the interval to longer, for example 30 seconds.
The best way to do it in my opinion, are WEB Sockets. It is a very new technology. With web sockets you can create a two-way connection to the server. That means that the server could simply send data to the clients without them having to ask for new data every few seconds. In PHP it's a little difficult to use web sockets (Or so I heard), but you could give it a shot. If you choose web sockets, try to learn about them first:
tutsplus tutorial
This library will be helpfull:
socketo.me
Php/Ajax example:
In this example you have index.html and record_count.php files
Here is the Code:
index.html contains the html code and javascript call to load record_count.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('record_count.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<body>
<div id="load_tweets"> </div>
</body>
and record_count.php has the php code
<?php
echo "some code or variable here";
?>
you can change the javascript interval to suit your needs
I'll leave you the blog link as a reference: 9lessons
As I making interactive displays, which must switch pages instantly, then I create pages without refreshing.
My approach is something like that:
I have one index.html with all structure (pages) with all necessary html tags.
javascript/typescript loads json from CMS (Kirby for example), which has all information about texts and image links.
when json is loaded now I just need to switch between pages by showing/hiding or creating/removing html elements. And all data and texts are loaded by javascript.
There is some cons, which can be fixed, for example link for each page in address bar. In that case You need to add history management and change url in address bar on page switch.

get access to database from javascript

I am getting records from database in my HTML
<g:each in="${index}">
${""+it.indexDate+""+it.value }
</g:each>
It's working fine, but I want to use this record below in my javascript:
I want to do some thing like this
<SCRIPT LANGUAGE="JavaScript">
if(it.value>10){
alert("yes")
}
Is there a way I can do that?
Apparently you want to do exactly the same as what is described in this question.
Trying to access your database directly Javascript might be feasible but it is never a good idea.
In fact, the Javascript runs on the client side, and you don't want your clients to be able to mess up with your data. I would highly recommend using Ajax. That is to say, be able to asynchronously call the server side (PHP or any other server-side language you use) from the client side to request what you need from the database.

To build a `Delete` -button efficiently with JavaScript / PHP

Which of the following code is better in building a delete -action for removing a question?
1 My code
<a href='index.php?delete_post=777>delete</a>
2 Stack Overflow's code
<a id="delete_post_777>">delete</a>
I do not understand completely how Stack Overflow's delete -button works, since it points to no URL.
The id apparently can only be used by CSS and JavaScript.
Stack Overflow apparently uses JavaScript for the action.
How can you put start the delete -action based on the content of CSS -file by JavaScript?
How can you start a SQL delete -command by JavaScript? I know how you can do that by PHP, but not by JavaScript.
Your method is not safe as a user agent could inadvertently crawl the link and delete the post without user intervention. Googlebot might do that, for instance, or the user's browser might pre-fetch pages to speed up response time.
From RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1
9.1.1 Safe Methods
Implementors should be aware that the
software represents the user in their
interactions over the Internet, and
should be careful to allow the user to
be aware of any actions they might
take which may have an unexpected
significance to themselves or others.
In particular, the convention has been
established that the GET and HEAD
methods SHOULD NOT have the
significance of taking an action other
than retrieval. These methods ought to
be considered "safe". This allows user
agents to represent other methods,
such as POST, PUT and DELETE, in a
special way, so that the user is made
aware of the fact that a possibly
unsafe action is being requested.
Naturally, it is not possible to
ensure that the server does not
generate side-effects as a result of
performing a GET request; in fact,
some dynamic resources consider that a
feature. The important distinction
here is that the user did not request
the side-effects, so therefore cannot
be held accountable for them.
The right way to do this is to either submit a form via POST using a button, or use JavaScript to do the deletion. The JavaScript could submit a hidden form, causing the entire page to be reloaded, or it could use Ajax to do the deletion without reloading the page. Either way, the important point is to avoid having bare links in your page that might inadvertantly be triggered by an unaware user agent.
Bind a click event on the anchor which start with "delete_post_" and use that to start an Ajax request.
$("a[id^='delete_post_']").click(function(e){
e.preventDefault(); // to prevent the browser from following the link when clicked
var id = parseInt($(this).attr("id").replace("delete_post_", ""));
// this executes delete.php?questionID=5342, when id contains 5342
$.post("delete.php", { questionID: id },
function(data){
alert("Output of the delete.php page: " + data);
});
});
//UPDATE
With the above $.post(), JavaScript code calls a page like delete.php?id=3425 in the background. If delete.php contains any output it will be available to you in the data variable.
This is using jQuery. Read all about it at http://docs.jquery.com/How_jQuery_Works.
The url you are looking for is in the js code. Personally I would have an id that identifies each <a> tag with a specific post, comment... or whatever, and then have a class="delete_something" on each one, this then posts to the correct place using javascript.
Like so:
Delete
<script type="text/javascript">
jQuery('a.delete_post').live('click', function(){
jQuery.post('delete.php', {id: jQuery(this).attr('id')}, function(data){
//do something with the data returned
})
});
</script>
You're quite correct that absent an href="..." attribute, the link would not work without JavaScript.
Generally, what that JavaScript does is use AJAX to contact the server: that's Asynchronous JavaScript and XML. It contacts a server, just as you would by visiting a page directly, but does so in the background, without changing what page the browser is showing.
That server-side page can then do whatever processing you require. In either case, it's PHP doing the work, not JavaScript.
The primary difference when talking about efficiency is that in a traditional model, where you POST a form to a PHP page, after finishing the request you must render an entire page as the "result," complete with the <head>, and with all the visible page content.
However, when you're doing a background request with AJAX, the visitor never sees the result. In fact, it's usually not even a human-readable result. In this model, you only need to transfer the new information that JavaScript can use to change the page.
This is why AJAX is usually seen as being "more efficient" than the traditional model: less data needs to travel back and forth, and the browser (typically) needs to do less work in order to show the data as part of the page. In your "delete" example, the only communication is "delete=777" and then perhaps "success=true" (to simplify only slightly) — a tiny amount of information to communicate for such a big effect!
It all depends on how your application is built, what happens at Stack Overflow is that the delete link click is caught by JavaScript and an Ajax request is being made to delete the post.
You can use a JavaScript library to easily catch clicks on all elements that match your selector rule(s).
Then you can use Ajax to send a request to the PHP script to do the SQL work.
On a side note, ideally you would not use GET for deleting entries, but rather POST, but that's another story.

Categories

Resources