dynamically updating html page in rails3 - javascript

I have an html text-area which uses ajax-autocomplete where it populates the dropdown as i start typing. When I select an entry from the dropdown it will set some field to the id of that object.
Once I get the id of the object is there a way I could do something like this?
<% #myObjects.find(1) do |myObj| %>
<h1><%= myObj.attr1 %><h1>
<h2><%= myObj.attr1 %><h2>
<% end %>
Right now, when I get the id of the object I am using jquery's attr() function to set the values which exposes my javascript logic which I don't really like. Is there a way I can activate the field? Or, hide the fields and where the id is populated show the field and let ruby do its magic with myObjects.find?
UPDATE:
Right now the way I am populating the fields in the view like this:
$(function() {
// Executes a callback detecting changes with a frequency of 1 second
$("#id_element_placeholder").observe_field(1, function(){
//alert('Change observed! new value: ' + this.value );
$.ajax({
type: "GET",
dataType: "json",
url: "/myobj/get/" + this.value,
success: function(data){
$('#last_name').attr('value', data.myobj.last_name);
$('#first_name').attr('value', data.myobj.first_name);
}
});
});
});
Is there a way around exposing the above javascript code?

There is nothing wrong with your javascript and you seem to be confused between client side and server side technologies. Ruby cannot directly update your page once it has been sent to your user. It is on your web server and your page has been sent to the clients browser. It can however send javascript in response to a further request made by your application from the clients browser to do exactly that, just as you are doing.
You could send a new html snippet to your browser and replace the entire node but really there is no point. What you are doing is the same as everybody else who uses javascript.

Answer is simple, you can't :)
What you are doing is ok, using AJAX for such things is the way to have such a things done.
If you are concerned about exposures don't look at javascript, look at what the server side code allow a user to do with get/post methods ;)

Related

How to use JS to display images from database

So I made a website that displays FPS information stored in a mysql database. For each second of gameplay I have a pair of number(fps)-image(screenshot).
I display the numbers in a line chart made with JavaScript. The behaviour desired is when I click on a bullet in the chart, the screenshot for that particular second is displayed in a div on the page.
I have to mention that the screenshots are stored in the database and they are very low in size. I display then using PHP like this:
$query = "SELECT `image` FROM `logs` WHERE `session_id`=".$_GET['session']." AND `second`=".$second;
$sth = $mysqli->query($query);
$result=mysqli_fetch_array($sth);
if (!empty($result))
echo ' <img id="screen" src="data:image/jpg;base64,'.base64_encode($result['image']).'"/>';
The method I'm using now is when I click on a bullet in the chart (action recorded in JS), I send it as a GET parameter and read it with PHP afterwards, like this:
window.location.href = url + "?second=" + second;
This method obviously will refresh my page. The problem is, the chart I made also has a zoom/scroll option and that resets whenever the page is refreshed, making the experience very bad for the user.
Is there any method to display the screenshots without refreshing the page, for this particular case (where I have to query the database for each click/picture)? Maybe there is a better way of approaching this problem?
Thanks.
I think you've got 2 solutions which are Ajax or Websocket depending your needs.
AJAX
Ajax permit to asynchronously, only when you need, call the server and get datas from an URL which could be a webservice or PHP page... Perhaps, it's the better solution in your case.
To make it easy, you can use JQuery library by donwloading the script and insert it in your HTML :
<script src="jquery-3.0.0.min.js"></script>
To call the server, using JQuery :
$.ajax({
url: url + "/yourphppage.php",
data: "parameter=" + yourOptionelParameter,
async: false,
success: function(data) {
refreshYourChart(data);
},
error: function() {
alert("Your error");
},
contentType: 'charset=utf-8'
});
Or if your prefer pure javascript.
Now, you just have to work on the presentation of your data, on the server side. It could be what you want HTML, TXT, JSON, XML...
Websocket
Websocket is like a permanent tunnel opened between your server and the client. Each side can ask or send datas in real time.
It seems to be a library server side :
http://socketo.me/
And client side, it's very easy :
Nice documentation on mozilla website
Hope it helps. Good luck.
To change a picture source, as I see the easiest way is using an ajax call, so you can send any kind of parameters to your server, and in return your will get your new picture source.
$.get('urlToYourServer.com?parameter=1', function(data){
$('#img').attr('src', data.imgSrc);
})

