How to submit a form via ajax in vue 2.6 - ajax

I am vue newbie.
I have a simple form that looks like this:
<form :action=" appUrl +'ConnectionHandler'" method="post" enctype="multipart/form-data">
<fieldset
id="fileHandlingButtons"
:disabled="is_fileHandler_disabled"
>
<legend>File Handling</legend>
<input
type="file"
id="selectFile"
name="selectFile"
>
<input
type="button"
value="Run"
id="run"
#click="startRun"
>
</fieldset>
</form>
I want to submit to my backend without using a submit type. Instead, I want to submit it via ajax.

Vue.js has an official package which is called vue-resource which works as an HTTP client, but the official documentation suggests using Axios.
Installing Axios and Setting up a Component
$ npm install axios
OR
$ yarn add axios
Using Axios in Vue Components
<template>
<div><div/>
</template>
<script>
import axios from "axios";
export default {
data() {
return {};
};
}
</script>
now in your case, your template should look like this
<template>
<div>
<form :action=" appUrl +'ConnectionHandler'" method="post" enctype="multipart/form-data">
<fieldset id="fileHandlingButtons" :disabled="is_fileHandler_disabled" >
<legend>File Handling</legend>
<input type="file" id="selectFile" name="selectFile" >
<input type="button" value="Run" id="run" #click.prevent="startRun">
</fieldset>
</form>
<div/>
</template>
<script>
import axios from "axios";
export default {
data() {
return {};
},
methods: {
startRun() {
axios.post("api endpoint")
.then(response => console.log(response))
}
}
}
</script>
**Note* :* this will not a working code on yours but an idea on how you will solve your problem

