How to code in Laravel so that the requests are executed without refreshing the page? - laravel

In Laravel when we using forms to store or delete a resource, the page is refreshed. What is the best technology to avoid refreshing the page while the request is being processed? AJAX, Vue.js, etc?

There are two main ways to handle http requests: synchronously and asynchronously.
Laravel is a PHP framework and therefore uses... PHP, which is a synchronous language. This implies a page refresh for every requests you make. The point is, every PHP framework have this behavior, this is the way PHP works.
So let's answer your question: indeed, you need an asynchronous technology to make a request to the server and get the response without refreshing the page. The technolodgy of choice in this case is Javascript, which will be able to make AJAX calls.
An AJAX (asynchronous JavaScript and XML) will, as stated in its name, make an asynchronous request. But an AJAX request is just the way of doing it, it's not really a technology. Yes, javascript frameworks like Vue.js are using AJAX, but that is overkill to just make some AJAX requests.
Using Axios or even jQuery is much easier and will allow you to make a request, grab the answer and modify your page without refresh very quickly :)
[EDIT]
The process to achieve what you are looking for is pretty simple:
Use Axios or jQuery to make an AJAX call (an asynchronous request)
Handle this request with Laravel, as you do for every other request
Returns something (or not, it depends of you) to alert your user that something happened
This response will be handled by Javascript

Vue is suitable for small projects where you just want to add a little bit of reactivity, submit a form with AJAX, show the user a modal, display the value of an input as the user is typing, or many other similarly straightforward things. It's scalable and also fantastic for huge project.

Related

AJAX POST does not always occur

I have tried to incorporate AJAX into an application that I built.
The basic function is:
-The user clickes a button, which triggers JS code that makes an AJAX call that does a POST to a Servlet(sending account data).
-The Servlet(which has an EJB injected into it), communicates with an EJB through it's local interface.
-The EJB(on init) initializes a DAO object, injects an EntityManager into it, and uses that DAO object to communicate with a database through JPA (Hibernate as the provider).
-The local interface methods of the EJB return Data Transfer Objects, which are parsed in the Servlets doPost() method, and the DTO's are used to build an HTML table(String) that the Servlet responds to the AJAX call with.
-On the client side, I use that HTML table(responseText) to update a div on the page.
I have 2 questions:
1) Is using a data-centric approach to the AJAX call (returning an HTML table instead of JSON Strings) a common choice in enterprise level applications that make use of AJAX?
2)I've noticed that sometimes the POST is not even called. It seems to be intermittent. I tried to add the Cache Control header, but that doesn't seem to work. This concerns me especially when I think about eventually deploying the application to production, that maybe AJAX is not the way to go, but when it works, the application works smoothly.
1) Using AJAX to submit data or update the web page is very common. Page at a time applications are the old way web applications used to be done where you would need to reload the entire page just to update a little bit of information - which would be inefficient and not to mention would create a bad user experience. These days, updating just "Part of a page" is very common and is mostly done using AJAX, and if not WebSockets.
Now you question regarding updating the page using the servers response which is HTML - to update the page, or just get a JSON String, and manipulate the DOM (ie adding tables etc). I have used a combination of these. For example if needed to add a row to a table, you could get the server to generate the HTML using a tempting engine (groovy or similar). In addition you you need a response code, so you can package the HTML and Response code in a JSON, and send it back to the client. Any combination of these works depending on your use case.
JsonObject json = new JsonObject();
json.addProperty("responseCode", responseCode);
json.addProperty("html", html);
2) You can write a simple script to send multiple requests to the AJAX url to see if it is the server that is not able to handle the amount of requests. If it works, then you can narrow down the problem to be client side. Make sure you are not using blocking techniques. You can also setup a callback function to see if there is any response if any. AJAX Post is similar to a normal POST request, just make sure you have some indicator for the user notifying them that the request is in progress/complete.

ajax in wordpress: avoid wp-admin

I need to trigger ajax requests on wordpress frontend in order to get some custom response. lets say to get next/previous post-ID in JSON format.
In production environment the wp-admin directory is inacccessible for http requests by htaccess.
Whats the best practice to solve this problem?
Because AJAX is already used in WordPress’ back end, it has been basically implemented for you. All you need to do is use the functions available. Let’s look at the process in general before diving into the code.
Every AJAX request goes through the admin-ajax.php file in the wp-admin folder. That this file is named admin-ajax might be a bit confusing. I quite agree, but this is just how the development process turned out. So, we should use admin-ajax.php for back-end and user-facing AJAX.
Each request needs to supply at least one piece of data (using the GET or POST method) called action. Based on this action, the code in admin-ajax.php creates two hooks, wp_ajax_my_action and wp_ajax_nopriv_my_action, where my_action is the value of the GET or POST variable action.
Adding a function to the first hook means that that function will fire if a logged-in user initiates the action. Using the second hook, you can cater to logged-out users separately.

