Insert data to MySQL with Ajax in Laravel - javascript

I have a JS variable which store a JSON value in my blade view and I want to insert it to MySQL in Laravel project. But I don't know how to write it right. This is what I tried in my blade view:
<body>
<div id="fb-editor"></div>
<div id="saveToDatabase">
<button id="saveBtn" type="button">Save To Database</button>
</div>
</body>
<script>
var formBuilder = $('#fb-editor').formBuilder();
$("#saveBtn").click(function() {
var mFormData = formBuilder.actions.getData(); //my JSON data
$.ajax({
type: 'POST',
url: '/saveToDatabase',
data: {"mFormData":mFormData}
}).done(function (msg) {
alert("Data saved!");
});
});
</script>
But when I run it, it appear error said: jquery.js:8630 POST http://localhost/saveToDatabase 404 (Not Found).
How I can fix this?
Thank you very much!

First, enter your database details on .env file.
You need to use two routes. One for the blade file to render and another for the api request.
On routes/web.php, define your route,
Route::get('/', function(){ return view('app');});
Create app.blade.php in resources/views/ folder with your HTML code.
On routes/api.php, define your route like this
Route::post('saveToDatabase','HomeController#saveToDb')
Next, you need to create saveToDb method on the HomeController.
Open App\Http\Controller\HomeController.php
Create a new method
public function saveToDb()
{
// Database Insertion Code goes here
}
Laravel Provide CSRF Protection to the POST request. So add Exception to this route by adding it in the App\Http\Middleware\VerifyCSRFToken.php
protected $except = [
'api/*'
];
For the insertion operation, we can do this with the help of the model.
So first create Form.php in App\ folder.
Inside that, we specify the fields of the database.
<?php
use Illuminate\Database\Eloquent\Model;
class Form extends Model
{
protected $fillable = [
"key", "data"
];
protected $hidden = [];
}
Next, we can use this model to insert data to the Form table.
In your HomeController.php at the top
use App\Form;
use Request;
Now we can update the saveToDb function that we write before.
public function saveToDb()
{
// Request all the post data
$req = Request::all();
// From that post data store key and data part to form table
Form::create($req);
}
If you have any issue in route, controller or model. Refer Laravel official docs: https://laravel.com/docs/5.8/routing
And this one is also useful to get started to laravel. https://laracasts.com/series/laravel-from-scratch-2018

The route is not selected correctly. http://localhost/saveToDatabase is not find for do something

Related

Laravel : How to pass variable from View (javascript) to Controller? [duplicate]

This question already has an answer here:
How to send a variable from JS to my Laravel Controller
(1 answer)
Closed 2 years ago.
I'm extremely new to Laravel (level -0). Our backend guy used it for a web app that we are developing. So after googling i finally figured out how to pass variables from Controller to View. Now i need to pass from View to Controller. I saw that there are some question regarding this but the way its been asked/answered i really dont understand. So what i have now is
Controller :
public function index()
{
$title = "Congratulations";
$messageOne = "You've learned something new!";
$messageTwo = "Remember all the tips!";
return view('pages.index',compact('title','messageOne'));
}
View (where i want the string to be displayed) :
<div>
{{$title}}
<br>
{{$messageOne}}
</div>
These messages (messageOne, and others) will change depending on button click which is controlled via js. I was thinking in the js function i could have a variable set like :
$('thebutton').click(function(){
var buttonclicked = "learning";
})
then send that variable to Controller then in Controller (im not sure how to code it but..) check what the string of buttonclicked variable is and depending on the string return to View the message string. From searches i have to also tweak the Route (which im not sure about as well)?
is that flow possible? otherwise, advice on how i can do this will be appreciated.
UPDATE
the suggested link to another question in the comment helped which answers the question. also, all the answers helped in some way so im not sure which to choose. Do i have to choose only 1?
One way you can send it using the $.ajax() or the other way you can send it using query parameters like so:
<a href={{ route('route-name', ['param 1' => 'Param 1 Value', ......]) }}Click me!</a>
Then in your route define your route as following.
Route::get('/url/{param1}/{param2}/.....', 'ControllerName#MethodName')->name('route-name');
Then go to your controller and define your function like so:
use Illuminate\Http\Request;
public function functionName(Request $request){
// Get your variables from $request
$param1 = $request->param1;
$param2 = $request->param2;
}
In JS you should use ajax for passing data from view to controller for example
$('thebutton').click(function(){
var buttonclicked = "learning";
//her xyz your url
$.get( "xyz", { value: buttonclicked } )
.done(function( data ) {
//write your code after success
});
});
then in controller get the value from ajax request
public function test(Request $request){
dd($request->value);
}
View to Controller. You can post data via ajax call.
or Submit the form data to controller form post method
<form method="post" action="/controller" />
<input type="text" value="100" id="txt" name="txt" />
<button type="submit"/>
</form>
Once submit data 100 go to controller. By this way we can pass data to controller.
JS to Controller Pass data
var pincode = $('#pincode').val();
$.ajax({
type:'POST',
url:"{{ route('post_data') }}",
data:{"_token": "{{ csrf_token() }}","postal":pincode},
success:function(data){
//Success code
}
});
Controller code like below
public function post_data(Request $request)
{
$postal_code = addslashes($request->all()['postal']);
}
Hope it helps

