Implementing Jquery ajax get request in laravel - javascript

Am more of an angular person so i do not really do well with jquery. I have a project i took over from someone and i have to implement a get request to my controller and append returned data to view. I know this is vague but i would appreciate any help.
<tbody>
#foreach($restaurant_meals as $meal)
<tr>
<td>
{{$meal->name}}
</td>
<td>
${{$meal->price}}
</td>
<td>
<i class="fa fa-plus-circle"></i>
</td>
</tr>
#endforeach
</tbody>
This is my view.
This is my ajax request.
<script type="text/javascript">
$(documnent).ready(function(){
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/addtocartid' + id, // This is the url we gave in the route
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
console.log(response);
}
});
});
Then my Controller would be
public function getaddtoCart(Request $request, $id)
{
$product = Product::find($id);
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->add($product, $product->id);
$request->session()->put('cart', $cart);
return redirect()->route('home');
}
Any help would be appreciated

Your problem is with the concatenation of the id in the URL. It is adding the extra numbers in the URL pattern.
$(documnent).ready(function(){
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/addtocartid', // This is the url we gave in the route
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
console.log(response);
}
});
});
Like /addtocartid1 instead of /addtocartid/1
Ideally that should be removed. You are already sending the parameters by data property

Related

passing data from laravel view to controller via ajax onchange event

I have a dropdown list in a blade view. I want to send the value of the selected item to the controller immediately onchange. I have 2 routes in web.php:
Route::get('/plots', 'PlotController#index');
Route::get('/plots/{testId}', 'PlotController#getData');
The first one populates the dropdown list. The second one is supposed send the value of the dropdown list to the controller, which pulls stuff from mysql and sends the data back to the view, which draws a chart. I can get the dropdown to populate ok, but I can't figure out how to send the selected value to the controller. I'm trying to use ajax to do it like this:
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
console.log("testId=" + testId);
$.ajax({
url: 'plots/' + testId,
type: 'get',
dataType: 'json',
success: function(response) {
console.log("success");
}
});
});
});
The testId output to the console is correct but it never makes it to the controller. The error I see in the console is:
GET http://homestead.test/plots/1 500 (Internal Server Error)
I'm pretty new to laravel and find it extremely confusing. Can anyone explain the correct way to do this?
EDIT:
After testing and confirming Rian's answer as correct, I then tried to implement the real code, which of course is much more complicated. Instead of the controller returning the input test_id:
return $request->test_id;
It actually returns a more complex structure:
return view('plot')
->with('measurements',json_encode($result))
->with('events',json_encode($timeline))
->with('limits',json_encode($limits));
When I uncomment the original controller code, including the return section above, it seems to affect the ability of the controller to return anything at all. Here is the first few lines of the PlotController getData method:
public function getData(Request $request) {
Log::debug("made it to PlotController.php#getData");
Log::debug("test_id="+$request->testId);
And here is the log output:
[2020-02-23 16:43:52] laravel.DEBUG: made it to
PlotController.php#getData
The second line does not output anything. Here is what I see in the javascript console after I select an item from the dropdown list:
testId=49 jquery.min.js:2 GET
http://homestead.test/get-data-by-id?test_id=49 500 (Internal Server
Error)
Any ideas?
The easiest way is to get the data in Laravel Request. At least that's how I do it.
So your route shouldn't contain any parameter for that.
Your route will look like this:
Route::get('get-data-by-id', 'PlotController#getData')->name('get.data.by.id');
Your ajax should be like this:
$(document).on('change', '#sel_test',function(){
var testId = $(this).val();
$.ajax({
type:'GET',
url:"{{ route('get.data.by.id') }}",
data:{'test_id':testId},
success:function(data){
console.log(data);
}
});
});
In your controller's getData() function just use Laravel Request to fetch the data.
public function getData(Request $request)
{
// You can return the ID to see if the ajax is working
return $request->test_id;
}
Make it post from Get for easier
At Web.php
Route::post('/list/plots', 'PlotController#getData')->name('getData');
At Blade file Ajax Request :
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
var url = '{{ route("getData")}}';
var token = "{{ csrf_token()}}";
$.ajax({
method:"post",
url: url,
data:{testId:testId,_token:token}
dataType: 'json',
success: function(response) {
console.log("success",response);
}
});
});
});
At Controller :
public function getData(Request $request){
$testId = $request->testId;
// Write your logic here
}
Try this. Hopefully work for you

How to call a route & send data with javascript

I'm working with Laravel 5 and I've the following code
HTML
<div id="row">
<textarea class="form-control" rows="3" id="comment" placeholder="Update your Post"></textarea>
</div>
<a href="#" id="btn-post" dusk="postButton" class="btn btn-primary" role="button" data-toggle="modal" data-target="#addPost">
<span class="ion-plus-circled"> Post</span>
</a>
JS
$(document).ready(function(){
$("#btn-post").click(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var comment = $('textarea#comment').val();
var postData = {
post_content: comment.val();
groupId: window.location.href.split("/")[4] // hack to get group id
}
console.log(postData);
$.ajax({
type: "POST",
url: "/post",
data: JSON.stringify(postData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, status){
$("#addPost").modal('toggle');
//window.location.href = data.redirectTo;
}
});
});
});
web.php
Route::post('post', 'GroupController#post');
GroupController.php
public function post(Request $request){
$post_content = $request->input('post_content');
$userId = Auth::user()->id;
$groupId = $request->input('groupId');
$post = PostGroup::firstOrNew(['group_id' => $groupId, 'post_content' => $post_content]);
$post->user_id = $userId;
$post->save();
$redirectPath = '/groups/' . $groupId;
return response()->json(['message' => 'Your post have been published! Take a look at',
'redirectTo' => $redirectPath]);
}
What I want to do is to call the javascript function btn-post at the click of the link-button Post. This function takes the content of the textarea (which I don't know if I wrote correctly) and sends it to the GroupController using the same javascript function, to the route "/post", calling the function post (as defined in web.php), but for some reason it doesn't work, and I don't know where I was wrong (I think the problem is in the javascript function, as if it weren't called).
You have a syntax and a logic error in your Javascript here:
var comment = $('textarea#comment').val();
var postData = {
post_content: comment.val();
groupId: window.location.href.split("/")[4] // hack to get group id
}
Logic error: you assign textarea value to the var comment. Then 2 lines after that, you call comment.val() on it, although it's a string at this point. No need to call .val() again.
Syntax error: you shouldn't use ; within the postData JSON definition. You separate JSON fields with a comma.
This is the fix for the above 2 problems:
var postData = {
post_content: comment, // <----
groupId: window.location.href.split("/")[4] // hack to get group id
}
I suggest you start using developer tools to debug your Javascript