To make XMLHTTPRequests from Vue.js you would typically use a library. I recommend Axios, which is also referenced in the Vue guide.
I suggest you start by reading those two, but I've given a short example how you might apply this to your problem below.
Install axios and import it to your component. You would use a package manager like yarn or npm, if you use npm (commonly used) the following command in your project folder should do it:
npm install axios
Define a submitMyForm() method in your component that is going to submit the form for you by making the axios call. here is a (pseudocode) example of what such a method would look like:
submitMyForm() {
axios.post('your-api-url', {
dataField1: value,
dataField2: value
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
Add a listener to whatever user action you would like to submit the form, for example:
<button #click="submitMyForm()">Submit</button>
To have the form-data available in your component methods, you would use v-model bindings, here is a link to the guide entry.. In your case, you might define two variables in the data object of your component, one for each of your input fields. you can then send these variables in your axios.post() call.
There are other patterns to do this, one I personally like is to use Vuex and do all api calls in Vuex actions, organized per module. I prefer this because it enables code reuse between components and removes the responsibility of server communication from my components, keeping them nice and simple. But that's a bit more involved, the above method is good to get started.

Related

Get Data back from Vue Component

Is it possible to get Data back from a vue component?
Laravel blade.php code:
...
<div>
<component1></component1>
</div>
...
In component1 is a selectbox which i need (only the selected item/value) in the blade.php
A vue component, when rendered in the browser, is still valid HTML. If you make sure your component is wrapped in a form element and has a valid input element, and the form can be submitted, the PHP endpoint can consume the form’s data without problems. It could look like this:
Layout/view:
<form method="post" action="/blade.php">
<component1></component1>
<button type="submit">Submit form</button>
</form>
Component (<component1/>):
<fieldset>
<input type="checkbox" name="my_option" id="my_option">
<label for="my_option">I have checked this checkbox</label>
</fieldset>
PHP script (blade.php):
echo $_POST["my_option"] // if checked, should print "on"
If you are looking for a JavaScript centered approach, you may want to serialize the form and fetch the endpoint; it could look similar to this:
import serialize from 'form-serialize';
const formData = serialize(form)
fetch(form.action, { method: 'POST' }, body: JSON.stringify(formData) })
.then(response => {
// update page with happy flow
})
.catch(error => {
// update page with unhappy flow
})
Building from an accessible and standardized basis using proper HTML semantics will likely lead to more understandable code and easier enhancements down the road. Good luck!
(Edit: if you require a complete, working solution to your question, you should post more code, both from the Vue app as well as the PHP script.)

Passing and binding img src from props in Vue.js

I am trying to display an image with the img tag by using a path from props for the src attribute.
I've tried changing the path with #, using the whole path with src, adding ../assets/ in the component and only passing the file name (orange.png) as props.
I always get the default broken image displayed.
When inspecting in the browser, the path seems fine.
When I display the image directly, I can see that the path is resolved to some different path <img data-v-1212d7a4="" src="/img/orange.7b71a54c.png">.
Edit:
Additionally I tried this post Can't dynamically pass relative src path for imgs in Vue.js + webpack ,
where using <img :src="require(picture_src)" /> is given as an answer.
This leads to an error: Error in render: "Error: Cannot find module '../assets/orange.png'"
(Edit2:
This answer in the end worked for me in the end as described in my answer post.)
The same error occurs with the similar webpack method using let images = require.context('../assets/', false, /\.png$/) in my script part, as the answer on this post Can't dynamically pass relative src path for imgs in Vue.js + webpack .
I am new to Vue.js, so I don't exactly know what is happening or how to search for this or it might not have anything to do with what I'm originally trying.
I am able to display my image when I pass the path directly, like this
<img src="../assets/orange.png"/>
Now I'd actually like to pass it to my component in the props and then, inside the component, display it reading the path from props.
Component
<template>
<div>
<img :src=picture_src />
<div class="pic_sub">{{pic_desc}}</div>
</div>
</template>
<script>
export default {
name: 'PictureCard',
props: {
picture_src: String,
pic_desc: String
}
}
</script>
Using the component:
<template>
<div>
<PictureCard pic_desc='some description text' picture_src='../assets/orange.png' />
</div>
</template>
<script>
import PictureCard from './components/PictureCard.vue'
export default {
name: 'app',
components: {
PictureCard
}
}
</script>
If it is possible, I'd love to display my from a path that is passed through the component's props.
Otherwise I'd love to know some other solutions, work-arounds or knowledge on best practices in this case.
This worked for me
<img :src="require(`#/assets/img/${filename}`)">
where filename is passed in as a String prop e.g. "myImage.png".
Make sure you use the path specific to your project.
Source: https://github.com/vuejs-templates/webpack/issues/450
Note: # is a webpack alias for /src that is set by default in Vue projects
After some research, I understand that my problem has to do with webpack and resolving filepaths. I used a modified version from this answer:
Vue.js dynamic images not working
and this answer:
Can't dynamically pass relative src path for imgs in Vue.js + webpack
Since the link in the second answer was dead, here's an active link to require.context documentation:
https://webpack.js.org/guides/dependency-management/#requirecontext
My mistake when trying the second link's answer was that I returned only orange.png as the path, while I needed to add ./ at the beginning.
My working picture component now looks like this.
<template>
<div>
<img :src="resolve_img_url(picture_src)" />
<div class="pic_sub">{{pic_desc}}</div>
</div>
</template>
<script>
export default {
name: 'PictureCard',
props: {
picture_src: String,
pic_desc: String
},
methods: {
resolve_img_url: function (path) {
let images = require.context('../assets/', false, /\.png$|\.jpg$/)
return images("./"+path)
}
}
}
</script>
I edited the regular expression to match .png and .jpg file endings. Therefore passing the prop looks like this now
<PictureCard picture_src='orange.png' pic_desc='some picture description'/>
This works for me:
This is how i use my Componenent.
<image-element
:imageSource="require('#/assets/images/logo.svg')">
</image-element>
My Image Component:
<template>
<div>
...
<img v-bind:src=imageSource />
...
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import { Component, Prop } from 'nuxt-property-decorator'
#Component({
components: {
.....
}
})
export default class extends Vue {
...
#Prop({ default: '' }) imageSource!: String
...
}
</script>
Newer solution:
The 'require()'-method does not work when using Vite.
I got this error: ReferenceError: require is not defined.
This is how I solved it without 'require()' and with composition API:
From parent component:
<ChildComponent icon-filename="icon.svg" />
ChildComponent:
<template>
<div>
<img :src="getImageUrl()">
</div>
</template>
<script setup lang="ts">
import {defineProps} from "vue";
const props = defineProps({
iconFilename: String
})
function getImageUrl() {
// This path must be correct for your file
return new URL(`../assets/icons/${props.iconFilename}`, import.meta.url)
}
</script>
this is my favorite super simple way to do it. It can easily be reused in any file in any folder in my project. Just pass the actual path as a string from the perspective of the parent:
//some file
<ParentA>
<ImageComponent
myImagePath="../../../../../myCat.png"
/>
</ParentA>
//some other file in a different folder in my project
<ParentB>
<ImageComponent
myImagePath="../../myCat.png"
/>
</ParentB>
//child component file
<template functional>
<div>
<img :src="props.myImagePath">
</div>
</template
Thats all not working for me :D
The template File is wrong!
you need to add ":" before you set your prop.
thats how i should use the PictureCard
<PictureCard :picture_src="require('orange.png')"
pic_desc='some picture description'/>
and thats how my PictureCard should look like:
<template>
<div>
<img v-bind:src="picture_src" />
</div>
</template>
export default class PictureCard extends Vue {
#Prop({ default: require("#/assets/orange.svg") }) img!: string
}
so in case no prop is setted, so i added a default prop too.
and yes i only used the image.