How does an MVC 5 view request with parameter data a controller to launch another view

This is an MVC 5 project. I am having a problem getting a second view to be shown from a parent view. My parent view is a purchase order which has line items. The line items are to be added by launching a second view from the parent view. Both views use the same controller but each has their own action method.
I use the below JavaScript from the PurchaseOrder view to pass data to PurchaseOrderAddItem view (child view):
$(document).ready(function () {
$('#PurchaseOrderLineItemAddId').click(function () {
var aPurchaseOrderViewModel = #Html.Raw(Json.Encode(Model));
var selectedVendorText = $('#ddlvendors option:selected').text();
var selectedVendorValue = $('#ddlvendors option:selected').val();
var LineItemReqJsonObj = {};
LineItemReqJsonObj.PurchaseOrderId = aPurchaseOrderViewModel.PurchaseOrderId;
LineItemReqJsonObj.VendorText = selectedVendorText;
LineItemReqJsonObj.VendorValue = selectedVendorValue;
var dataToPass = '{aLineItemReqJsonObj: ' + JSON.stringify(LineItemReqJsonObj) + '}';
$.ajax(
{
type: "POST",
//data: '{ aPurchaseOrderViewModel: ' + JSON.stringify(aPurchaseOrderViewModel) + ' }',
//data: aPurchaseOrderViewModelStr,
data: dataToPass,
url: '#Url.Action("PurchaseOrderAddItem")',
contentType: "application/json; charset=utf-8",
datatype: "json"
})
.done(function (aNewLineItemViewModel) {
AddNewLineItemReceived(aNewLineItemViewModel);
})
.fail(function (xhr) {
alert('error', xhr);
});
});
});
Below is the action method in the controller which receives the above ajax request:
[HttpPost]
public ActionResult PurchaseOrderAddItem(LineItemReqJsonObj aLineItemReqJsonObj)
{
LineItemViewModel aLineItemViewModel = new LineItemViewModel();
aLineItemViewModel.PurchaseOrderId = aLineItemReqJsonObj.PurchaseOrderId;
aLineItemViewModel.VendorId = Convert.ToInt32(aLineItemReqJsonObj.VendorValue);
return View(aLineItemViewModel);
}
Below is the class in the controller which gets data filled into it as it is passed in from the JavaScript:
public class LineItemJsonObj
{
public string PurchaseOrderId {get;set;}
public string VendorText { get; set; }
public string VendorValue { get; set; }
};
The below diagram illustrates what I am trying to do:
As the diagram shows, I am unable to get the PurchaseOrderAddItem View to be shown. How do I get the PurchaseOrderAddItem View to show, receiving parameter data, after the PurchaseOrder View has invoked the PurchaseOrderAddItem Action From the controller?
Thanks in advance.
-- UPDATE 2/17/2020 1:38PST--
I am probably incorrect in thinking the controller could start the PurchaseOrderAddItem View which when
closed could get the resulting new model data somehow back to the PurchaseOrder
View with the JavaScript that started this.
I am beginning to think this approach using the JavaScript $Ajax to
reach the controller is not the right way to do this. I'm checking now to see
if maybe I should of just loaded another web page from the PurcahseOrder View
with parameter data to create a new PurchaseOrderAddItem View. The challenge here though would
be to probably pack up the entire PurchaseOrder view model data to go with the
PurchaseOrderAddItem View request. If I have the entire PurchaseOrder View Model
data when I exit the PurchaseOrderAddItem View I will be able to load a new
PurchaseOrder View and pass it all the data that was in the first instance so it
is repopulated to include the newly added line items. I'm not sure this is
the right way to do this. I have not seen any examples yet of how this type of
application view presentation problem is handled. I would appreciate it if anyone can
point me to any internet articles that perhaps cover how to design this type of
MVC application. This is very easy to do in desktop apps but web development
with MVC makes this very different and needing a lot more work than something
in WPF or WinForms.
The solution for me in this case was to use the TempData dictionary object to help transport data from the PurchaseOrder View request to the LineItem View and back. There is no sensitive data in this data transport so using TempData should be fine. Additionally, to launch the LineItem view to create a new Line Item worked better for me to just us the standard submit action from within an Html.BeginForm block. The standard post operation provided by the submit button is what I used in this case rather than a button to run $.Ajax code in a JavaScript. Ajax was really not needed in this case since the whole PurchaseOrder View was to be replaced by the LineItem create view.

How to update both a responsive front-end and the database?

