Send multiple field arrays via ajax to Laravel 5 - javascript

I need help with saving a drag n drop menu order. I use http://farhadi.ir/projects/html5sortable to drag and update the list. Each menu item has two hidden fields: id and order. The order is updated dynamically when dropped. I don't know how to turn the fields id and order into a correct array so I can update via AJAX into Laravel.
HTML - Menu :
<div>
<input name="menu[1][id]" type="hidden" value="1">
<input name="menu[1][order]" class="new-order" type="hidden" value="3">
</div>
<div>
<input name="menu[2][id]" type="hidden" value="2">
<input name="menu[2][order]" class="new-order" type="hidden" value="4">
</div>
<div>
<input name="menu[3][id]" type="hidden" value="3">
<input name="menu[3][order]" class="new-order" type="hidden" value="5">
</div>
jQuery - Drag/drop, update order value then send via ajax :
// Sortable options
$('.nav-pages__items').sortable({
handle: '.nav-pages__drag',
items: ':not(.home)'
}).bind('sortupdate', function() {
// When dropped clear list order
$(this).find('input[name=menu]').attr('value', '');
// Then update list order
$('.nav-pages__items li:not(.home)').each(function(i, element) {
element = i+1;
$(this).find('input.new-order').attr('value'),
$(this).find('input.new-order').attr('value', + element);
});
// !! Somehow create array to send/save !!
// Ajax to send
$.post('/menu-update', {
_token: token,
id: id,
order: order
}, function(data) {
if (data.status == 'success') {
console.log('success: ', data);
} else if (data.error == 'error') {
console.log('error: ', data);
};
});
});
PHP/Laravel - Not got this far (without errors):
public function update()
{
$menu = Input::all();
$save = Page::where('id', $menu['id'])->update([
'order' => $menu['order']
]);
if ($save) {
$response = [
'status' => 'success',
'msg' => 'Message here',
'id' => $menu['id'],
'order' => $menu['order'],
];
};
return Response::json($response);
}
To summarise:
Get the id and order for each field group
Loop though them in js and crate correct array
Send array to Laravel and update order based on id
Also, if there's a much simpler way to do this, I'm all ears.

I don't believe you need those hidden inputs -- what about something like:
jQuery:
// Sortable options
$('.nav-pages__items').sortable({
handle: '.nav-pages__drag',
items: ':not(.home)'
}).bind('sortupdate', function() {
// Collect the new orderings
var newOrders = [];
$('.nav-pages__items li:not(.home)').each(function(i, element) {
var id = $(element).data('id'); // Set a data-id attribute on each li
var order = i;
newOrders[order] = id;
});
// Ajax to send
$.post('/menu-update', {
_token: token,
newOrders: newOrders
}, function(data) {
if (data.status == 'success') {
console.log('success: ', data);
} else if (data.error == 'error') {
console.log('error: ', data);
};
});
});
PHP/Laravel:
public function update()
{
$responses = [];
foreach (Input::get('newOrders') AS $order => $id) {
$save = Page::where('id', $id)->update([
'order' => $order
]);
if ($save) {
$response[$id] = [
'status' => 'success',
'msg' => 'Message here',
'id' => $id,
'order' => $order,
];
}
}
return Response::json($responses);
}

Related

Yii2 Dynamic Form Select2 Change Event not working from second index

I was trying to create a dynamic form for one of my project. I initialized a ajax request to retrieve value for a field.
<div class="row">
<div class="col-md-4">
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
'select2:select' => 'function(params) {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
$.ajax({
"url" : "units",
"type" : "post",
"data" : {itemID: itemVal},
success: function (data) {
console.log(data);
console.log(attrID);
$("#reqitems-"+attrID+"-rt_unit").val(data);
},
error: function (errormessage) {
//do something else
alert("not working");
}
});
}',
],
]); ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_unit")->textInput(['maxlength' => true, 'readOnly' => 'true']) ?>
</div>
The ajax is working perfectly in the first index of the dynamic form. But unfortunately from the send index, nothing is happening. I checked couple of questions & answers in stackoverflow for the situation, but everything failed.
Can anyone help me to find a solution?
Hi found a solution in an alternative way using jquery.
Since the elements are dynamically loaded, we need dynamically generate via AJAX or something similar the following input element. I removed the pluginEvent and initialized a new class for dynamic field.
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'reqItem form-control'],
'pluginOptions' => [
'allowClear' => true
]); ?>
Then manually I wrote jquery script to read the element.
<script>
$(document).on("change", ".reqItem", function() {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
$.ajax({
"url": "units",
"type": "post",
"data": {
itemID: itemVal
},
success: function(data) {
console.log(data);
console.log(attrID);
$("#reqitems-" + attrID + "-rt_unit").val(data);
},
error: function(errormessage) {
//do something else
alert("not working");
}
});
});
But still I am working to find the appropriate solution using Yii.