ng-repeat not reflecting when the source variable gets modified

I have the following angularJs code. When my source data changes, my ng-repeat does not update my view. I looked at other posts and added $scope.$apply(); , $scope.$digest(); at the end of my ajax success callback, but it did not help. The idea is that the page will have an empty table in the begining and after the ajax call onReady() it will populate the rows with data. Could someone point me at what I am missing here or a better way to achieve the same
JS:
(function() {
var app = angular.module("jmeter-module", []);
app.controller('JmeterTableController', ['$scope', function($scope){
$scope.data = [];
$(document).ready(function(){
var url = "jmeterTableData.html";
fetchTableData(url, 10, 25);
});
function fetchTableData(url, minAge, maxAge){
$.ajax({
type: "GET",
url: url,
data: { minAge : minAge,
maxAge : maxAge },
datatype: "json",
success: function(data){
/*If I try to print data here, I see the values rightly getting returned*/
$scope.data = data;
},
error: function(e){
console.log(e);
}
});
}
}]);
})();
JSP:
<div id="buildGroupsParentDivId" ng-controller="JmeterTableController as row">
.
.
.
<tbody id="jmeter-table-content" >
<tr ng-repeat="val in row.data">
<td><img title="History" src="/images/history.png" width="20" height="20"></td>
<td><input type="checkbox" value="save"></td>
<td>{{val.firstName}}</td>
<td>{{val.lastResult}}</td>
</tr>
</tbody>
the problem is with the execution of $.ajax outside of the scope of Angular's digest cycle. You could get this working with $scope.$apply, but since you're already using Angular it's better to use the AngularJS xhr helper methods:
https://docs.angularjs.org/api/ng/service/$http
// Simple GET request example :
$http.get('/someUrl').
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Django data updation in the table

I am using Django to enter some data into my database. After entering the data I want to edit it. Now, what I am trying is, the user should not go to any other page to change the data. So I have implemented a javascript method which edits the text on the front end.
How do I reflect the changes made by the user in the database?
The related code is given below:
<html>
{% csrf_token %}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<table id="table">
<tr>
<th>Name</th>
<th>Phone Number</th>
</tr>
{% for record in queryset %}
<tr>
<td onClick="clickable(this)"> {{record.first}} </td>
<td onClick="clickable(this)"> {{record.second}}</td>
</tr>
{%endfor%}
</table>
<script>
function clickable(ele)
{
var value = prompt("Enter the details");
if(value)
{
ele.id='edited'
ele.innerHTML = value;
//I want to send the request to my django view to edit the database here
//The data has been updated.
}
You should send a Ajax request to your server using jQuery you are using. with Ajax request request you should send your updated data .
Simple Ajax request can be .
$('#click_place').click(function() { // when click is placed
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the content here Ex. {'name': 'test', 'phone': '123'}
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // request url
success: function(response) { // on success..
// display your message
}
});
return false;
});
You can follow How to POST a django form with AJAX & jQuery .
http://coreymaynard.com/blog/performing-ajax-post-requests-in-django/ .
Edit :
You can simply call below function at any event .
function myajaxhit() {
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the content here Ex. {'name': 'test', 'phone': '123'}
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // request url
success: function(response) { // on success..
// display your message
}
});
}
just call myajaxhit() at any place . Please change it as per your requirement .

How to redirect response from ajax request

I need to redirect to a page from response. I made a ajax call and can handle success. There is html page in response, but how to redirect it to that page.
Here's my code.
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = response;
}
});
});
Not using ajax would make this easier:
<form type="POST" action="xyz.json">
<label for="id">Enter ID:</label><input id="id" name="id">
<button type="submit" id="launchId">Send</button>
</form>
If you really want to use ajax, you should generate a distinct server response, containing only the HTML parts you want to update in your page or actual JSON.
If you insist on using the response which you currently get, the appropriate way of dealing with it would be document.write:
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'html', // it's no JSON response!
success: function(response) {
document.write(response); // overwrite current document
},
error: function(err) {
alert(err+" did happen, please retry");
}
});
Please try this.
var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
Your response is an object containing the full HTML for a page in the responseText property.
You can probably do $(body).html(response.responseText); instead of window.location.href = ...; to overwrite the current page content with what you got a response.
...
complete : function(response) {
$(body).html(response.responseText);
}
But i suggest you don't and there could be style and other conflicts with whats already there on the page.
In your HTML add a div with id as 'content', something like this
<div id='content'/>
Since your response is html in your complete function append the content into the div like this -
complete : function(response) {
$('#content').append(response.responseText);
}
Let me know if you still face issues.
try this
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = '/yourlocation?'+response;
}
});
});

Categories