I am looking for ways to update the cart in my toy e-commerce application without having to reload the page and I was following this pen.
For example the code that is updating a product's quantity is the following:
$('.product-quantity input').change( function() {
updateQuantity(this);
});
It works nicely but the database is not updating of course at this point.
I was wondering what is the best way to update both the front-end and the database with products' quantities or similar operations? I am probably looking for AJAX but not sure what the latest best practices are (ideally with as less JS as possible).
Your updateQuantity() function has to make an ajax call to a method in your controller that handles the change in the database and responds to either json or js to manipulate the dom.
function updateCart(e){
$.ajax({
type: "patch",
url: 'your_route_to_method', //point to the route that updates the item
data: {
your_resource_scope: { quantity: e.value } //sanitize input in strong params
},
success: function (response) {
//response is the json you get back from your controller
//handle the logic of whatever happens in the dom after you update the quantity
}
});
}
I'd suggest attaching the id of the product you want to update to the input's parent so you can pass it to your route and remember to pass the value under the required scope so you can sanitize the input in your controller via strong_params.
In your controller:
def update
respond_to do |format|
if #your_resource.update(your_resource_params)
format.json { render json: { key: value } } #build the json you want to return
else
#handle failiure
end
end
If you decide to respond in js instead of json, you need to create a view with the same name as your method with a .js or .js.erb extension (instead of .html/.html.erb) and handle the successful response in js. In this view you have access to all the instance variables declared in your method. For example:
# => update.js.erb or your_custom_method_name.js.erb
$('#resource_#{ #your_resource.id }_price').replaceWith('<p>#{ #your_resource.quantity * #your_resource.price }</p>');
If you go this route, remember to delete the success part of your ajax call.

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.

Thymeleaf page refresh followup - Now with AJAX

As a followup to my earlier question about using Thymeleaf and preventing page refresh:
http://forum.thymeleaf.org/Preventing-page-refresh-Thymeleaf-amp-Spring-MVC-td4029155.html
Basically I had a working Spring MVC app that uses Thymeleaf to save form data. When the user saves the data the page would refresh (since I wanted to leave them on the page for more edits) and I wanted to eliminate the page refresh.
I have coded up some Javascript to use JQuery Ajax to post the data to my Spring MVC Controller. The trick seemed to be to not use a submit button, just a regular button and bind a JS function to it for sending the data to the server.
It all seems to work perfectly, but I want to make sure I understand what is happening. In particular I'm wondering if Thymeleaf is now redundant. I don't think it is because when I initially load the page Thymeleaf is still bound to the data bean. From using the debugger on the server side in the controller it looks like the post request calls the mapped method and passes in the data to the model.
I would appreciate your comments on whether or not this is the correct way to accomplish this.
Finally, how do I handle an error, say for example the repository fails to persist the data for any reason?
Thanks very much.
Here are the important parts of the form:
<FORM id="adminDataForm" action="#" th:action="#{/admin_ajax}" th:object="${adminFormAjax}" method="post">
<input type="button" value="Save Changes" id="post" onClick="sendData()" />
Here is the Javascript:
function sendData()
{
$.ajax(
{
type: "POST",
data: $("#adminDataForm").serialize(),
cache: false,
url: "/admin_ajax",
success: function(data)
{
alert("Your changes have been saved");
},
error: function()
{
alert("Error - Data not saved");
}
});
}
Here is the controller:
#SessionAttributes("adminFormAjax")
#Controller
public class TestController
{
final static protected long INDEX_RA = 2L;
#Autowired
private AdminDataRepository rep;
#RequestMapping(value="/admin_ajax", method=RequestMethod.GET)
public String adminFormAjax(Model model)
{
AdminData ad = rep.findById(INDEX_RA);
// If there is no configuration record, create one and assign the primary key
if(ad == null)
{
ad = new AdminData();
ad.setId(INDEX_RA);
}
model.addAttribute("adminFormAjax", ad);
return "adminFormAjax";
}
#RequestMapping(value="/admin_ajax", method=RequestMethod.POST)
public #ResponseBody AdminData adminSubmit(#ModelAttribute("adminFormAjax") AdminData ad, Model model)
{
rep.save(ad);
model.addAttribute("adminFormAjax", ad);
return ad;
}
}
So breakdown of answer.
Thymeleaf not redundant, it will still render the HTML page prior to sending to client. Ajax just does the further processing for you on client side.
You can use submit button as well, you just need to ensure your form is properly structured and you have javascript listening for your submit button click e.g.
$("#submitbutton").on('click', function (){//do stuff});
You handle any and all exceptions/issues within your Ajax controller as you would with standard controller. You need to separate issue handling at different levels. e.g. respository level issues should be managed at rep level, controller/pojo should be at controller level (or pojo if you using one for processing). You should also be capturing any exceptions through a global medium (e.g. ControllerAdvice).
Any issues/errors you pick up you should be communicating back via your return call in adminSubmit, and managing the relevant client response in ajax.

Categories