This question already has an answer here:
Firing SQL query on click of button?
(1 answer)
Closed 5 years ago.
I have a page where photos are uploaded, when you see the photos there is a button to give you points to the photo.
To the button I gave an onclick with a javascript function that has this php code
function puntos(){
<?php
mysql_query("UPDATE 'fotos' SET 'relevancia=relevancia+1' WHERE 'id = $id'");
?>
}
This is in photo.view.php in photo.php I have this code that retrieves the id of the selected photo
$id = isset($_GET['id']) ? (int)$_GET['id'] : false;
what am I doing wrong?
You're far from home.
Back to basics first:
Server vs. client
mysql and PHP run on the server
JavaScript runs on the client in their browser.
This means javascript cannot access your database directly, you need to do a lot of work before you get there.
Detecting and reacting on a click is something JavaScript can do (and is quite adept at doing).
Communication
Normally when a page downloads it and the components it refers are sent from the server to the client over HTTP.
Once in the browser, to get something back from the client to the server the only way is to send another query or open up some network connection somehow from the client to the server which then transfers that content, or indicates somehow what happened on the client.
Traditionally this meant a form and a click resulting in a GET or POST HTTP request and a reload of the page in the browser.
That's till we got:
AJAX
Essentially the connection from the client to the server can also be initiated by JavaScript itself and it can talk to a server component (just like the browser can) without having to reload a page or having to submit a form or so). This allows one to create things where a click or even a move of the mouse (or anything else JavaScript can detect -it can detect a lot-) can result into data being sent to the server and answers collected by that JavaScript. If it updates the page (aka DOM) is up to the script to chose.
Server Side
Now having JavaScript on the client communicating with the server still isn't going to let said JavaScript update a database. So you need a sever side component that does stringent validations (the code you have above is a horror story from the security side should that ever get to work) and updates a database behind it as needed.
TL;DR
Suggest you read up more on how to do simple AJAX
Some starting points:
https://www.w3schools.com/xml/ajax_intro.asp
https://www.owasp.org/index.php/AJAX_Security_Cheat_Sheet
But there's much more out there for sure.
Related
I'm working on a project that uses IP Payments to process transactions. The project involves a web form written in ASP with Code-Behind written in C#.
IPP offers an iFrame implementation, where you can put an iFrame in your page and display a small IPP page with fields for entering credit card information. The idea behind this is that the credit card info will only be handled by IPP and never by the server running the page, thus there is no requirement to ensure that card data is kept secure.
In order to display the IPP page in the iFrame though, a session needs to be initiated with IPP. The server initiates the session, and passes in a SessionID variable. Upon a successful session initiation, a Secure Session Token is returned to the server. The server then needs to "force" the client's browser to GET or POST the SessionID and the SST (Secure Session Token) to the IPP website. This is where my problem is.
I wrote a Javascript function in the ASPX page that would accept two parameters - the SessionID and SST - and send them to the IPP website. I'm now trying to call this Javascript function from my C# code upon successful initiation of the IPP session. However, I have been completely unable to do so.
I've done a lot of searching, and the one answer I keep coming across is to use either RegisterStartupScript or RegisterClientScriptBlock. The problem is, these seem to insert text directly into the page, rather than calling an existing function. Assuming I inserted my function into the page via one of those functions rather than writing it into the page myself, it still doesn't solve my problem of how to call said function.
Now it is possible that I'm going about this the wrong way, and there's a much better way to get the client's browser to GET/POST the SessionID and SST; if so, please tell me. I'm inexperienced with web programming and am thus learning as I go and making up solutions along the way that are quite likely not ideal.
Thanks in advance.
I think this should work:
Lets say you have something like this in your HTML:
<html>
<head>
<script>
function sendValuesToIPP(sessionId, sst){
//do stuff
}
</script>
</head>
</html>
If you do this in your C# code it should work
ClientScriptManager.RegisterStartupScript(
this.Type,
"some_key_you_want_to_identify_it",
string.Format("sendValuesToIPP('{0}','{1}')", SessionID, SST),
true);
Keep in mind that I'm assuming you have SessionID and SST properties server side, you can get them from wherever you want and just add them to the string that will actually call the function when registered in your ASPX.
How can I pass a javaScript variable into ruby. I want to do something like this but I don't know how to express it.
function save(){
var g = document.getElementById("self").value;
<% #owner.info = g %>
}
Another possible work around is that i would need to be able to extract contents of a text area through rails and not javascript.
Can anyone help me?
What you are attempting to do doesn't make sense with a vanilla rails installation and javascript. Here's a good workflow that accomplishes what you're trying to do along with some details:
1. A page is requested from the server
The ruby code that runs rails and your application is executed on the server. The server receives a request, executes the ruby code, and sends the response as an html document.
2. A user gets the response from the server
The user's browser receives the html and turns it into a pretty web page. It's at this point that any javascript related to your application is executed in the user's browser. The connection with the server has been severed and no further ruby code will be executed until another request is made.
3. The user fills out an ajax form
On the page rendered in step 2, you have a form. Following this guide you can tell this form to submit via ajax. That means instead of requesting a new web page, the browser will send a special request using javascript to the server. The server can save the form values to your database and send a response back to the browser. All the while the user hasn't left the page they are currently viewing.
Alternatively you can skip the ajax and have the user submit the form, but you'll need to redirect them back to the page they were viewing (and probably adding a note the form they submitted was saved).
Since mostly a backend guy, I am not sure how can I achieve the following since it
requires some interaction with the browser.
So, I have a the following things so far.
A communication protocol where server is in python and client is in javascript code.
Ultimately, I want my data to reach to that javascript code.
Now, this data is being captured from browser.
As a practice.. what I am trying to do is.. have two radio buttons on my browser and a submit button
*radio A
*radio B
* Submit
Now, when the user presses submit, I somehow want to create a query "user submitted: A (or B)" and this query i am able to capture on python script.
I am at lost on how to do this.
My guess is that "submit" invokes a python script.
But what if my python server is always on .. how do i parse that response from the click of browser to this python server?
This is the way it usually works:
Client (browser) visits webpage and initiates request to server
Server (in your case, Python) handles request and writes HTML response, including the radio-button form
Client fills out form and hits Submit, triggering another request to the server
Server handles the second request and writes another response (e.g. "Purchase successful", "message posted", etc.).
Note that the second request is a brand-new request. You may want some way of linking the first request to the second one unless the second request is anonymous. Some frameworks will do that for you, but if you are making the server from the ground up you'll want some kind of session mechanism to keep track of state.
To get the client to make the second request, the simplest is to add appropriate action and method attributes to the form element in your HTML. action specifies the URL to access for the form request, and method is either GET or POST. (More advanced usage, e.g. on this site, typically uses AJAX to make the submissions instead).
I have a jQuery plugin I use to dynamically create and render a form on a default.aspx asp.net page, then submit it. The page it gets submitted to is a pdf.aspx page. The page builds a PDF then uses Response.Write to write the file (application/pdf) to the browser. I use the same method to render XLSX files to the browser as well. It works really great, but I need a callback or some event to tell the button when to stop spinning. This prevents the user from continuously clicking the Excel or PDF buttons. Does anyone know a way to detect the file dialog window when it was not created using JavaScript? I am also open to other methods of callback from the server side as well.
The way I do that was suggested in response to a question I asked here a while ago by T.J. Crowder. I can't find the response from the last time I wrote this up because the Stackoverflow "search" facility is so incredibly lame, so I'll probably type in a blog post. The basic idea is that your client code (Javascript) should append an extra parameter when it submits the request for the download. The parameter should contain some generated random string (probably just the current timestamp is good enough). The server then looks for that parameter, and when it's preparing the response with the download file it also sets a cookie and gives it that random value.
Right after the submit (or right before; it doesn't really matter), the Javascript code should start an interval timer with a routine to look at the value of document.cookie and see if it contains that random string. As soon as the cookie does contain that string, then you know that the server has sent back its response and that the file download dialog has been presented.
I need to do as much as possible on the client side. In more details, I would like to use JavaScript to code an interface (which displays information to the user and which accepts and processes response from the user). I would like to use the web serve just to take a date file from there and then to send a modified data file back. In this respect I would like to know if the following is possible in JavaScript:
Can JavaScript read content of a external web page? In other words, on my local machine I run JavaScript which reads content of a given web page.
Can JavaScript process values filled in a HTML form? In other words, I use HTML and JavaScript to generate an HTML form. User is supposed to fill in the form and press a "Submit" button. Then data should be sent to the original HTML file (not to a web server). Then this data should be processed by JavaScript.
In the very end JavaScript will generate a local data-file and I want to send this file to a PHP web server. Can I do it with JavaScript?
Can I initiate an execution of a local program from JavaScript. To be more specific, the local program is written in Python.
I will appreciate any comments and answers.
It could technically, but can't in reality due to the same origin policy. This applies to both reading and writing external content. The best you can do is load an iframe with a different domain's page in it - but you can't access it programmatically. You can work around this in IE, see Andy E's answer.
Yes for the first part, mmmm not really for the second part - you can submit a form to a HTML page and read GET arguments using Javascript, but it's very limited (recommended maximum size of data around 1024 bytes). You should probably have all the intelligence on one page.
You can generate a file locally for the user to download using Downloadify. Generating a file and uploading it to a server won't be possible without user interaction. Generating data and sending it to a server as POST data should be possible, though.
This is very, very difficult. Due to security restrictions, in most browsers, it's mostly not possible without installing an extension or similar. Your best bet might be Internet Explorer's proprietary scripting languages (WScript, VBScript) in conjuction with the "security zones" model but I doubt whether the execution of local files is possible even there nowadays.
Using Internet Explorer with a local file, you can do some of what you're trying to do:
It's true that pages are limited by the same origin policy (see Pekka's link). But this can be worked around in IE using the WinHttpRequest COM interface.
As Pekka mentioned, the best you can manage is GET requests (using window.location.search). POST request variables are completely unobtainable.
You can use the COM interface for FileSystemObject to read & write local text files.
You can use the WScript.Shell interface's Exec method to execute a local program.
So just about everything you asked is attainable, if you're willing to use Internet Explorer. The COM interfaces will require explicit permission to run (a la the yellow alert bar that appears). You could also look at creating a Windows Desktop Gadget (Vista or Win 7) or a HTML Application (HTA) to achieve your goal.
Failing all that, turn your computer into a real server using XAMPP and write your pages in PHP.
see i got what you want to do
best things is do following
choose a javascript library (eg:jquery,dojo,yui etc), i use jquery.this will decrease some of your load
inspite of saving forms data in in a local file, store them in local variables process them and send them to server (for further processing like adding/updating database etc) using XMLHttp request, and when webservice returns data process that data and update dom.
i am showing you a sample
--this is dom
Name:<input type='text' id='name' />
<a href='javascript:void(0)' onClick='submit()'>Submit Form</a>
<br>
<div id='target'></div>
--this is js
function submit()
{
var _name=$('#name').val();// collect text box's data
//now validate it or do any thing you want
callWebservice(_name,_suc,_err);
//above call service fn has to be created by you where you send this data
//this function automatically do xmlHttprequest etc for you
//you have to create it ur self
}
//call this fn when data is sucessfully returned from server
function _suc(data)
{
//webservice has returned data sucessefully
//data= data from server, may be in this case= "Hello user Name"; (name = filled in input box);
//update this data in target div(manipulate dom with new data);
$('#target').html(data);
}
function _err()
{
//call this fn when error occurs on server
}
// in reality most of the work is done using json. i have shown u the basic idea of how to use js to manipulate dom and call servcies and do rest things. this way we avoid page-reloads and new data is visible to viewer
I would answer saying there's a lot you can do, but then in the comment to the OP, you say "I would like to program a group game."
And so, my answer becomes only do on the client side what you are able and willing to double check on the server side. Never Trust the Client!
And I do not want to do my job twice.
If you are going to do things on the client side, you will have to do it twice, or else be subject to rampant cheating.
We had the same question when we started our project.In the end we moved everything we could on the JS side. Here's our stack:
The backend receives and send JSON data exclusively.We use Erlang, but Python would be the same. It handles the authentication/security and the storage.
The frontend, is in HTML+CSS for visual elements and JS for the logic.A JS template engine converts the JSON into HTML. We've built PURE, but there are plenty of others available. MVC can be an overkill on the browser side, but IMO using a template engine is the least separation you can do.
The response time is amazing. Once the page and the JS/CSS are loaded(fresh or from the cache), only the data cross the network for each request.