check the checkbox base on the response coming from axios - javascript

I have a checkbox
<div class="checkbox">
<label>
<input type="checkbox" value="add user" v-model="user.permissions">Add User
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" value="edit user" v-model="user.permissions">
Edit User
</label>
</div>
the checkbox is v-model on user.permission array
user:{
permissions: []
},
in which when i check a checkbox it will produce a result like this
user:Object
permissions:Array[2]
0:"edit user"
1:"add user"
now when i fetch a data from my backend using axios and put the data on user
editUser: function(id){
let vm = this;
axios.get('api/users/' + id)
.then( response => {
vm.user = response.data.data; //PUT RESPONSE DATA TO USER OBJECT
vm.usersModal = true;
})
.catch( error => {
console.log(error);
});
},
it will produced an output like this
user:Object
created_at:"2018-08-28 03:17:33"
deleted_at:null
email:"aa#gmail.com"
id:3
name:"aa"
permissions:Array[2]
0:Object
created_at:"2018-08-28 03:03:41"
guard_name:"web"
id:2
name:"delete user"
pivot:Object
updated_at:"2018-08-28 03:03:41"
1:Object
created_at:"2018-08-28 03:03:41"
guard_name:"web"
id:3
name:"add user"
pivot:Object
updated_at:"2018-08-28 03:03:41"
updated_at:"2018-08-28 03:17:33"
Now how can I check the checkbox using only v-model user.permission. I used the v-model user.permission because I'm using it on posting a request. However when I fetch it using id the data structure changes.

You will have to modify the fetched response:
editUser: function(id){
let vm = this;
axios.get('api/users/' + id)
.then( response => {
response.data.data.user.permissions = response.data.data.user.permissions.map((item) =>
{
return item.name; // <--- convert the array of objects into array of strings
});
vm.user = response.data.data; //PUT RESPONSE DATA TO USER OBJECT
vm.usersModal = true;
})
.catch( error => {
console.log(error);
});
},

Related

Serialize Symfony form data to JSON

Using Symfony Forms, HTML is generated that looks like this:
<input type="text" id="form_name" name="form[name]">
<input type="email" id="form_email" name="form[email]">
<textarea id="form_message" name="form[message]"></textarea>
With a bit of JS the entries are transformed to JSON and submitted:
const contactForm = document.getElementById('contact-form');
contactForm.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(event.target);
const jsonData = JSON.stringify(Object.fromEntries(formData));
// handle submission...
})
JSON that is sent to the backend:
"{"form[name]":"John Doe","form[email]":"example#domain.com","form[message]":"Some message"}"
In my controller (in PHP) I serialize the data into an array: $data = json_decode($request->getContent()); The issue is this data is formatted (as expected) like so:
["form[name]" => "John Doe", "form[email]" => "example#domain.com", "form[message]" => "Some message"];
Is there a built-in way to get the following result (either in PHP or JS)?
[ "name" => "John Doe", "email" => "example#domain.com", "message" => "Some message" ];
I looked into using the Serializer Component without success, and now wonder if I missed something or if the data should be fixed in JS before submission. Might there be a built-in solution?
If I'm not wrong you are submitting from using AJAX. And in that you can directly specify FormData object as body in AJAX API request. At backend you will receive data in $_POST or $_GET array as per your request method.
Here is the example code.
const contactForm = document.getElementById('contact-form');
contactForm.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(event.target);
fetch('<AJAX API URL>', {
method: 'POST',
body: formData
}).then(function (response) {
if (response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function (data) {
console.log(data);
}).catch(function (error) {
console.warn(error);
});
})
<form id="contact-form">
<input type="text" name="form['name']" />
<input type="text" name="form['job']" />
<input type="submit" value="submit" />
</form>
Here is how you will get data in POST array.
Array
(
[form] => Array
(
['name'] => 123
['job'] => 123123
)
)

How to properly render new elements after a POST request?

I have a react page that looks like this:
and right now when creating a new category the post request goes through to the database but the categories is not rendered again to display the new category unless you refresh the page (GET request for all categories on page start up).
SideBar.js
createNewCategory = async (input) => {
console.log("CREATING NEW: ", input);
var response = await fetch("http://localhost:8081/api/categories", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Token": 1234,
Accept: "application/json"
},
body: JSON.stringify({
title: input
})
})
let resp = await response.json();
this.setState({
categories: [...this.state.categories, resp]
})
}
CreateCategory.js
handleNewCategory = (event) => {
event.preventDefault()
this.props.createNewCategory(this.state.input)
this.setState({
input: ''
})
}
render(){
return (
<form onSubmit={this.handleNewCategory} className="new-category-form">
<h4>Create Category</h4>
<input onChange={this.handleInput} className="new-category-input" type="text" value={this.state.input} />
<input className="new-category-input" type="submit" value="Create" />
</form>
)
}
CategoriesContainer.js
function CategoriesContainer(props) {
function renderCategories(){
console.log("PROPS: ", props)
return props.categories.map(category => {
console.log("CATEACH: ", category)
return <Category key={category.id} category={category} />
})
}
return(
<div>
{renderCategories()}
</div>
)
}
At the moment if I create a new category with a name of letters I get the err
Uncaught (in promise) SyntaxError: Unexpected token a in JSON at position 0 sidebar.js:46
and if I create it with numbers I get
Warning: Each child in a list should have a unique "key" prop.
Im still new to react so hopefully Im not completely off the mark here, any ideas?
Fixed it. First off I was using response instead of resp to update the state and I was returning just the name rather than the whole object to the POST request.

