This post is more a question than an actual issue with code.
So for a long time when I had to display for example a list of items from database, I used to display the Id (primary key in the table) directly in the HTML like this for example :
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
So like this when I wanted to do an Ajax request of the current clicked item, it was easy because I just had to retrieve the attribute from the html like this :
$.ajax({
url: '/api/Item/'+$(this).attr('id'),
type: 'GET',
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
That's only after browsing a lot of websites that I noticed that nobody display the primary key (Id) directly in the HTML. But somehow they could still do ajax request to the API using the Id of the clicked item. So my question is : How can I get the current clicked Id to do my ajax request without displaying anywhere. I mean how does these websites manage to do that ? Maybe they get list from server that they use in the client then ? But it still does not explain how they manage to get the current clicked Id.
Appreciate your thoughts and suggestions on this.
Example of website : https://www.toneden.io/
The chat at the bottom right when connected see network and web browser console.
To get response from the server, you have to request something. In this case, you are saying i don't want to display primary key anyware in html side and get result from server. my suggestion on this, In php > you can use binary number instead of primary key and convert back to number and use acc. to requirements. Example :- decbin() and bindec()
There's nothing wrong with displaying an id. I've appended the database id such as id="game_1281" in cases where I only want to refer to the DOM in response to a server push update. Another option is to use a data attribute like so: data-id="1281". This allows you to get the value without any messy parsing before sending it to the server.
Referencing a unique id is not a security issue. Just make sure you are doing the appropriate server-side checks to ensure that the action taken is possible for that user based on various constraints and privileges.
Related
I'm actually running into little problems with my current project. Following case:
I've got a model called "Posting" with relations:
public function subscribers(){
return $this->belongsToMany('User');
}
In my view-file there is a table containing all Postings and also a checkbox for subscribing/unsubscribing with the matching value to the posting-id:
<input class="click" type="checkbox" name="mobileos" value="{{{$posting->id}}}"
#if($posting->subscribers->find(Auth::User()->id))
checked="checked"
#endif
>
Now the thing I want to archive:
A JavaScript is going to watch if the checkbox is checked or not. According to that, the current user subscribes/unsubscribes to the posting. Something like:
$('.click').on('click',function() {
// $posting->find(---$(this).prop('checked')---)->subscribers()->attach(---Auth::user()->id---);
// $posting->find(---$(this).prop('checked')---)->subscribers()->detach(---Auth::user()->id---);
});
Is there any possibility to archieve that or any other ways? I couldn't get my head around this so far.
Cheers,
Chris
If you want to use Ajax to achieve this, you will need a REST endpoint in Laravel for the subscriptions, e.g.:
http://localhost/subscribe/{{userid}}
When this Endpoint is called, the database can be updated. The function could also return a JSON showing, if the saving database in the database successful.
Use this endpoint to make an Ajax Call on click:
var user = {
id: 0 // retrieve the correct ID from wherever it is stored
}
$('.click').on('click',function() {
$.GET('http://localhost/subscribe/' + user.id,
function () { // this is the success callback, that is called, if the Ajax GET did not return any errors
alert('You are subsribed')
});
});
Ideally you won't be using the GET method, but instead use POST and send the user ID as data. Also you would need to retrieve the user ID from session or wherever it is stored.
Take care that as you are using Ajax it can easily be manipulated from the client side. So on the server you should check, if the user ID that was sent is the same as in the Session. Maybe you don't need to send the user id at all, but that depends on how your backend is built.
I currently have this code and I want to know how to store it, and then use it, in a database:
var stores = {
"McDonalds" : .90,
"Target" : .92,
"iTunes" : .95,
"Starbucks" : .87,
"Best Buy" : .93,
}
This list will be different and much bigger, but thats an example. It is currently put into action using:
<script src="location"></script>
I want to hide it in a database so that it isn't accessible to customers or competitors. How can I do that? And, when doing so, how would I then have my page access it instead of using script src?
You can't hide this from your customers, and still have your customers use that data in their browser. That isn't how the Internet works. If the browser needs to read that data, the user can also read that data.
If you can move whatever calculation you're doing server-side, that might be an option, but these are pretty simple values, and I'm guessing that people will have little difficulty guessing them simply by examining the inputs and outputs of your algorithm.
Hello again StackOverflow.
I've been tasked with modifying a website that runs on Scala's Play! framework and Twitter Bootstrap. I've hit a roadblock concerning altering the DOM. I need to accomplish the following:
(The page being talked about takes user input and passes the server a Form, which if
valid writes the mapped Data in the Form to a database.)
Have the user choose a category from a drop-down. This particular drop-down has nothing to do with the Form.
Based on their choice, query the database for all objects of a certain type that relate to the chosen category via a foreign key.
Alter the DOM (that is, show without reloading the page) to display those objects for the user to select them. Their selections are added to the Form.
Submit the Form, write to the database, etc.
Questions:
Is this a good way to go about what I'm trying to accomplish?
If so, is there a way to alter the DOM via Scala/Play HTML templates without reloading the page?
If that's not possible, what ilk of manually written Javascript is necessary?
Admissions:
I have very little experience with web development other than Play.
I have very little experience with Javascript.
Resources I've been looking at:
This SO post
Play docs on Javascript routing
Scala.js
Thank you!
For anyone who might come upon this in future, the short answer is Javascript.
Long answer:
To do any AJAX work, you'll need a method like the following in your top-level Controller to set up Javascript routing:
def javascriptRoutes = Action { implicit request =>
Ok(
Routes.javascriptRouter("jsRoutes")(
SomeOtherController.someMethod // Returns a JsValue!
)
).as("text/javascript")
}
Then in the HTML template (*.scala.html) which will contain some AJAXy Javascript:
<script type="text/javascript" src="#routes.ApplicationController.javascriptRoutes"></script>
And finally in your actual JS file (assuming you're using jQuery):
$("someSelector").click(function() {
// Notice that this matches the method name that exists in Scala!
// Make sure to pass `someMethod` what it needs.
var req = jsRoutes.controllers.SomeOtherController.someMethod(...)
$.ajax({
url: req.url,
type: req.type,
success: function(json) {
// DOM manipulation, etc., here.
},
error: function(xhr, status, errorThrown) {
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
}
}); // ajax
}); // handler
I have built a calendar in php. It currently can be controlled by GET values from the URL. Now I want the calendar to be managed and displayed using AJAX instead. So that the page not need to be reloaded.
How do I do this best with AJAX? More specifically, I wonder how I do with all GET values? There are quite a few. The only solution I find out is that each link in the calendar must have an onclick-statement to a great many attributes (the GET attributes)? Feels like the wrong way.
Please help me.
Edit: How should this code be changed to work out?
$('a.cal_update').bind("click", function ()
{
event.preventDefault();
update_url = $(this).attr("href");
$.ajax({
type : "GET"
, dataType : 'json'
, url : update_url
, async : false
, success : function(data)
{
$('#calendar').html(data.html);
}
});
return false;
});
Keep the existing links and forms, build on things that work
You have existing views of the data. Keep the same data but add additional views that provide it in a clean data format (such as JSON) instead of a document format (like HTML). Add a query string parameter or HTTP header that you use to decide which view to return.
Use a library (such as YUI 3, jQuery, etc) to bind event handlers to your existing links and forms to override the normal activation functionality and replace it with an Ajax call to the alternative view.
Use pushState to keep your URLs bookmarkable.
You can return a JSON string from the server and handle it with Ajax on the client side.
I am a real noob when it comes to javascript/ajax, so any help will be very appreciated.
In reference to this question:
Updating a MySql database using PHP via an onClick javascript function
But mainly concerned with the answer left by Phill Sacre. I am wondering if someone could elaborate on how we are(if we can?) passing values/data through his example, using jquery.
The code example left by him is as follows:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
Say for example, we are wanting to pass any number of values to the database with php, could someone give me a snippet example of what is required in the javascript function? Or elaborate on what is posted above please?
Thanks again all.
The simplest example I can think of is this. Make your AJAX call in your if block like this:
$.get('updatescore.php', {'score': '222'}, function(d) {
alert('Hello from PHP: ' + d);
});
On your "updatescore.php" script, just do that: update the score. And return a plain text stating wether the update operation was successful or not.
Good luck.
P.S.: You could also use POST instead of GET.
What you would do is on the php server side have a page lets say its update.php. This page will be visited by your javascript in an Ajax request, take the request and put it in a database.
The php might look something like this:
<?php
mysql_connect(...)
mysql_query("INSERT INTO table
(score) VALUES('$_GET["score"]') ")
Your javascript would simply preform an ajax request on update.php and send it the variables as get value "score".
Phil is not passing any values to the script. He's simply sending a request to the script which most likely contains logic to 'update' the score. A savvy person taking his test though could simply look at the HTML source and see the answer by checking to see what the anchor is doing.
To further nitpick about his solution, a set of radio buttons should be used, and within the form, a button or some sort of clickable element should be used to send the values to the server via an ajax request, and the values sent to the server can be analyzed and the status of the answer sent back to the page.
Since you're using jQuery, the code can be made unobtrusive as seen in the following example:
$('#submit_answer').click(function() {
var answer = 'blah' // With blah being the value of the radio button
$.get('updatescore.php',
{'value': answer},
function(d) {
alert('Your answer is: ' + d') // Where d is the string 'incorrect' or 'correct'
}
});
Enjoy.