Validating From using AJAX and jQuery without sending data to another file - php

my problem is - for now - not about specific code but more about basic understanding - I think.
I want to create a formular and use the data without refreshing the page, so that brings me to AJAX.
Now do I always have to create a seperate file that works with the data that AJAX sends? Can't I just "grab" the data and work with it on the same page?
I think I missunderstood some basic concepts.
I thought about something like this:
<form id="load_filters_form">
..
</form>
<?php
var_dump($_GET); // values from <form>
?>
<!-- AJAX, jQuery -->
<script>
$("#load_filters_form").submit(function(event){
event.preventDefault();
$.ajax({
type: 'get',
data: $(this).serialize()
success: function() {
$("#load_filters_form")[0].reset();
}
});
});
</script>

What you're proposing is certainly possible, it's exactly how AJAX works. You make an AJAX request from JavaScript code, sending any data the server-side code will need, and handle the response from the server in your JavaScript code.
The problem with what you're proposing is that you're making it unnecessarily complex for yourself. Consider what your code in the question would return to the JavaScript code in the AJAX response. It returns an entire HTML page, most of which is already on the client.
Why re-transmit all of that data that the client already has? Why have code on the client to parse out the data it's looking for from all of the unnecessary markup around that data?
Keep your operations simple. If you need a server-side operation which receives data, performs logic, and returns a result then create an operation which does exactly that. Call that operation in AJAX and use the resulting data.
Now maybe that response is structured JSON data, which your client-side code can read and update the UI accordingly. Or maybe that response is raw HTML (not an entire page but perhaps a single <div> or any kind of container which presents an updated version of a section of the page), which your client-side code can swap into the UI directly.
The AJAX interactions with the server should generally be light. If you're intentionally re-loading the entire page in an AJAX operation then, well, why use AJAX in the first place? The point is to send to the server only the data it needs, and receive back from the server only the data you need. For example, if all you need is to update a list of records displayed on the page then you don't need the whole page or even the HTML table of records, you just need the records. JSON is useful for exactly that, returning structured data and only structured data to the client. Then the client-side code can render that data into the structure of the page.

Now do I always have to create a separate file that works with the data that AJAX sends?
Yes and no. You may choose not to have a specific file which your ajax is pulling, but you do need some sort of Routing and Controller relationship as most frameworks build it.
You could in theory create a request to self (the same page) but that's bad logic. You are going to mix backend logic with frontend and will get messy - very quickly. You really need to separate all three elements,
PHP takes the data and process it
JavaScript takes the data and displays it
Your html should be code free; Just a pretty finalized product.
The best design pattern is to separate those files in their proper environment.
Can't I just "grab" the data and work with it on the same page?
Not really, at least not consistently. You also have to keep in mind it's a potential issue in attempting to serve two separate contents from the same route/file:
if ajax
// do something
else
// do the other thing
Ajax does not want fully rendered HTML files, it takes too long; it's best to serve JSON objects/arrays which will be rendered in your frontend via JavaScript; which was also used to make the request - in the user's browser without the latency caused by their network or your server.
There's no sure way of knowing which request is what since no data from the client is trustworthy, including HTTP headers; they are easy to fake and could potentially lead to security/unwanted results.
Thus, the best solutions is to have a foreign file which you would make the requests to, instead of doing it from itself.

Related

How to log activities across multiple requests

Our site makes heavy use of AJAX, and ends up calling several different PHP files in the background to fill individual tabs. Specifically, JQuery and DataTables are used. Because PHP is stateless, I'm struggling to create an activity log to work across all requests for a single session (e.g., all SQL queries performed for this page view) as each PHP file executes its own queries in its own state, so they are unaware of each other.
Any tips on how to handle this? I fear I'm overcomplicating matters or missing an obvious solution.
In the end, ideally the footer of our application can say something like: Your application performed 6 SQL queries, here they are: ....
I don't require specific code, but hopefully the above makes sense and a Eureka moment can be discovered.
One solution using Jquery would be for each $.post Ajax call to pass a callback function. The callback then adds the result when returned from the server to a DIV or a js array.
Ajax post could be:
$.post(server_url, params, my_callback, "json")
and callback:
function my_callback(response) {
$("#thediv").append(response)
}
This would asynchronously log each response in the div with id "thediv"

jQuery AJAX - Get data from php during the request

I'm using AJAX to insert data in MySQL database. During the AJAX request, there is a PHP function that loops inside a JSON array in order to get data and to insert it inside the DB. Everything works fine.
But, I would like to know if there is a way to pass, during the AJAX request a PHP var to jQuery in order to append it in HTML or to retrieve the data with console.log. I can get these info on AJAX complete but is it possible to get info during AJAX request?
I think you can just echo the php var on the page?
E.g. echo "<label>".$phpVarToAppend."</label>";
Nope. HTTP is stateless. You make a request and you get a result.
You must use different techniques to check the request's processing advancements from server.
Given that you store a record of the progression during the processing somewhere (db, cache or whatever), the simpler trick is using another AJAX call to a simple function that returns the last processing record.
This is a traditional polling mechanism.
A more advanced solution could be using a different connection upgraded to websockets. This will be a true realtime channel.
On top of these there's a world of possibilities. It only depends on what you need to manage with your POST request and how long does it take the processing.
For big payloads it's usually better to return immediately and start processing in a different task. (and thus a pooling mechanism to check progression)

Way to send POST data to a PHP file from another PHP file?