How to POST array of objects of multiple form radio inputs to PHP using axios and vue?

I have a multi applicant form in my web app that has a radio button selector section. I managed to get the radio buttons fixed in every new application form but now have a problem in posting the data to PHP and MySQL database. My question is how do I go about posting an array of object to PHP and save it to MySQL database using axios?
I tried to find tutorials on the topic or even finding other questions asked but I didn't find an answer.
let app = new Vue({
el: "#app",
data: {
buttons: [{
val: null
}]
},
methods: {
addNewRadios(evt) {
evt.preventDefault();
this.buttons.push({
val: null
});
//console.debug(this.buttons);
},
onSubmit(evt) {
evt.preventDefault();
const formData = app.toFormData(app.buttons);
console.log(formData);
//What to do here???
},
toFormData(obj) {
let formData = new FormData();
for (var key in obj) {
formData.append(key, obj[key]);
}
return formData;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<h1>Multiple radio buttons VueJS</h1>
<div id="app">
<div class="radio">
<form #submit='onSubmit' method="post">
<div v-for="(button, index) in buttons">
<b>Index {{ index }}:</b>
<label :for="'rButton-' + index">option 1</label>
<input type="radio" :name="'rButton-' + index" value="value-1" v-model="button.val">
<label :for="'rButton-' + index">option 2</label>
<input type="radio" :name="'rButton-' + index" value="value-2" v-model="button.val">
</div>
<br>
<button #click="addNewRadios">Add radios</button>
<button type="submit">Submit</button>
</form>
</div>
<div>
</div>
</div>
Here, I have made a few modifications to your code. Build the form data with button values and then post the data using axios,
let app = new Vue({
el: "#app",
data: {
buttons: [{
val: null
}]
},
methods: {
addNewRadios(evt) {
evt.preventDefault();
this.buttons.push({
val: null
});
//console.debug(this.buttons);
},
onSubmit(evt) {
evt.preventDefault();
const formData = app.toFormData(app.buttons);
// What to do here???
// post data to your backend server.
axios({
method: 'post',
url: 'http://example.com/my-url',
data: formData,
}).then(response => {
console.log('Response:', response);
// upon successful post request, you will see the response from the backend server here.
}).catch(err => {
console.log('Error:', err);
// and in case of any error at the backend server.
});
},
toFormData(obj) {
let formData = new FormData();
for (let key in obj) {
formData.append(key, obj[key].val); // appending the button `val` property here, instead of the entire object.
}
return formData;
}
}
});
Then in the backend server, handle the post data. You should receive there an array of the button values that you'd sent.
I hope this helps.

How to render or update list in vue js if in array value changes

This is my vue code:
const app = new Vue({
el:'#app',
data:{
searchedLocation:'',
loctionsResults:[]
},
watch:{
searchedLocation:function(){
this.getLocations();
}
},
methods:{
getLocations: _.debounce(function(){
// Make a request to get list of locations
axios.get('/getLocations/'+ this.searchedLocation)
.then(function (response) {
//console.log(response.data);
this.loctionsResults = response.data;
console.log(this.loctionsResults);
})
.catch(function (error) {
console.log(error);
});
},500)
},
});
my Html :
<label for="location">Search by location</label>
<input type="text" name="location" v-model='searchedLocation'>
<ul>
<li v-for = "item in loctionsResults">
#{{item.location}}
</li>
</ul>
What I want?:
when i type something in input it will send a request using axios and then getting some result. But when trying to render that result it does not show any list.
How i can make that happen?

Edit MEANJS list in the list page

I am using MEAN JS, i am trying to edit the list items on the list page, but it shows the error as below. i have initiated the data using ng-init="find()" for the list and ng-init="findOne()" for individual data.
Error: [$resource:badcfg] Error in resource configuration for action `get`. Expected response to contain an object but got an array
HTML
Below i the form inside the controller where it initiates the find() and findOne().
<div ng-controller="OrdersController" ng-init="find()">
<div>
<div class="order-filter">
<div ng-repeat="order in orders">
<form ng-init="findOne()" name="orderForm" class="form-horizontal" ng-submit="update(orderForm.$valid)" novalidate>
<input type="text" class="" ng-model="order.title">
<input type="text" class="" ng-model="order.content">
<div class="form-group">
<input type="submit" value="Update" class="btn btn-default">
</div>
</form>
</div>
</div>
</div>
</div>
Controller
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'orderForm');
return false;
}
var order = $scope.order;
order.$update(function () {
$location.path('orders/' + order._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function () {
Orders.query(function loadedOrders(orders) {
orders.forEach(appendFood);
$scope.orders = orders;
});
};
$scope.findOne = function () {
$scope.order = Orders.get({
orderId: $stateParams.orderId
});
};
You need to check your Orders Service which probably is using $resource to provide your API requests (Orders.query)
It should look something like this:
function OrdersService($resource) {
return $resource('api/orders/:orderId', {
orderId: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
The style may be different depending on which version of mean you're using. By default, the $resource query will expect an array of results, but if for some reason you've set "isArray" to false then it will expect an object.
https://docs.angularjs.org/api/ngResource/service/$resource

Categories

Resources