In Rails how do I use ajax? where do I put my Ajax code?

How do I get data from the database, without refreshing the page?
I dont even know where to start...
In Rails you will need to implement a page that pulls data from the DB and shows the data in whatever format you prefer, plaintext/json/xml. There's no asynchronous stuff in this part.
Ajax will be happening in frontend, the javascript part, that asynchronous connects to the webpage that you made above. jQuery's $.ajax will save you a lot of time.
You'll need to make your AJAX call from either an onload.js or a page specific js file (example.js). You'll then need to run a $.get or $.post call to the URL of the data.
Here is a pretty detailed tutorial: http://www.tutorialspoint.com/ruby-on-rails/rails-and-ajax.htm

script to auto-generate ajax url's for google analytics?

I inherited a site that's completely built using Ajax so I'm using this code to detect pageloads:
(the standard GA code)
var _gaq=[["_setAccount","UA-#######-#"],["_trackPageview"]];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.async=1;
g.src=("https:"==location.protocol?"//ssl":"//www")+".google-analytics.com/ga.js";
s.parentNode.insertBefore(g,s)}(document,"script"));
and the gaq.push:
_gaq.push(['_trackPageview', '/#pagename']);
except this is a big site with over 30 pages and I dont want to have to write in every one. is there a script that can find the paths/pagenames and put it in there for me?
I don't know Ajax OR Javascript, so apologies if this is not worded correctly.
You can use the _push function however because an AJAX request can mean so many things (sometimes a page load, sometimes a postback of data, and sometimes just a ping to make sure the user is still alive) you wouldn't want to track every XMLHttp request.
Depending on what language your site is written in, I would strongly suggest making use of some form of partial page component (php include, ASP.NET MVC Partial, ServerSide Include) etc which would stop you re-writing the code a million times if you change it.
However you will still need to edit your 30'odd pages if they are hard-coded. Or one master page if its a sensible design.
Check out this link for a sample on how to track ajax requests using the push method.

is it possible to do partial postback on web?

I read some paragraphs in a book saying that it is not possible to do a partial postback for web, even AJAX is employed. Ajax will postback everything and update only ajaxfied controls.
However, on pages I made using ajax, I used Fiddler to monitor the transportation. I found when the page initial load, it loaded everything include pictures .... However, when I click a button and do a ajax postback. I can only see the some data were loaded.... Looks like it doesn't need to reload the whole page again.
I don't know if what I see is correct? Or the book I read is correct?
Thank you guys.
That depends what you put in the term "postback".
The AJAX call will send the complete form data back to the server, just as if the form was posted normally. The server will answer with a partial response that only contains the parts of the page that should be updated.
So, the request is not partial, but the response is.
I am not sure how you are posting back from the client side. I am guessing you are using UpdatePanels. How well you 'AJAX-ify' a web page depends on what method you employ.
UpdatePanels - Read Dave Ward's posting on them - http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/
PageMethods to post back to a web service, get the data and update the DOM to display the result
JQuery and other such AJAX frameworks to post back to a web service
I am sure the link above should clear things up a bit
I'm having a hard time understanding your terminology. I'm not really sure what a "postback" is, much less a "partial" one. I do know that one of the basic ways to transmit information to an HTTP server is via a POST request, which is usually used when submitting forms. If you mean to say that the entire form is transmitted when you click a submit button, I believe you'd be right.
You also seem to be doing something with AJAX, but it's difficult to tell. The whole point of AJAX is to have dynamic data displayed on a page without resorting to reloading it. Defining what to send and what to do with the results is entirely up to your own JavaScript. So unless you're using a framework, which you don't specify, there is no such thing as "ajaxified controls."
In any case, "AJAX" usually means using the XMLHttpRequest() method of modern browsers to send data to servers without refreshing the page. When you call this function, you specify exactly what data to send. This has nothing to do with HTML forms. One caveat: if you are indeed using a library for AJAX, it might impose additional limits on how you structure information to send.

Resources