Alright, so I've looked at a ton of questions, but I only found 1 that resembled what I am trying to do. Here is the link to it: Passing POST data from one web page to another with PHP
I want to pass data from one PHP file(we'll call it editData.php) to another PHP file(we'll call it submitData.php). Neither file has any HTML elements (pure PHP code I mean). The first file(editData.php) receives $_POST data, edits it, and needs to send it to the second file. The second file(submitData.php) needs to be able to read in the data using $_POST. No sessions nor cookies can be used I'm afraid.
In the linked question above, the answer accepted was to create hidden fields inside a form and POST the data from there. This worked for the OP because he had user interaction on his "editData.php", so when the user wanted to go to "submitData.php", he would POST the data then.
I can't use this solution(at least, I don't think I can), because I am accessing (and sending $_POST data to) editData.php from a javascript AJAX call and there will be no user interaction on this page. I need the modified data to be POSTed by code, or some other way that does the transfer 'automatically'(or 'behinid-the-scenes' or whatever you want to call it). submitData.php will be called right after editData.php.
I don't know if I can rewrite submitData.php to accept GET data, so count that out as well (it's a matter of being able to access the file). I really don't want to echo stuff back to my original JavaScript function(and then AJAX again). I am encrypting info in editData.php, and (while it sounds silly to say it) I don't want to make it easy for someone to develop a cipher for my encryption. Returning values after being encrypted(viewable with Inspect Element) would make it too easy to decipher if you ask me.
I feel like this issue could come up a lot, so I'd expect that there is something obvious I'm missing. If so, please tell me.
tl;dr? How can I send data to a PHP file via the POST method while only using code in another PHP file?
Well you might consider just streamlining your approach and including the submitData logic at the end of the editData file. But assuming that this is not possible for some reason (files live on different systems, or whatver), your best bet might be to use cURL functionality to post the data to the second script.
If the files are on the same server though I would highly recommend not posting the data to the second script as this will basically just double the amount of requests your web server needs to handle related to this script.

javascript vs. php : pros and cons for code development

If a user refreshes a page I need to send the data using php as it accesses a mysql table.
If the user adds content, I don't want to run an AJAX call "first" as I can simply and immediately update the DOM, and then send a one-way ajax call to store it in the mysql table.
So on a referesh I have PHP creating my XHTML and sending it to the Browser.
On user input, I have the DOM update immediately followed by ajax call to put it in the mysql table.
Thing is I have to write code in JS and PHP for each user action that modifies the page.
Should I have the data sent to the Javascript for entry into the DOM and not do less with it in the PHP. What are the tradeoffs from taking user input and converting it to the UI with javascript vs. php?
Should I offload as much as possible to the client to reduce server load?
You have answered it yourself:
With php you need to send it through ajax and wait for response
With javascript you need to maintain 2 set of templates (server- and client-side one)
If you need to do something with the data serverside (validation, processing, etc), you can either use JavaScript with AJAX, or send it off on a page reload using POST or GET, depending on what you're sending. If you don't need to do anything with the data serverside, then using JavaScript to modify the DOM immediately is fine.
DOM operations aren't fast. Try it and you'll see that is better for your users to pass real HTML as it is or JSON-embedded with AJAX requests. Even big names like Twitter do it so.
If you still want to get away without PHP consider server-based JavaScript, e.g. Node.js.

jQuery AJAX get PHP script, display the content as it loads

I'm having to interact with the Facebook API for this project, which I find to be actually a bit slower than I expected. Because of this, I'm having to do something which I find rather unorthodox: I need to load the content Facebook provides back in my PHP script AS IT LOADS from Facebook. Traditionally I've loaded content into a div tag at the success of the script; however, I need to load the content as it appears. It would be absolutely unacceptable to have a client wait nearly a minute for Facebook to load an album and all respective comments before displaying anything. Hopefully I'm not being to vague; I'm not here to ask for code, but I've tried just about everything I can think of. Is this a simple concept I'm missing?... I feel as though this is easier than I'm making it.
I'm using jQuery AJAX as I find this easiest to work with. Any comments and/or help would be greatly appreciated.
The root of your problem is that jQuery's AJAX methods hook into the onreadystatechange event and readyState variable. readyState is only set to 4 when the file is completely transferred, and therefore your events will only fire after the download is complete.
Accessing the data as it is being sent is not consistent across different browser families. Doing it this way is going to be incredibly complex and time-consuming. I would recommend first doing this a little differently, perhaps by preloading the relevant facebook data on your own server predictively. This can be compiled to a static page, and that can in turn be served to your users very quickly.
To get the data to your users faster, you'll need to work outside the box as well. There's a jQuery plugin discussed here ( Does PHP flush work with jQuerys ajax? ) that makes jQuery ajax methods compatible with streamed output. Good luck.
The problem seems to stem from the fact that you're getting too much data at once. I suppose you are talking about receiving content from ajax as it is printed out immediately, but it is possible this content is built and sent at once and you won't have access to the data until the entire parse is complete. If this is untrue, look into COMET. If it is true, the solution is to put a limit on how much data you retrieve at once in an effort to reduce the parse time. For example, retrieve 5 photos in each request. Add those 5 photos to the DOM while you retrieve the next 5.
Instead of putting whatever code you want inside of the callback, just put it after the callback
for example
$("#div").load("facebook...", function() {
//do stuff
});
//put the stuff you want to load at the same time, here

Categories