How to store HTML attributes that trigger javascript commands properly to mysql using ajax?

I have problems when saving html5 data from a page into mysql through an ajax request and trying to retrieve it back with ajax. HTML attributes that trigger some javascript such as
<onload> or <iframe> will be stored as <on<x>load> and <if<x>rame> in the database and thus screw up the page when loading it.
Here's a short description of what I am trying to accomplish: I want registered users to have the ability to highlight text on my site and get the highlighted text back after refreshing the page, relogging etc.
What I have done so far: I implemented a javascript highlight library on my server that allows users to highlight text. That works well.
By clicking a button, those data are then saved into mysql through jquery ajax post. See specific code here:
Javascript
$(document).ready(function() {
//saves highlighted data in var "highlighted"
$('#savehighlights').click(function() {
var highlighted = $('.tabcontent.content1').html();
//send data to server
$.ajax({
url: 'highlight.php',
type: 'POST',
data: {highlighted: highlighted},
dataType: 'html',
success: function(result) {
console.log(result);
}
});
});
Saving the data to mysql works generally, but it looks as if certain commands are disabled through the process (e.g. onload becomes on<x>load5). The data are stored in the database as longtext and utf8_bin. I also tried blob, but problem remains. I also tried different dataTypes with Ajax such as 'text' and 'script'. 'Text' causes the same problem and 'script doesn't work at all. I also tried the ajax .serialize function, but no luck either.
I really don't know what to do about it and I am not sure what is causing the problem, Ajax or mysql? I was searching the web for an answer, including many articles in stackoverflow (which normally always give me the answer), but this time I am stuck. Either I don't know enough about it to look for the right question, or I just don't have any luck this time. So, any help would be greatly appreciated.
I was requested to add some more information. Here it is:
I am actually doing this on my local server (localhost) with XAMP, so security issues should not be a problem, right? If it is of any help, I am doing this in a Tiki Wiki CMS. The php script that is called through ajax (highlight.php) is the following:
require_once ('tiki-setup.php');
include_once ('lib/highlights/highlightslib.php');
$highlighted = $_POST['highlighted'];
$highlightslib->save_highlights($user, $highlighted);
The highlightslib library is here:
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
class HighlightsLib extends TikiLib
{
function save_highlights($user, $highlighted) {
$saveHighlights = $this->table('tiki_user_highlights');
$saveHighlights->insert
(array(
'user' =>$user,
'highlightId' =>'',
'data' =>$highlighted,
'created' =>$this->now,
)
);
return true;
}
};
$highlightslib = new HighlightsLib;

how to send a single element from browser to server without reload

How can I send just one element from browser to server fast and without reloading browser page?
Is there an AJAX way to do this, that is a NON-FILE method? The opposite of ".load"?
.load works great sending a single element from server to browser without page reload.
How to do the opposite direction?
Browser is JavaScript.
Server is vxworks with windmarks.
PRESENT METHOD THAT WORKS BUT RELOADS PAGE:
Presently, the browser element is and I use submit to send it to the server, but this takes too long and reloads the browser page.
The element's innerHTML contains data formatted as a vxworks WINDMARK.
(When the vxworks server receives this submission, it reads the windmark and copies it to a 'C' string for backend software to process.)
If you're using jQuery and PHP then something like this should work:
JS:
$.ajax('doServerSuff.php?action1=saveLog', function() {
// do stuff after server received the data
});
PHP (doServerStuff.php):
<?php
if ($_GET['action1'] == 'saveLog') {
//do stuff
}
?>
You can get and send data using jQuery. using something like this:
$.post('urlfromserver',browserdata,function(datafromserver){
//do stuff
})
if you let me put a little bit more, it's a good idea to use JSON to send/receive data to/from server. Having that in mind, you can do something like:
$.post('urlfromserver',{browserdata: JSON.stringify(browserdata)},function(datafromserver){
javascriptObject = jQuery.parseJSON(datafromserver)
//do stuff
})
And in your PHP code, it would be as simple as using json_encode to send data to javascript and json_decode to receive data from javascript
UPDATE
Obtaining the data in the server should be as simple as requesting the object via post or get depending on your send method, and parsing the JSON.
In PHP, this is an example of obtaining data using the above code:
$dataFromBrowser = json_decode($_POST['browserdata'])
Use $.post in jQuery to send the data.
The load intruction can also be used to transmit data to the server:
$().load("url", {limit: 25}, function(){
//transmission finished
});
In this example the parameter limit with the value 25 wil be transmitted to the server.
Taken from:http://api.jquery.com/load/
You can simply do with the ajax call like this
$.ajax({
type: "POST",
url: "yourpage.php?id=someValue",
success:function(data){
//do some stuff here
});
I got it working. Here is the corrected JavaScript, from the above answer.
Here is how to change a single element at the server.
This is also an example of how to write to a vxworks windmark string at a vxworks web server, without reloading the page.
NOTE: no URL is specified, so that the same page is used.
$.ajax({
type: "POST",
url: "?general_page_to_MM_data_1_windmark=CCCCCCCCCCCCCC",
success:function(data_from_server){
}});

Can I pass a Javascript variable in an #Ajax.Actionlink in asp.net-mvc 3?

I have the following Javascript code:
var idJS;
$('.disp').click(function () {
idJS = $(this).attr("id");
})
And then I want to do this:
#Ajax.ActionLink("myMethod", "myMethod", "HomeController", new { id = idJS },
new AjaxOptions() { HttpMethod = "Get", UpdateTargetId = "myDiv" })
Is it possible to do this?
This is not possible to do because Razor view code is rendered when the page it loaded, so all that code is resolved (transformed to HTML) before the javascript can even execute.
You can however use Javascript to change properties of a link, like the following for example (using JQuery though I am afraid, look up a javascript equivalent if need be)
$("a").attr("href", "/Home/myMethod/" + idJS);
ok I will look it up then, javascript only:
document.getElementById("link").href = "/Home/myMethod/" + idJS;
No. Server side and client side are two very different things. The server side is rendered before even reaching the client. By the time $(document).ready() is fired, the server is finished.
What you can do is change the id of the link with jQuery. With a little more information, I would be able to help more, but it's a simple thing to change attribute with jQuery.
I would set the id to be hard coded, like "ajaxBtn" or something, then, in your click even for .disp, change a data attribute to what you need it to be. However, without more data, I can't know for sure exactly why you're needing to set the id.

Jquery modification to add 1 and save the number in a txt file on every click

I am using the following click function for a purpose. What can I add so it will add 1 in a txt file when it is clicked? Like a counter on how many times it was clicked.
Thank you
$("#clearme").click(function(e) {
e.preventDefault();
// i have some stuff here
});
You can't access or edit files from the front-end. You'll need PHP or something. You can save it in a variable and pass it and process it with ajax. Something like this, untested:
var num = 0;
$button.click(function(){
$.ajax({
url: 'bla.php',
type: 'POST',
data: { num: ++num }
//...
});
});
And in PHP:
$num = $_POST['num'];
// Add to file stuff
you will have to modify the text file on the server. Send a ajax request every time the click event happens.
$("#clearme").click(function(e) {
$.post("url")
e.preventDefault();
// i have some stuff here
});
Text file where? On the server or the client machine?
If you're aiming for the client machine, javascript and jquery alone aren't going to work. There are security measures to prevent this so that would be hackers don't drop trojans on our machines every time we visit a website.
That leaves the server.
Accomplishing this depends entirely on the server side language/framework you are using (i.e. PHP, JSP, .NET).
You didn't post the reason behind needing to do this, so I'll offer the option of writing the value to a cookie instead of a file, but since you haven't told us more about what you're up to, this might not be a viable solution.

Categories

Resources