I a laravel project using React js for the font-end , i would like to pass some data rendered by a React component to my controller. In a blade template i have a form , and within that form , i'm displaying a "select" element using React js. How to pass the value in the select element via the Request(Request $request) variable to the controller?
Here is my form in the blade template:
<form method="POST" action="">
#csrf
<div id="example" data={{ $currencies }}></div>
<input type="submit" value="Create" class="btn btn-primary">
</form>
And there is the component:
class Example extends Component {
render() {
return(
<div>
<select>
<option></option>
<option>Currency</option>
<option>Reputation</option>
</select>
</div>
);
}
}
export default Example;
if (document.getElementById('example')) {
var data = document.getElementById('example').getAttribute('data');
ReactDOM.render(<Example data={data}/>, document.getElementById('example'));
}
I guess you can simply send or pass the data to laravel route or controller directly . You can use fetch() method or axios() to send the data in post method to the url and catch that in the respective controller. As react component or can say react is only the view of the MVC that there is no way(may be in my knowledge) to pass the data to server side with a api request like fetch() n all.
Related
This should be something trivial but I can't figure it out for the life of me.
What I need is an input field that is by default filled out for a user from a value from local Storage.
The problem I've run into is that none of the ways I'd normally do this (jQuery onload, JS onload or a (onload) in the HTML tag) seem to be run when a user switches to a different page without reloading. I've also tried ngOnInit() but that seems to be running before the page's DOM Content is ready to be edited and isn't working here.
Here is my code:
<form (submit)="editName($event)">
<div class="form-group">
<label for="nameInput">Name</label>
<!-- I want to insert the localStorage Value user_name into this input -->
<input type="name" class="form-control" id="nameInput" (onload)="initName()">
</div>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
A sad attempt at acheiving this is also in my component.ts:
initName() {
document.getElementById("nameInput").textContent = localStorage.getItem('user_name');
}
The error message in my console is:
ERROR TypeError: Cannot read property 'user_name' of undefined
I would recommend using an Angular ReactiveForm in this case instead of manually retrieving and binding the value.
In your component, create an instance of a FormGroup and bind the value from localStorage to the form control:
#Component({
template: `
<form *ngIf="form" [formGroup]="form" (submit)="editName($event)">
<div class="form-group">
<label for="nameInput">Name</label>
<input formControlName="name" type="name" class="form-control" id="nameInput">
</div>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
`
})
export class YourComponent implements OnInit {
form: FormGroup;
ngOnInit(): void {
this.form = new FormGroup({
name: new FormControl(localStorage.getItem('user_name')),
});
}
}
For more on Reactive forms in Angular, see: https://angular.io/guide/reactive-forms
I'd recommend using Angular Reactive Forms over Template-driven Forms regarding the purpose here. With a Template-driven approach you'll end up setting the localStorage bindings explicitly for every value inside your form. A better alternative is using Reactive Forms. (see Brandon's answer)
Assuming you use a FormGroup for your whole form you can retrieve and save the whole form using the FormGroup.value method that will give you all the values of your form in one step without disabled controls or FormGroup.getRawValue() to also include disabled controls. You can then just use this to store your attributes in the localStorage on form submit:
this.form = new FormGroup({
surName: new FormControl('user_surname'),
name: new FormControl('user_name'),
age: new FormControl('user_age'),
...
});
localStorage.setItem('userFormValues',JSON.stringify(this.form.value));
See how this example looks in your local storage:
This way your local storage will not be messed up with many keys. To read your values back to your form just use JSON.parse in combination with FormGroup.setValue():
this.form.setValue(JSON.parse(localStorage.getItem('userFormValues')));
TS page
init variable
username:string;
create function for fill variable from localstorage
getName(){
this.username = localStorage.getItem("user_name";
}
call variable on page load
onInit(){
this.getName();
}
html page
<input type="name" class="form-control" id="nameInput" value="{{username}}">
In the end I've gone with creating a method called getUsername() in component.ts:
getUsername() {
return localStorage.getItem('user_name');
}
then I bound it to the input using this:
<input type="name" class="form-control" id="nameInput" value="{{getUsername()}}">
I am using Nuxt and Vue and I am trying to submit a form, redirect the user to a new route including the submitted params, send an API request to get some data and then render that data.
I achieved this by simply setting the form action to the new path and manually adding all the URL parameters to the API request.
First I create a simple form with the route /search.
<form action="/search">
<input type="text" name="foobar">
<button type="submit">Submit</button>
</form>
When submitting the form the user leaves the current page and gets redirected to the new page. The URL would now look like this: http://www.example.com/search?foobar=test. Now I fetch the foobar parameter by using this.$route.query.foobar and send it to my API.
However the problem in my approach is when submitting the form the user leaves the current page and a new page load will occur. This is not what we want when building progressive web apps.
So my question is how can I submit a form in Nuxt/Vue and redirect to a new route including the submitted parameters?
The default behavior of <form> is to reload the page onsubmit. When implementing SPA's it would be better to avoid invoking default behavior of <form>.
Making use of router module which is available out-of-box in nuxtjs will enable all the redirection controls to flow within the application. if we try to trigger events available via <form> then browser reload will occur. This has to be avoided.
So my question is how can I submit a form in Nuxt/Vue and redirect to
a new route including the submitted parameters?
You can try below approach
First
Use .stop.prevent modifiers to prevent the submit button from invoking default <form> behavior. This is similar to using event.stopPropagation(); and event.preventDefault(); in jQuery
<form>
<input type="text" name="foobar" v-model="foobar">
<button type="submit" #click.stop.prevent="submit()">Submit</button>
</form>
Then
Create
vue model object foobar
vue method submit
Use this.$router.push to redirect to next page. This will enable the control flow to stay inside the SPA. if you want to send any data into server then you can do it before invoking this.$router.push else you can redirect and continue your logic.
export default {
data(){
return {
foobar : null
}
},
methods: {
submit(){
//if you want to send any data into server before redirection then you can do it here
this.$router.push("/search?"+this.foobar);
}
}
}
submitClick(){
this.$router.push({path: '/search', query:{key: value}})
}
<form #submit.stop.prevent="submitClick">
<input v-model="keyword">
<button type="submit">Search</button>
</form>
This is the right way to achieve a SPA with form submit. it supports enter key and in submitClick, there can be any logic before submitting
just add this:
#submit.prevent="false"
<form #submit.prevent="false">
<div class="form-group">
</div>
</form>
i hope this be useful for u :)
I want a way to show a classes render method due to an onclick event.
I have a log in page, once the uses completes it and hits submit (aka logs in), I want a new view to render.
class LoginPage extends React.Component{
render() {
return (
<div id="container">
<button onClick={() => this.refs.myref.myfunc()}>Click</button>
<form onSubmit={this.handleClick}>
<p><input type="text" id="playerName" value={this.props.nameValue} onChange={this.handleNameChange} /></p>
<p><input type="email" id="playerEmail" value={this.props.emailValue} onChange={this.handleEmailChange}/></p>
<p><input type="submit" value="submit" /></p>
</form>
</div>
)
}
}
class HomePage extends React.Component{
//does things
render() {
return (
<div>
<h1 className="headings" id="heading"> Home Page </h1>
</div>
)
}
}
How can I render the Home Page title instead of the form. I used to have some code that would toggle it based on state but now I am trying to break it into components and only set state in one place.
The handleClick function was updating the state before but now it is doing nothing but I want it to in some way call the render method inside the homepage component or pass state/props around. what is the react way of doing this? can further clarify if things do not make sense
I have a rails api that sends default input to an Angular app. The angular app receives json at localhost:9000/api/query, and then the view at localhost:9000/#/query styles that json into an unordered list.
If I send a POST request (from the browser javascript debugger) to the Rails app, and can send custom input and get desired output as a json string.
$.get('http://rails-app-url:3000/api/query', { 'input': 'my input goes here}
What I decided to do what build a form with an input box, and give it an ng-submit function that runs that javascript post request
<form ng-submit="sub()">
<textarea name="my_input"></textarea>
<button id="execute"></button>
</form>
Where the sub() function is defined in a jquery script that sets the queries variable to the desired json
$('#execute').click(function() {
queries = $.get('http://url-to-rails-app:3000/api/query', { 'input': 'my input here' });
});
to display the queries, I use markup like this
<div ng-controller="QueryCtrl">
<ul ng-repeat="query in queries">
<li>{{query}}</li>
</ul>
</div>
There are two problems with this:
the script does not execute unless it is written inline with the html for the view of this specific tab. I cannot attach it to index.html, as it can not find the #execute button.
even when the script is written inline with the html, the request is sent to the server, but the response from the server is not reflected in the html.
use ng-click
$scope.onSubmit = function() {
queries = $http.get('http://url-to-rails-app:3000/api/query', { 'input': 'my input here' });
};
<form ng-submit="onSubmit()">
<textarea name="my_input"></textarea>
<input type="submit"/>
</form>
EDIT
as per comments
<form ng-submit="onSubmit()">
<textarea name="my_input"></textarea>
<button type="submit" ng-click="onSubmit()"/>
</form>
You could do something like this (and use $http from AngularJS)
<form>
<textarea ng-model="my_input" name="my_input"></textarea>
<button id="execute" ng-click="sub()">Execute</button>
</form>
And in the controller:
$scope.sub = function(){
$http.get('http://url-to-rails-app:3000/api/query', {'input':$scope.my_input}).success(function(data){
$scope.queries = data;
}
}
I assume that your form and your display list are in the same controller (sharing the same $scope).
Why are you using GET, I think that a POST request should be better in this case.
I am trying to write a simple upload form with input file type using React JS. When i submit the file, it is not submitting multi form data. It is submitting plain input file name.
Do we need to make any other changes if we want to write upload functionality in React.
Basic javascript code for uploading (js fiddle link) :
/** #jsx React.DOM */
var HelloMessage = React.createClass({
render: function() {
return (<div>
<form name="secret" ENCTYPE="multipart/form-data" method="POST" action="http://localhost:8080/uploadFile">
Please choose two files to upload.
<br/>
File 1:<input type="file" id="profilePic" name="profilePic"/>
<br/>
<input type="submit" value="submit"/>
</form>
</div>);
}
});
React.renderComponent(<HelloMessage />, document.body);
Can someone help me to write using React JS.
Casing is important for React components. Try encType instead of ENCTYPE. (You should have seen a warning in your console suggesting that you use encType.)
Here's a complete list of tags and attributes:DOM Elements.