What is the best way to use v-model without using it in the main app.js file?

I was wondering i have this code inside my blade file:
<input type="text" class="form-control" :model="productname" id="name" name="name" aria-describedby="emailHelp" placeholder="Title" value="{{ old('name') }}" required>
and i want to create an 2 way data binding, so when user submitted 3 or more character to get an green background of this input field, but when they are less to get a red background.
I tried to do this with vue-component, but it seems for whatever reason the vue-component does not have access to the main #app id which is assign to the main app blade template in order all vue code to have access to the html code and change it. I have created an vue-component called Upload inside ressources/assests/js/components/Upload.js, but when i write this code:
<template>
</template>
<script>
export default {
data() {
return {
productname: '',
};
},
mounted() {
console.log('Upload component', this.message);
}
}
</script>
and added of course to app.js like that Vue.component('upload-component', require('./components/Upload.vue'));
and run - npm run dev to compile the code i am getting this error:
[Vue warn]: Property or method "productname" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
Whatever when i write this code inside the main app.js file (resources/assests/js/app.js):
const app = new Vue({
el: '#app',
data() {
return {
productname: '',
};
},
});
everything is working fine and i dont get any errors, but i dont want that, as imagine for my website/app i have to have for example 100 v-models and i dont want to put them all inside the main app.js file. Is there other way to do this?
Can i still somehow make it work inside the vue component, so the component can see the v-model and not giving me this error?
If not, can i make it work and use vue inside the blade file something like that?
new Vue({
el: '#form',
data: {
productname: ''
}
});
but this code its not working. Thanks!
It's a bit tricky to make out what you are doing exactly, but your error is related to having no data property 'message', you have only a property called 'productname'.
If you want your component to communicate up to its parents or siblings you should read into emitting events in vue using
this.$emit

Pass data from blade to vue component