Send true or false to database wether checkbox is checked or not

i got an issue regarding checkboxes with nedb. I want to send true or false if the checkbox is checked or not to the database i cannot solve this issue. i am working with node.js and nedb. please help!
client js eventlistener:
var taskDone = document.querySelectorAll('.taskDone');
taskDone.forEach(btn => {
btn.addEventListener('click', (e) => {
var done = e.target.attributes[1].value;
let id = e.target.getAttribute('data-id');
let isDone = document.querySelector(`input[data-id=${id}]`).value;
console.log(isDone + "isdone")
if ($(taskDone).is(':checked')) {
$('.text').addClass('line-through')
console.log("trues")
$.ajax({
url: 'http://localhost:3000/done/' + id,
type: 'PUT',
data: { isDone }
}).done(function (data) {
//location.reload()
console.log(data)
})
} else {
console.log('falses')
$('.text').removeClass('line-through')
}
})
})
update function to nedb:
function taskIsDone (id, done) {
return new Promise((resolve, reject) => {
db.update({ _id: id }, { $set: done }, { returnUpdatedDocs: true }, (err, num, updateDocs) => {
if (err) {
reject(err)
} else {
resolve(updateDocs)
}
})
})
}
server:
app.put('/done/:_id', async(req, res) => {
try {
var id = req.params._id;
let done = {
title: req.body.isDone,
}
const updateToDo = await taskIsDone(id, done)
console.log(updateToDo + " Todo done");
res.json(updateToDo);
} catch (error) {
res.json({error: error.message});
}
})
html/ejs:
<% for ( var i = 0; i < row.length; i++) { %>
<div class="edit-container" >
<input type="text" name="editTask" value="<%=row[i].title %>" data-id="<%=row[i]._id %>">
<button name="<%= row[i]._id %>" class="edit" data-id="<%=row[i]._id %>">save edit</button>
</div>
<div>
<input type="checkbox" name="isDone" class="taskDone" data-id="<%=row[i]._id %>">
<span class="text"><%= row[i].title %></span>
<button class="delete" name="<%= row[i]._id %>">delete</button>
</div>
<br>
<% } %>
i could really need some help with this! thanks
I have recreated a minimal example of what you are trying to do with checkbox checked state. I have added three checkboxes with same class name .taskDone
And i have using a change function not a click function. Every-time you clicked on the checkbox and check it will show the console log with checked and the data-id of that checkbox as well.
To get the data-id you can simply use .data function of jQuery and just specify what you want after the data-** to get it stored value.
In addition, do not use fat arrow - => function with jQuery. Use normal function statements so you can access you things by using $(this) instead of specifying each class or id
Live Working Demo:
let taskDone = document.querySelectorAll('.taskDone'); //get all the chechbox with same class .taskDone
taskDone.forEach(function(btn) { //use normal function
btn.addEventListener('change', function() {
let id = $(this).data('id') //get the data id of checkbox
if ($(this).is(':checked')) { //check if the clicked checkbox is checked or not
console.log(id + ' is Checked - Updating neDB') //console.log
$.ajax({
url: 'http://localhost:3000/done/' + id,
type: 'PUT',
data: 'isDone'
}).done(function(data) {
console.log(data)
})
} else {
console.log("Not Checked")
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="isDone" class="taskDone" data-id="1">
<input type="checkbox" name="isDone" class="taskDone" data-id="2">
<input type="checkbox" name="isDone" class="taskDone" data-id="3">

Prevent InvalidArgumentException on dynamic form field creation

I'm following Symfony cookbook on dynamic form fields creation.
Basically, in my case, I have a Product, a ProductVersion and a Quantity field in my form.
On new forms, ProductVersion is hidden (only with a class attribute, It's still an EntityType).
On Product change (via select menu), I make an AJAX request to see if some ProductVersion exists for this product. If so, I populate the ProductVersion with available versions and show it to the user.
It's working fine with new forms. But when editing the same form, I have an InvalidArgumentException response on my AJAX request that tells me that the Quantity field is null :
Expected argument of type "int", "null" given at property path
"quantity".
I understand that indeed, I don't provide the quantity on my form submission through the AJAX request but that's the purpose of this method isn't it ? To only submit the field that makes a dynamic field change.
How can I do to avoid this Exception ?
Here is the ItemType :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('product', EntityType::class, [
'label' => 'item.product',
'class' => Product::class,
'placeholder' => 'item.product',
]);
$formModifier = function (FormInterface $form, Product $product = null) {
if (null !== $product) {
$productVersions = $product->getVersions();
if (count($productVersions) > 0) {
$form->add('productVersion', EntityType::class, [
'class' => 'App\Entity\ProductVersion',
'placeholder' => 'item.product_version',
'choices' => $productVersions,
'label' => 'item.product_version'
]);
} else {
$form->add('productVersion', EntityType::class, [
'class' => 'App\Entity\ProductVersion',
'placeholder' => 'item.product_version',
'choices' => [],
'label' => 'item.product_version',
'disabled' => true,
'row_attr' => [
//'class' => 'd-none'
]
]);
}
} else {
$form->add('productVersion', EntityType::class, [
'class' => 'App\Entity\ProductVersion',
'placeholder' => 'item.product_version',
'choices' => [],
'label' => 'item.product_version',
'disabled' => true,
'row_attr' => [
//'class' => 'd-none'
]
]);
}
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$form = $event->getForm();
$data = $event->getData();
$options = $event->getForm()->getConfig()->getOptions();
//add custom product version according product selected
$formModifier($event->getForm(), $data->getProduct());
$form
->add('quantity', IntegerType::class, [
'label' => 'item.quantity',
]);
if ($data->getId()) {
$form
->add('save', SubmitType::class, [
'label' => $options['submit_btn_label'],
]);
} else {
$form
->add('save', SubmitType::class, [
'label' => $options['submit_btn_label'],
]);
}
}
);
$builder->get('product')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$product = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $product);
}
);
}
And here is the Javascript part :
$(document).ready(function () {
var $product = $('#item_product');
// When product gets selected ...
$product.on('change', function () {
console.log("product has changed")
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected product value.
var data = {};
data[$product.attr('name')] = $product.val();
// Submit data via AJAX to the form's action path.
console.log(data);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: data,
success: function (html) {
// Replace current position field ...
$('#item_productVersion').closest('.form-group').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#item_productVersion').closest('.form-group')
);
// Position field now displays the appropriate positions.
}
});
});
})
As #Jakumi suggested, adding an empty_data option to the quantity field solved the problem. Nevertheless, It gives an error on the quantity on the form received via the AJAX request and that's normal.
I found that this is not a "clean" method (you have to tweak form fields, you load the entire page on each AJAX request, etc..) so I decided to create a special route dedicated to form submissions that are meant to add/remove/edit fields.
This route creates a new form with preset fields (in my case the product selected by the user).
Then I can populate the other field (in my case the 'ProductVersion') with a regular PRE_SET_DATA Form Event.
This way :
- I don't have to worry about any other required field
- I can serialize the entire form in my AJAX request (no need to find the field, everything is done in the form builder)
- The AJAX request only output the form (I guess this improves performance a bit)
The form builder doesn't change (you still need to listen to PRE_SET_DATA and POST_SUBMIT. If you don't listen to the POST_SUBMIT, the form will not know about the choices you added dynamically and It will give you an error).
Here is the JS part :
$product.on('change', function() {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// serialize the entire form
var data = $form.serializeArray();
// Submit data via AJAX to the form's action path.
console.log(data);
$.ajax({
url : '/project/item/partial-edit', //custom route
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current position field ...
$('#item_productVersion').closest('.form-group').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#item_productVersion').closest('.form-group')
);
}
});
});
Here is the special route :
/**
* #Route("/item/partial-edit", name="edit_item_partial", requirements={"project"="\d+","item"="\d+"})
*/
public function edit_item_partial(Request $request)
{
$item = new Item();
$formOption = $request->get('option') ?? array(
'submit_btn_label' => 'update'
);
$form = $this->createForm(ItemType::class, $item, $formOption);
$form->handleRequest($request);
if ($form->isSubmitted()){
//if form was submitted, create a new form with the $item that has now a Product given
$newForm = $this->createForm(ItemType::class, $item, $formOption);
//here is the custom view only rendering the form
return $this->render('item/new_form-only.html.twig', [
'form' => $newForm->createView(),
]);
}
else {
return new Response('No form was submitted');
}
}

