I have the following code with an if statement depending if a user has saved an article or not. I'm simply trying to delete the article from the database using jquery. I unsure where im going wrong? help is much appreciated!
View:
<form action="{{URL::route('article-delete')}}" method="post" id="article_one_delete">
<div class="form-group">
<input type="hidden" name="first_desc" value="{{$firstrow->description}}" class="form-control">
</div>
<div class="form-group">
<input type="hidden" name="first_title" value="{{$firstrow->title1}}" class="form-control">
</div>
<button type ="button" id="Recodelete" class="btn btn-success btn-xs">UnSave</button>
{{Form::token()}}
</form>
Route:
Route::delete('/home/', array( 'as' => 'article-delete',
'uses' => 'HomeController#deletearticle'));
Controller:
public function deletearticle(){
$firsttitle = Input::get('first_title');
$articledelete = UserSaveArticle::where('user_id', Auth::id()
->where ('user_save_articles.chosen_title', $firsttitle))->delete();
return true;
JQuery:
$(document).ready(function(){
$('#Recodelete').on('click', function(){
var article_one_delete = $('#article_one_delete').serializeArray();
var url_d = $('#article_one_delete').attr('action');
$.get(url_d, article_one_delete, function(data){
console.log(data);
});
});
});
You should define right route for DELETE article, like this:
Route::delete('/article/{id}', ['as' => 'article-delete', 'uses' => 'HomeController#deleteArticle']);
In the HomeController $id variable (article ID) will be available as a method parameter:
function deleteArticle($id)
{
…
}
In PHP side you defined DELETE route, it means you should make DELETE request on JS side using the ajax method:
$.ajax({
url: '/article/' + articleId,
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
Related
I want to pass student Id in my controller action, I used JsonResult action, I catch student id but can't pass in action,
this is my JavaScript code ,
<script type="text/javascript">
$(document).ready(function () {
$("#sId").change(function(){
var studentId = $(this).val();
debugger
$.ajax({
type:"post",
url:"/Department/GetDeptName/" + studentId,
contentType:"html",
success:function(response){
debugger
$("#dId").empty();
$("#did").append(response);
}
})
})
});
</script>
And I have a Dropdown list, I pass my list fron database using ViewBag. When I select a student name then need to pass his/her department name. This is the view code
<div class="row">
<div class="col-md-6 mb-4">
<label asp-for="Name" class="control-label">Student Name</label>
<select asp-for="Id" class="form-control" id="sId"
asp-items="#(new SelectList(#ViewBag.messageStudent,"Id", "Name"))">
</select>
</div>
<div class="col-md-6 mb-4">
<label asp-for="DeptName" class="control-label">Department Name</label>
<input asp-for="DeptName" id="dId" class="form-control mb-3" type="text" placeholder="Dept Name" disabled>
</div>
<input type="hidden" asp-for="Id" name="Id" id="DeptName" />
</div>
This is my controller code that is passed a list from database to View
public async Task<IActionResult> DropDown()
{
var model = _scope.Resolve<FormModel>();
await model.LoadStudenDataAsync();
var studentList = model.StudentList.ToList();
studentList.Insert(0, new Student { Id = 0, Name = "Select Group" });
ViewBag.messageStudent = studentList;
return View(model);
}
Now I need to pass student id from view page, if i pass student id then I solve my problem,
This is my JsonResult Action
public async Task<JsonResult> GetDeptName(int studentId)
{
var model = _scope.Resolve<FormModel>();
if (ModelState.IsValid)
{
await model.DeptList(studentId);
}
return Json(model);
}
Please help me anyone how to pass student id,Thanks in Advance
you have to use get ajax since you are not posting any data in the request body. And change data type to json since you are returning json
$.ajax({
type:"GET",
url:"/Department/GetDeptName/" + studentId,
dataType: 'json',
....
and action
[Route("~/Department/GetDeptName/{studentId}")]
public async Task<JsonResult> GetDeptName(int studentId)
and fix route config
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
but if you use old net that doesn't support attribute routing then just change ajax and leave the action as it is now
$.ajax({
type:"GET",
url:"/Department/GetDeptName?studentId=" + studentId,
dataType: 'json',
....
Shopping cart with many items how to remove any item asynchronously with JavaScript this is my work so far. Can anyone improve on this?
your help would be greatly appreciated. Have a great day
Ok so this works if you remove items from the top of the list but fails if you remove items from some other place.
The problem seems to be that the form names are all the same "remove" without any indexing.
Problem is I'm not sure how to proceed with this.
document.forms['remove'].onsubmit = () => {
let formData = new FormData(document.forms['remove']);
fetch('/sales/cart?handler=RemoveItem', {
method: 'post',
body: new URLSearchParams(formData)
})
.then(() => {
var url = "/sales/cart?handler=CartPartial";
console.log(url)
$.ajax({
url: url,
success: function (data) {
$("#exampleModal .modal-dialog").html(data);
$("#exampleModal").modal("show");
//alert('Posted using Fetch');
}
});
});
return false;
}
<pre>
#foreach (var item in Model.Items)
{
<form name="remove" method="post">
<h4 class="text-left text-body">#item.Price.ToString("c")
<button class="btn btn-sm" title="Trash"><i style="font-size:large"
class="text-warning icon-Trash"></i></button>
</h4>
<input type="hidden" asp-for="#Model.Id" name="cartId" />
<input type="hidden" asp-for="#item.Id" name="cartItemId" />
</form>
}
</pre>
Update
----------
New markup
I added an index to the id and included an onclick event.
<form method="post" id="#i" onclick="removeItem(this.id)">
<button class="btn btn-sm" title="Trash">Item One</button>
<input type="hidden" asp-for="#Model.Id" name="cartId" />
<input type="hidden" asp-for="#item.Id" name="cartItemId" />
</form>
and create a new function that captured the form id including it in a constant.
<script>
function removeItem(formId) {
const form = document.getElementById(formId);
form.onsubmit = () => {
let formData = new FormData(form);
fetch('/sales/cart?handler=RemoveItem', {
method: 'post',
body: new URLSearchParams(formData)
})
.then(() => {
var url = "/sales/cart?handler=CartPartial";
console.log(url)
$.ajax({
url: url,
success: function (data) {
$("#exampleModal .modal-dialog").html(data);
$("#exampleModal").modal("show");
//alert('Posted using Fetch');
}
});
});
return false;
}
}
</script>
If anybody can improve on this please post it here.
Thanks.
Updates code behind Cart.cshtml.cs
using System;
using System.Threading.Tasks;
using Malawby.Models;
using Malawby.Services.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Malawby.Pages.Sales
{
public class CartModel : PageModel
{
private readonly ICartRepository _cartRepository;
public CartModel(ICartRepository cartRepository)
{
_cartRepository = cartRepository ?? throw new
ArgumentNullException(nameof(cartRepository));
}
[BindProperty]
public Cart Cart { get; set; } = new Cart();
public const string SessionKeyName = "_Name";
public string SessionInfo_Name { get; private set; }
public void OnGetAsync()
{
}
public async Task<PartialViewResult> OnGetCartPartialAsync()
{
var userName = GetUserName();
if (userName != null)
{
Cart = await _cartRepository.GetCartByUserName(userName);
}
return Partial("_ToCart", model: Cart);
}
private string GetUserName()
{
return HttpContext.Session.GetString(SessionKeyName);
}
public async Task OnPostRemoveItemAsync(int cartId, int cartItemId)
{
await _cartRepository.RemoveItem(cartId, cartItemId);
}
}
}
Update 2
This is the modified code I used. This is the error in the console.
XML Parsing Error: no root element found Location: localhost:44331/sales/cart?handler=RemoveItem Line Number 1, Column 1
There is no error on the page just nothing happens on the click of the trash can.
<script type="text/javascript">
function removeItem(cartItemId, cardId) {
var removeUrl = "/sales/cart?handler=RemoveItem";
$.post(removeUrl,
{
cartItemId: cartItemId,
cardId: cardId
})
.done(function (data) {
alert(data); //usually return true or false if true
remove card
$('#card_' + cardId).remove();
});
}
</script>
I am not familiar with asp.net core, but I will show how I usually do it without focusing on syntax.
first on the view no need to add multiple form but should use card id as index and delete button sent selected index like this:
#foreach (var item in Model.Items)
{
<div id="card_#item.cardId">
<h4 class="text-left text-body">#item.Price.ToString("c")
<button class="btn btn-sm" onclick="removeItem('#item.cardId') title="Trash"><i style="font-size:large"
class="text-warning icon-Trash"></i></button>
</h4>
</div>
}
then the script function will call remove api and remove selected card with no need to re-render the page:
<script type="text/javascript">
function removeItem(cardId) {
var removeUrl = "your apiUrl";
$.post( "removeUrl", { cardId: cardId })
.done(function( data ) {
alert( data ); //usually return true or false if true remove card
$('#card_'+ cardId).remove();
});
}
</script>
Description
I have a table, where i collect values from checkboxes with JavaScript. This values should be send to a protected API route in a Laravel backend.
I use the standard Laravel auth setup (out of the box).
Question
What do I have to send with the JavaScript post request for authentication and how do i do that? Can i add a auth token or something like that to the headers?
At the moment i get the reponse:
"This action is unauthorized".
exception: "Symfony\\Component\\HttpKernel\\Exception\\AccessDeniedHttpException"
Edit
At the current point of my research the api token seems to be a simple solution for my case. But i can't figure out how to attach the api token to the JavaScript post request.
Thats the JavaScript function for collecting the values storing them in objects.
import SaveData from "../api/SaveData";
export default async function SaveMultipleReports() {
const table = document.getElementById("reports-dashboard");
const rows = table.querySelectorAll("div[class=report-tr]");
let reports = [];
for (const row of rows) {
const checkbox_visible = row.querySelector("input[name=visible]")
.checked;
const checkbox_slider = document.querySelector(
"input[name=show_in_slider]"
).checked;
const report = {
id: row.id,
visible: checkbox_visible,
show_in_slider: checkbox_slider
};
reports.push(report);
}
console.log(reports);
const response = await SaveData("/api/reports/update", reports);
console.log(response);
}
And that is the SavaData function:
export default async function SaveData(api, data) {
const token = document
.querySelector('meta[name="csrf-token"]')
.getAttribute("content");
const url = window.location.origin + api;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-TOKEN": token,
Accept: "application/json"
},
body: JSON.stringify(data)
});
const result = await response.json();
return result;
}
And thats the line in the api.php:
Route::middleware("can:administration")->post("reports/update", "ReportsController#UpdateAll");
The whole repo is here.
Thanks for your time in advance :)
Edit 2
For now i managed it without JavaScript. Put all the values, i want to update in form and load a hidden input for the ID of every object (the ID is needed for the controller afterwards).
Thanks to this post.
{!! Form::open(["route" => ["admin.reports.multiupdate"], "method" => "PUT", "class" => "report-table"]) !!}
... // some HTML
#foreach ($reports as $report)
<div class="report-tr">
<input type="hidden" name="reports[{{$loop->index}}][id]" value="{{$report->id}}">
<div class="td-name">
<p class="td-text">{{$report->name}}</p>
</div>
<div class="td-flex">{{$report->body}}</div>
<div class="tr-wrapper">
<div class="checkbox-visible">
<div class="checkbox-container">
<input class="checkbox" type="checkbox" name="reports[{{$loop->index}}][visible]" value="1" checked>
<span class="checkmark"></span>
</div>
<label class="table-label" for="visible">Sichtbar</label>
</div>
<div class="checkbox-slider">
<div class="checkbox-container">
<input class="checkbox" type="checkbox" name="reports[{{$loop->index}}][show_in_slider]" value="1"
{{($report->show_in_slider == 1 ? "checked" : "")}}>
<span class="checkmark"></span>
</div>
<label class="table-label" for="show_in_slider">Im Slider</label>
</div>
<div class="td-buttons">
...
#endforeach
<button class="floating-save">
#svg("saveAll", "saveAll")
</button>
{!! Form::close() !!}
And a snippet from the Controller:
public function MultipleUpate(ReportUpdate $request)
{
$reports = $request->input("reports");
foreach ($reports as $row) {
$report = Report::find($row["id"]);
// giving the checkbox 0, if it isn't checked
$isVisible = isset($row["visible"]) ? 1 : 0;
$inSlider = isset($row["show_in_slider"]) ? 1 : 0;
$report->visible = $isVisible;
$report->show_in_slider = $inSlider;
$report->new = false;
if ($report->save()) {
$saved = true;
}
}
if ($saved == true) {
$request->session()->flash("success", "Änderungen gespeichert!");
} else {
$request->session()->flash("error", "Das hat nicht geklappt!");
}
return back();
The ReportUdpate function contains only that:
public function authorize()
{
return true;
}
public function rules()
{
return [
"visible" => "nullable",
"show_in_slider" => "nullable"
];
}
You are talking about authentication but using an authorization middleware. There is a difference between the two.
Read about it here: https://medium.com/datadriveninvestor/authentication-vs-authorization-716fea914d55
With that being said, what you are looking for is an authentication middleware that protects your routes from unauthenticated users. Laravel provides a middleware called Authenticate out of the box for this specific purpose.
Change your route to be like so:
Route::middleware("auth")->post("reports/update", "ReportsController#UpdateAll");
I am trying to retrieve data from a Bootstrap form element, and save it to a PostgresSQL database using Express and Knex. There are no errors when I run the route; however, the data from the form is saved as null. Here is my form element (I'm using React):
render() {
return (
<form>
<div className ="form-group">
<label>Add a Note:</label>
<textarea className="form-control" name="note" rows="5">
</textarea>
</div>
<button onClick={this.handleClick} className="btn btn-primary"
type="submit">Submit</button>
</form>
)
}
Here is my fetch to the POST route:
handleClick(e) {
e.preventDefault()
fetch('/create-note', {
method: 'POST'
})
}
Here is my Express POST route (app.use(bodyParser.json()) is included in this file):
app.post('/create-note', (req, res) => {
postNote(req.body.note)
.then(() => {
res.sendStatus(201)
})
})
Here is the Knex postNote function:
export function postNote(newNote) {
const query = knex
.insert({ note_content: newNote })
.into('notes')
return query
}
Any help would be appreciated!
With POST requests you may have to wait for data body to be ready. Try this
app.post('/create-note', (req, res) => {
var body = '';
request.on('data',function(data) { body += data; });
request.on('end', function(data) {
postNote(body)
.then(() => {
res.sendStatus(201)
})
});
})
try the following in your markup, and forgo using fetch
...
<form method="POST" action="/create-note" enctype='application/json'>
...
</form>
...
or since the default encoding for a form is application/x-www-form-encoded (doc), add the following middleware to your express app..
...
app.use(bodyParser.urlencoded({ extended: true }));
...
also you could try...
...
<button ref="form" onClick={this.handleClick} className="btn btn-primary"
type="submit">Submit</button>
...
along with
handleClick(e) {
e.preventDefault();
const data = new FormData(this.refs.form);
fetch('/create-note', {
method: 'POST',
body: data
})
}
I found a solution and want to post it incase anyone else runs into a similar issue. The problem was I wasn't querying textarea's value correctly, so I was passing an undefined variable to the database to save.
Here's the solution I came up with:
handleSubmit(e) {
const data = new FormData(e.target)
const text = {note: data.get('note')}
fetch('/create-note', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(text)
})
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className ="form-group">
<label>Add a Note:</label>
<textarea className="form-control" name="note" rows="5">
</textarea>
<button ref="textarea" className="btn btn-primary"
type="submit">Submit</button>
</div>
</form>
)
}
I put a onSubmit event listener on the form, and created a new FormData instance with the form. Then I created an object containing the value of the textarea to pass into the fetch call.
I'm really stuck on how I would work with submitting a form that makes an ajax request using Vue.js and vue-resource then using the response to fill a div.
I do this from project to project with js/jQuery like this:
view in blade
{!! Form::open(['route' => 'formRoute', 'id' => 'searchForm', 'class' => 'form-inline']) !!}
<div class="form-group">
<input type="text" name="id" class="form-control" placeholder="id" required="required">
</div>
<button type="submit" class="btn btn-default">Search</button>
{!! Form::close() !!}
js/jquery
var $searchForm = $('#searchForm');
var $searchResult = $('#searchResult');
$searchForm.submit(function(e) {
e.preventDefault() ;
$.get(
$searchForm.attr('action'),
$searchForm.serialize(),
function(data) {
$searchResult.html(data['status']);
}
);
});
What I've done/tried so far in Vue.js:
view in blade
{!! Form::open(['route' => 'formRoute', 'id' => 'searchForm', 'class' => 'form-inline']) !!}
<div class="form-group">
<input type="text" name="id" class="form-control" placeholder="id" required="required">
</div>
<button type="submit" class="btn btn-default" v-on="click: search">Search</button>
{!! Form::close() !!}
vue/js
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
new Vue({
el: '#someId',
data: {
},
methods: {
search: function(e) {
e.preventDefault();
var req = this.$http.get(
// ???, // url
// ???, // data
function (data, status, request) {
console.log(data);
}
);
}
}
});
I'm wondering if it's possible to use components when dealing with the response to output the response data to a div?
Just to summarise everything:
How do I submit a form using vue js and vue-resource instead of my usual jQuery way?
Using a response from ajax, how can I output data into a div preferably using components?
I used this approach and worked like a charm:
event.preventDefault();
let formData = new FormData(event.target);
formData.forEach((key, value) => console.log(value, key));
In order to get the value from input you have to use v-model Directive
1. Blade View
<div id="app">
<form v-on="submit: search">
<div class="form-group">
<input type="text" v-model="id" class="form-control" placeholder="id" required="required">
</div>
<input type="submit" class="btn btn-default" value="Search">
</form>
</div>
<script type="text/javascript">
// get route url with blade
var url = "{{route('formRoute')}}";
Vue.http.headers.common['X-CSRF-TOKEN'] = document.querySelector('#token').getAttribute('value');
var app = new Vue({
el: '#app',
data: {
id: '',
response: null
},
methods: {
search: function(event) {
event.preventDefault();
var payload = {id: this.id};
// send get request
this.$http.get(url, payload, function (data, status, request) {
// set data on vm
this.response = data;
}).error(function (data, status, request) {
// handle error
});
}
}
});
</script>
If you want to pass data to component the use 'props' see docs for more info
http://vuejs.org/guide/components.html#Passing_Data_with_Props
If you want use laravel and vuejs together, then checkout
https://laracasts.com/series/learning-vuejs
Add v-model="id" on your text input
then add it to your data object
new Vue({
el: '#someId',
data: {
id: ''
},
methods: {
search: function(e) {
e.preventDefault();
var req = this.$http.get(
'/api/search?id=' + this.id,
function (data, status, request) {
console.log(data);
}
);
}
}
});
It’s better to remove v-on="click: search" and add v-on="submit: search" on the form tag.
You should add method="GET" on your form.
Make sure you have #someId in your html markup.