I'm trying to learn vue and with that I want to integrate it with laravel too..
I simply want to send the user id from blade to vue component so I can perform a put request there.
Let's say I have this in blade:
<example></example>
How can I send Auth::user()->id into this component and use it.
I kept searching for this but couldn't find an answer that will make this clear.
Thanks!
To pass down data to your components you can use props. Find more info about props over here. This is also a good source for defining those props.
You can do something like:
<example :userId="{{ Auth::user()->id }}"></example>
OR
<example v-bind:userId="{{ Auth::user()->id }}"></example>
And then in your Example.vue file you have to define your prop. Then you can access it by this.userId.
Like :
<script>
export default {
props: ['userId'],
mounted () {
// Do something useful with the data in the template
console.dir(this.userId)
}
}
</script>
If you are serving files through Laravel
Then here is the trick that you can apply.
In Your app.blade.php
#if(auth()->check())
<script>
window.User = {!! auth()->user() !!}
</script>
#endif
Now you can access User Object which available globally
Hope this helps.
Calling component,
<example :user-id="{{ Auth::user()->id }}"></example>
In component,
<script>
export default {
props: ['userId'],
mounted () {
console.log(userId)
}
}
</script>
Note - When adding value to prop userId you need to use user-id instead of using camel case.
https://laravel.com/docs/8.x/blade#blade-and-javascript-frameworks
Rendering JSON
Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:
<script>
var app = <?php echo json_encode($array); ?>;
</script>
However, instead of manually calling json_encode, you may use the #json Blade directive. The #json directive accepts the same arguments as PHP's json_encode function. By default, the #json directive calls the json_encode function with the JSON_HEX_TAG, JSON_HEX_APOS, JSON_HEX_AMP, and JSON_HEX_QUOT flags:
<script>
var app = #json($array);
var app = #json($array, JSON_PRETTY_PRINT);
</script>
Just to add for those who still get error.
For me this <askquestionmodal :product="{{ $item->title }}"></askquestionmodal> still gives error in console and instead showing html page I saw white screen.
[Vue warn]: Error compiling template:
invalid expression: Unexpected identifier in
Coupling to connect 2 rods М14 CF-10
Raw expression: :product="Coupling to connect 2 rods М14 CF-10"
Though in error I can see that $item->title is replaced with its value.
So then I tried to do like that <askquestionmodal :product="'{{ $item->title }}'"></askquestionmodal>
And I have fully working code.
/components/askquestionmodal.vue
<template>
<div class="modal-body">
<p>{{ product }}</p>
</div>
</template>
<script>
export default {
name: "AskQuestionModal",
props: ['product'],
mounted() {
console.log('AskQuestionModal component mounted.')
}
}
</script>

Better Way to use Laravel old and Vue.js

Im working using vue.js 2.0 and Laravel 5.4 I would like to know if exits a better way to send data Controllers -> views without lost the value, overwrite by the v-model
Because after charge vue.js this take the value in data that is define in this way
data: {
ciudad:'',
}
If I try to do something like that
<input class="form-control" id="ciudad" name="ciudad" type="text" v-model="documento.ciudad" value="{{ $documento->ciudad }}" >
I lost the value sending by the controller
Vue really expects you to init data from the view model which then updates the view, however, you want to use data in the view to update the underlying model data.
I think the easiest approach to this is to write a directive that inits the value from the HTML, so you don't need to directly access the DOM:
Vue.directive('init', {
bind: function(el, binding, vnode) {
vnode.context[binding.arg] = binding.value;
}
});
It's a little abstract so it's worth looking at Directive Hook Arguments section of the docs.
This can then be used like:
<input v-model="ciudad" v-init:ciudad="'{{ old('ciudad') }}'">
Here's the JSFiddle: https://jsfiddle.net/v5djagta/
The easy way to do this for me was in this way:
Laravel Controller
$documento = ReduJornada::where("id_documento",$id)->first();
return view('documentos.redujornada')->with(compact('documento'));
Laravel View
<input class="form-control" id="ciudad" v-model="documento.ciudad" value="{{ old('ciudad', isset($documento->ciudad) ? $documento->ciudad : null) }}" >
Vue.js
data: {
ibanIsInvalid : false,
documento: {
ciudad: $('#ciudad').val(),
}
In this way I can use the same view to create and edit an object, using the same form, even use laravel validation without lost the data after refresh.
If you know a better way to do that please tell me... Thanks
You have to define your value first, for example :
$oldValue = $request->old('value');
and then pass it to vue component, define props and use it in v-model
<script>
export default {
props: {
$oldValue : String,
}
};
</script>
<template>
<input class="form-control" id="ciudad" name="ciudad" type="text" v-model="oldValue">
</template>

Resources