I have a page where people can login and their login request is sent with jQuery's $.ajax to a processing page. On that page all of the errors collected during the login attempt are stored in $_SESSION['error'].
How can I access this variable to alert users of the errors after the attempt is made. I know how to access a session variale, I mean how do I access a php variable without reloading the page. The only way I currently am aware of is to inject them on page load, but there must be some way to access them with JavaScript after they have changed due to an Ajax request.
Unfortunately you cannot directly access the PHP $_SESSION[] array from JavaScript. This is by design, because one of the major points of using a Session, is that the data is saved on the server side, unmodifiable by the end user, and therefore your Javascript.
What you could do however, is include the error list in your ajax response. Chances are you are doing an ajax request that returns a 'json' type format. Just include your error list in your json returned, and use the JavaScript to display them. I recommend not sharing the entire $_SESSION array, since it could give away some key information about the interworkings of your PHP.
Also, if you are not currently doing an ajax request that expects json, back, then consider switching it up so that you are expecting and returning json. You can provide much more hidden data this way, instead of just some HTML or text.
Hope this helps
Related
So, I have a PHP file that runs an SQL(MySql) query and gets the result. I need that page to send that result to another page automatically(I can use PHP in the receiving page). However, I want to make my website accessible to privacy-sensitive people who disable cookies and javascript on their browsers. I'm not using any PHP frameworks.
An initial page that runs the query only runs in the backend like a controller so it does not have any HTML in it. This means I cannot use a hidden form and make the user submit it with a button. I thought about sessions but they need cookies to work and JSON needs javascript. I thought about sending the data in the URL but the query result is quite big and I was afraid it could exceed some kind of URL length limits(if such thing exists). Is there a way to achieve this reliably?
EDIT: To clarify some things, the data I am sending is a search result so the query changes depending on the users input(which was provided to the page which runs the query with a form).
Store data somewhere and send id or something through query string and access data from database through that id from query string. Sending too much data is not advisable through cookies, session or even query string just pass your unique id and grab data from db.
Happy coding.
What would be the "best" approach to dealing with forms which have to work without and with JavaScript enabled?
Would it be better to create different routes for each, like
AJAX request: route "API/contact" and return res.send("message")
without JavaScript: route "contact"and return a redirect with a query param of "message"
Or in one route and detect xhr and render it depending on this?
Or is there a better way of dealing with the problem of taking the user to the res.send("") when the JavaScript isn't enabled to give the user feedback on the submit?
To clarify:
I have a site which is working with AJAX requests for its forms to avoid full page loads. It lacks the fallback when JavaScript is not enabled and thus when a user clicks submit on a form, he receives the data from the post back with res.send and it replaces the whole page, instead of the desired effect which would be to just update a label with the "success/fail" message. The question then remains as above which would be the neat way of dealing with this?
Probably the best thing to do would be to check the X-Requested-With header and check that it contains XMLHttpRequest (but this might get deprecated as the new fetch API will slowly come into browser.
Based on that value, you might want to return a JSON payload, or eventually trigger a server side rendering, therefore returning an HTML page ready-to-be-consumed.
As an alternative, you can return a redirect response with a particular query string value; once the page is loaded, you will check for that value (using qs for example, or deparam in jquery and manipulate the client side accordingly.
Your server routes have nothing to do with client-side javascript. You don't need javascript to receive a "res.send" message.
I'm using a web server framework which works with only GET requests, at the moment I'm trying to pass a large amount of data, that is the text content in a textarea which comes from user input, into another page which echoes the user's input.
I've attempted Querystrings but I end up receiving the error "Requested URL too long".
Any suggestions as to what method I should use?
If you can only send data encoded in GET requests, then you will have to break up the request and send it in multiple parts.
You could either use Ajax or store the entire set of data in localStorage and fetch each chunk in turn as the page reloads.
One approach would be to make a request to an end point that allocates you a unique ID. Then send a series of requests in the form: ?id=XXX&page=1&data=... before closing it with ?id=XXX&total_pages=27 at which point you assemble the different pieces on the server.
This way lies madness. It would be much better to add POST support to your framework.
Try using Javascript Cookies.
you can store the textarea value there and then read it in another page (or wherever you want).
Here's a tutorial
http://www.w3schools.com/js/js_cookies.asp
I'm new to JavaScript and AJAX. My experience is mostly in PHP. How can you do a MySQL query from JavaScript without revealing in the View HTML Source of the web browser the connection information for the MySQL database such as the db user's password? Thanks!
You make your JavaScript request the information from a PHP script, which checks the user's login cookie (like any other page would) and queries MySQL, returning the information to the JavaScript in whatever form it needs (JSON, usually).
In this case you don't perform the actual database query from the JavaScript code. The fact that it's using AJAX doesn't move database connectivity to the client, it just allows you to request information from the server without refreshing the page (as well as potentially moving some of the UI logic to the client).
Your AJAX call would simply make a request to a PHP file in your website which could:
Render part of a page, where the JavaScript code from the other page which called it would insert that markup into the open page. Or;
Render data, usually in JSON format, which the JavaScript code from the other page would read and use.
So let's say you have PageA.php which has a bunch of HTML and JavaScript. You want some of that JavaScript to make an AJAX call to the server to get data. You'd create a PageB.php which behaves just like any other PHP code, but instead of using HTML between the PHP code fragments (or in echo statements) it would use JSON syntax to represent the data being returned.
The JavaScript code on PageA.php would make an AJAX call to PageB.php, read the data that's returned, and use it in the HTML of PageA.php entirely client-side without having to refresh PageA.php.
How do I design a Django/Javascript application to provide for conditional Ajax responses to conventional HTTP requests?
On the server, I have a custom-built Form object. When the browser POSTS the form's data, the server checks the submitted data against existing data and rules (eg, if the form adds some entity to a database, does that entity already exist in the database?). If the data passes, the server saves, generates an ID number and adds it to the form's data, and passes the form and data back to the browser.
if request.method == 'POST':
formClass = form_code.getCustomForm()
thisForm = formClass(data=request.POST)
if thisForm.isvalid():
saveCheck = thisForm.saveData()
t = loader.get_template("CustomerForm.html")
c = Context({ 'expectedFormObj': thisForm })
(Note that my custom logic checking is in saveData() and is separate from the html validation done by isvalid().)
So far, standard Django (I hope). But if the data doesn't pass, I want to send a message to the browser. I suppose saveData() could put the message in an attribute of the form, and the template could check for that attribute, embed its data as javascript variable and include a javascript function to display the message. But passing all that form html back, just to add one message, seems inelegant (as does the standard Django form submission process, but never mind). In that case I'd like to just pass back the message.
Now I suppose I could tie a Javascript function to the html form's onsubmit event, and have that issue an XMLHttpRequest, and have the server respond to that based on the output of the saveData() call. But then the browser has two requests to the server outstanding (POST and XHR). Maybe a successful saveData() would rewrite the whole page and erase any potential for conflict. But I'd also have to get the server to sequence its response to the XHR to follow the response to the POST, and figure out how to communicate the saveData outcome to the response to the XHR. I suppose that is doable, even without the thread programming I don't know, but it seems messy.
I speculate that I might use javascript to make the browser's response conditional to something in the response to the POST request (either rewrite the whole page, or just display a message). But I suspect that the page's javascript hands control over the browser with the POST request, and that any response to the POST would just rewrite the page.
So can I design a process to pass back the whole form only if the server-side saveData() works, and a message that is displayed without rewriting the entire form if saveData() doesn't? If so, how?
Although you can arrange for your views to examine the request data to decide if the response should be an AJAXish or plain HTML, I don't really recommend it. Put AJAX request handlers in a separate URL structure, for instance all your regular html views have urls like /foo/bar and a corresponding api call for the same info would be /ajax/foo/bar.
Since most views will examine the request data, then do some processing, then create a python dictionary and pass that to the template engine, you can factor out the common parts to make this a little easier. the first few steps could be a generic sort of function that just returns the python dictionary, and then actual responses are composed by wrapping the handler functions in a template renderer or json encoder.
My usual workflow is to initially assume that the client has no javascript, (which is still a valid assumption; many mobile browsers have no JS) and implement the app as static GET and POST handlers. From there I start looking for the places where my app can benefit from a little client side scripting. For instance I'll usually redesign the forms to submit via AJAX type calls without reloading a page. These will not send their requests to the same URL/django view as the plain html form version would, since the response needs to be a simple success message in plain text or html fragment.
Similarly, getting data from the server is also redesigned to respond with a concise JSoN document to be processed into the page on the client. This also would be a separate URL/django view as the corresponding plain html for that resource.
When dealing with AJAX, I use this:
from django.utils import simplejson
...
status = simplejson.dumps({'status': "success"})
return HttpResponse(status, mimetype="application/json")
Then, AJAX (jQuery) can do what it wants based on the return value of 'status'.
I'm not sure exactly what you want with regards to forms. If you want an easier, and better form experience, I suggest checking out uni-form. Pinax has a good implementation of this in their voting app.
FYI, this isn't an answer...but it might help you think about it a different way
Here's the problem I'm running into...Google App Engine + jQuery Ajax = 405 Method Not Allowed.
So basically I get the thing to work using the outlined code, then I can't make the AJAX request :(.