autocomplete and multiple function using ajax in laravel

I am new to laravel framework. I want to complete a important task in my app.
In that app they have modules like invoices,quotes,payment,customers. for particular customers they have multiple invoices with status of sent and partially paid.
Here is the receipt page, on type of customer name it will get autosuggestion from customer table. Onclick of cutomer name it will get invoice details from (invoice table) based on customer id,and need to show on table below that customer name textbox, onclick of table invoice it will open modal which means if the particular customer has unpaid invoice they need to record payment else proceed with normal receipt creation.
I try the code like this, But I am not getting proper output please anyone help me to get out of this issue.
<input type="text" name="customername" required="required" id="cust" placeholder="Customer Name" class="form-control col-md-7 col-xs-12 typeahead"/>
$( function() {
$( "#cust" ).autocomplete({
//source: "http://www.duminex.com/client/search",
source: "{{route('search.client')}}",
select: function( event, ui ) {
get_invoices(ui.item.id);
$('#id').val(ui.item.id);
$('#clientAddress').val(ui.item.address);
}
});
} );
function get_invoices(client_id)
{
$.ajax({
method: 'GET',
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}
routes
Route::get('/client/search',[
'uses'=>'ClientsController#search',
'as'=>'search.client'
]);
Route::get('/client/search2', 'ClientsController#search2')->name('client.details');
Controller
public function search(Request $request)
{
$s= Input::get('term');
$clients = Client::select("id" ,"user_id", "companyname", "companyaddress" , "billingAddress")->where('companyname','like','%'.$s.'%')->where('user_id',Auth::user()->id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['id' => $value->id, 'value' => $value->companyname , 'email' => $value->companyaddress , 'address' => $value->billingAddress];
}
}
return $searchResult;
}
public function search2(Request $request)
{
$clients = Invoice::select("invoiceNo")->where('status',['sent,Partially paid'])->where('client_id',$request->client_id)->get();
if(count($clients) == 0){
$searchResult[] = "No Item found";
}
else{
foreach ($clients as $key => $value) {
$searchResult[] = ['invoiceNo' => $value->invoiceNo];
}
}
return $searchResult;
}
Thanks in advance. Please anyone to help me get out of this issue.
You are not passing any data to the ajax so thats why you are not getting any result.
Try below code :
function get_invoices(client_id) {
$.ajax({
method: 'GET',
data : {
client_id: client_id
},
url: "{{route('client.details')}}"
}).done(function(data){
alert(data);
});
}

Express Routes not functioning on Single Page Web App

I'm converting an old LAMP stack project to use Node/Express/MongoDB instead of PHP/Laravel/MySQL. I built out my routes the same way I did in Laravel and have tested the routes I've built using Postman. Every route works as it should through testing in Postman.
However, when I try to use these routes in the display.js file that I wrote, the only route that works is GET /players. I am looking for some insight on these routes and the display file I'm using.
When I click the edit button, my GET /player/:id route grabs the correct information (status code 200 and preview shows JSON object) but will not populate the fields in my form.
When I click the delete button, I get a 404 status code with a response of "Cannot GET /players/123/delete". How do I adjust my display code to use DELETE instead of GET? (I believe I can refactor my all of my routes to just /players/:id using the correct http request method if I can figure out how to pass the request method in the display.js code).
When I try to submit a new record, I get a 400 status code with validation error saying Path age is required. It's actually the same error for each field name, so I assume that I'm not passing the values from the field into the JSON object correctly.
I haven't been able to test patch, but believe it should be remedied through fixing DELETE /players/:id and GET /players/:id.
Any help is appreciated. Code is below for display and server js files.
display.js
// this is the base url to which all your requests will be made
var baseURL = window.location.origin;
$(document).ready(function(){
// $.ajaxSetup({
// headers: {
// 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
// }
// });
$('#table').click(function(event) { // generates the table
// change the url parameters based on your API here
// Using an JQuery AJAX GET request to get data form the server
$.getJSON(baseURL+'/players', function(data) {
generateTable(data, $('#container'));
});
});
$('#form').click(function(event) {
// creating an empty form
generateForm(null, $('#container'));
});
// Handle table click event for delete
$('#container').on('click', '.delete', function(event) {
var id = $(this).val();
// change the url parameters based on your API here
// remember to create delete functionality on the server side (Model and Controller)
// Using an JQuery AJAX GET request to get data form the server
$.getJSON(baseURL+"/players/"+id+"/delete", function(data) {
//Generate table again after delete
//change the url based on your API parameters here
// Using an JQuery AJAX GET request to get data from the server
$.getJSON(baseURL+'/players', function(data) {
generateTable(data, $('#container'));
});
});
});
// Handle form submit event for both update & create
// if the ID_FIELD is present the server would update the database otherwise the server would create a record in the database
$('#container').on('submit', '#my-form', function(event) {
var id = $('#id').val();
console.log(id);
if (id != "") {
event.preventDefault();
submitForm(baseURL+"/players/"+id+"/edit", $(this));
} else {
event.preventDefault();
submitForm(baseURL+"/player", $(this));
}
});
// Handle table click event for edit
// generates form with prefilled values
$('#container').on('click', '.edit', function(event) {
// getting id to make the AJAX request
var id = $(this).val();
// change the url parameters based on your API here
// Using an JQuery AJAX GET request to get data form the server
$.getJSON(baseURL+'/players/'+id, function(data) {
generateForm(data, $('#container'));
});
});
// function to generate table
function generateTable(data, target) {
clearContainer(target);
//Change the table according to your data
var tableHtml = '<table><thead><tr><th>Name</th><th>Age</th><th>Position</th><th>Team</th><th>Delete</th><th>Edit</th></tr></thead>';
$.each(data, function(index, val) {
tableHtml += '<tr><td>'+val.playername+'</td><td>'+val.age+'</td><td>'+val.position+'</td><td>'+val.team+'</td><td><button class="delete" value="'+val._id+'">Delete</button></td><td><button class="edit" value="'+val._id+'">Edit</button></td></tr>';
});
tableHtml += '</table>';
$(target).append(tableHtml);
}
// function to generate form
function generateForm(data, target){
clearContainer(target);
//Change form according to your fields
$(target).append('<form id="my-form"></form>');
var innerForm = '<fieldset><legend>Player Form</legend><p><label>Player Name: </label>'+'<input type="hidden" name="id" id="id"/>'+'<input type="text" name="playername" id="playername" /></p>' + '<p><label>Age: </label><input type="text" name="age" id="age" /></p>'+ '<p><label>Hometown: </label><input type="text" name="city" id="city" />'+ ' ' + '<input type="text" name="country" id="country" /></p>' + '<p><label>Gender: </label><input type="text" name="gender" id="gender" /></p>'+ '<p><label>Handedness: </label><input type="text" name="handedness" id="handedness" /></p>'+ '<p><label>Broom: </label><input type="text" name="broom" id="broom" /></p>'+ '<p><label>Position: </label><input type="text" name="position" id="position" /></p>'+ '<p><label>Team: </label><input type="text" name="team" id="team" /></p>'+ '<p><label>Favorite Color: </label><input type="text" name="favoritecolor" id="favoritecolor" /></p>'+ '<p><label>Headshot: </label><input type="text" name="headshot" id="Headshot" /></p>'+ '<input type="submit"/>';
$('#my-form').append(innerForm);
//Change values according to your data
if(data != null){
$.each(data, function(index, val) {
$('#id').val(val._id);
$('#playername').val(val.playername);
$('#age').val(val.age);
$('#city').val(val.city);
$('#country').val(val.country);
$('#gender').val(val.gender);
$('#handedness').val(val.handedness);
$('#broom').val(val.broom);
$('#position').val(val.position);
$('#team').val(val.team);
$('#favoritecolor').val(val.favoritecolor);
$('#Headshot').val(val.headshot);
});
}
}
function submitForm(url, form){
$.post(url, form.serialize(), function(data) {
showNotification(data, $('#notification'));
});
}
function showNotification(data, target){
clearContainer(target);
target.append('<p>'+data+'</p>');
}
function clearContainer(container){
container.html('');
}
});
server.js
const _ = require('lodash');
const {ObjectID} = require('mongodb');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
var {mongoose} = require('./db/mongoose');
var {Player} = require('./models/player');
var app = express();
const port = process.env.PORT || 3000;
app.use(express.static(__dirname+'./../public'));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile('index.html');
});
app.post('/player', (req, res) => {
var player = new Player({
playername: req.body.playername,
age: req.body.age,
city: req.body.city,
country: req.body.country,
gender: req.body.gender,
handedness: req.body.handedness,
broom: req.body.broom,
position: req.body.position,
team: req.body.team,
favoritecolor: req.body.favoritecolor,
headshot: req.body.headshot
});
player.save().then((doc) => {
res.send(doc);
}, (e) => {
res.status(400).send(e);
});
});
app.get('/players', (req, res) => {
Player.find().then((players) => {
res.send(players);
}, (e) => {
res.status(400).send(e);
});
});
app.get('/players/:id', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Player.findById(id).then((player) => {
if (player) {
res.send(player);
} else {
return res.status(404).send();
}
}).catch((e) => {
res.status(400).send();
});
});
app.delete('/players/:id/delete', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Player.findByIdAndRemove(id).then((player) => {
if (player) {
res.send(player);
} else {
return res.status(404).send();
}
}).catch((e) => {
res.status(400).send();
});
});
app.patch('/players/:id/edit', (req, res) => {
var id = req.params.id;
var body = _.pick(req.body, ['playername', 'age', 'city', 'country', 'gender', 'handedness', 'broom', 'position', 'team', 'favoritecolor', 'headshot']);
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Player.findByIdAndUpdate(id, {$set: body}, {new: true}).then((player) => {
if (!player) {
return res.status(404).send();
} else {
res.send(player);
}
}).catch((e) => {
res.status(400).send();
})
});
app.listen(port, () => {
console.log(`Started on port ${port}`);
});
module.exports = {app};
When I click the delete button, I get a 404 status code with a response of "Cannot GET /players/123/delete". How do I adjust my display code to use DELETE instead of GET? (I believe I can refactor my all of my routes to just /players/:id using the correct http request method if I can figure out how to pass the request method in the display.js code).
This is because your app has app.delete('/players/:id/delete') and not app.get('/players/:id/delete'). However, your server side code shouldn't change much, just one tweak:
If you have an app.delete() then really no need to have the verb delete at the end of the resource.
Also you need to make the request using the HTTP Method DELETE instead of making a GET in display.js. Just make the DELETE request using $.ajax() with type set to 'DELETE'
When I click the edit button, my GET /player/:id route grabs the correct information (status code 200 and preview shows JSON object) but will not populate the fields in my form.
This is because your implementation of $.each() assumes data will always be an Array and not ever and object, however, your generateForm() is passing in a Player object. Change your $.each() to do type checking for array handling and object handling. See below changes.
When I try to submit a new record, I get a 400 status code with validation error saying Path age is required. It's actually the same error for each field name, so I assume that I'm not passing the values from the field into the JSON object correctly.
If you make the above change to generateForm() it should fix this.
Just take the below snippets and replace those sections within your app, it should work.
server.js
app.delete('/players/:id', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
return Player.findByIdAndRemove(id).then((player) => {
if (player) {
res.status(200).json(player);
} else {
return res.status(404).send();
}
}).catch((e) => {
res.status(400).send();
});
});
app.patch('/players/:id', (req, res) => {
var id = req.params.id;
var body = _.pick(req.body, ['playername', 'age', 'city', 'country', 'gender', 'handedness', 'broom', 'position', 'team', 'favoritecolor', 'headshot']);
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Player.findByIdAndUpdate(id, {$set: body}, {new: true}).then((player) => {
if (!player) {
return res.status(404).send();
} else {
res.status(200).json(player);
}
}).catch((e) => {
res.status(400).send();
})
});
app.post('/players', (req, res) => {
var player = new Player({
playername: req.body.playername,
age: req.body.age,
city: req.body.city,
country: req.body.country,
gender: req.body.gender,
handedness: req.body.handedness,
broom: req.body.broom,
position: req.body.position,
team: req.body.team,
favoritecolor: req.body.favoritecolor,
headshot: req.body.headshot
});
return player.save().then((doc) => {
return res.status(200).json(doc);
}, (e) => {a
return res.status(400).send(e);
});
});
display.js
// Handle form submit event for both update & create
// if the ID_FIELD is present the server would update the database otherwise the server would create a record in the database
$('#container').on('submit', '#my-form', function(event) {
var id = $('#id').val();
let formData = {};
$.each($('#myForm').serializeArray(), function(_, kv) {
if (formData.hasOwnProperty(kv.name)) {
formData[kv.name] = $.makeArray(formData[kv.name]);
formData[kv.name].push(kv.value);
}
else {
formData[kv.name] = kv.value;
}
});
console.log(id);
if (id != "") {
event.preventDefault();
$.ajax({
url: baseURL + '/players/' + id,
type: 'PATCH',
success: function(edited) {
// Handle returned edited player
}
})
} else {
event.preventDefault();
$.ajax({
url: baseURL + '/players',
type: 'POST',
success: function(created) {
// Handle created player
}
})
}
});
// Handle table click event for delete
$('#container').on('click', '.delete', function(event) {
var id = $(this).val();
// change the url parameters based on your API here
// remember to create delete functionality on the server side (Model and Controller)
// Using an JQuery AJAX GET request to get data form the server
$.ajax({
url: baseURL + '/players/' + id,
type: 'DELETE',
success: function(data) {
//Generate table again after delete
//change the url based on your API parameters here
// Using an JQuery AJAX GET request to get data from the server
$.getJSON(baseURL+'/players', function(data) {
generateTable(data, $('#container'));
});
}
});
});
// function to generate form
function generateForm(data, target){
clearContainer(target);
//Change form according to your fields
$(target).append('<form id="my-form"></form>');
var innerForm = '<fieldset><legend>Player Form</legend><p><label>Player Name: </label>'+'<input type="hidden" name="id" id="id"/>'+'<input type="text" name="playername" id="playername" /></p>' + '<p><label>Age: </label><input type="text" name="age" id="age" /></p>'+ '<p><label>Hometown: </label><input type="text" name="city" id="city" />'+ ' ' + '<input type="text" name="country" id="country" /></p>' + '<p><label>Gender: </label><input type="text" name="gender" id="gender" /></p>'+ '<p><label>Handedness: </label><input type="text" name="handedness" id="handedness" /></p>'+ '<p><label>Broom: </label><input type="text" name="broom" id="broom" /></p>'+ '<p><label>Position: </label><input type="text" name="position" id="position" /></p>'+ '<p><label>Team: </label><input type="text" name="team" id="team" /></p>'+ '<p><label>Favorite Color: </label><input type="text" name="favoritecolor" id="favoritecolor" /></p>'+ '<p><label>Headshot: </label><input type="text" name="headshot" id="Headshot" /></p>'+ '<input type="submit"/>';
$('#my-form').append(innerForm);
//Change values according to your data
if(data instanceof Array){
$.each(data, function(index, val) {
$('#id').val(val._id);
$('#playername').val(val.playername);
$('#age').val(val.age);
$('#city').val(val.city);
$('#country').val(val.country);
$('#gender').val(val.gender);
$('#handedness').val(val.handedness);
$('#broom').val(val.broom);
$('#position').val(val.position);
$('#team').val(val.team);
$('#favoritecolor').val(val.favoritecolor);
$('#Headshot').val(val.headshot);
});
}
else if (typeof data === 'object') {
$.each(data, function(key, value) => {
$('#' + key).val(value);
});
}
}
Try res.json(player); instead of res.send(player); in order to send the data in JSON format.
Also, instead of $.post(url, form.serialize(), function(data) {try the code from this answer in order to send the data in JSON format.

Categories