Converting from get request from JQuery to Vue.js - javascript

I am new to js and would like to convert my JQuery-based js to Vue. I want to send a get request and output back the data. What is the best way of doing this?
Here is the html:
<div>
<div>
<input type="text" id="var1" placeholder="Search...">
</div>
<div>
<button id="submit">Submit</button>
</div>
</div>
<div>
<p>Results</p>
<p id="results"></p>
</div>
Below is my js:
$(document).read(function() {
$('#var1').keypress(function(e) {
if (e.keyCode == 13)
('#submit').click();
});
});
$(document).ready(function() {
$("#submit").click(function() {
var var1 = document.getElementById("var1").value
// sends get request to URL
$.getJSON("URL" + var1, function(search, status) {
console.log(search);
// cont.
$("#results").text(search.results);
});
});
});
EDIT: Here is what I have so far with axios:
function performGetRequest() {
var var1 = document.getElementById('var1').value;
axios.get('URL', {
params: {
id: var1
}
})
.then(function (response) {
console.log(search);
})
}
I am not sure if the above code is correct or how to factor in keypress and click-- is there a simple way to do that?

Well, I am not sure what you want to do with this ajax call, but hopefully this may help you. Vue is data driven, so I always try to focus on that aspect. So this is an example of how you can access and input and send the data using axios.
<div>
<div>
<input v-model='input' type="text" placeholder="Search...">
</div>
<div>
<button #click="searchInput()">Submit</button>
</div>
</div>
<div>
<p>Results</p>
<p >{{ result }}</p>
</div>
you must have those models in your data
// Your data
data() {
return {
input: '',
result: '',
}
}
and your method will look something like this.
searchInput() {
axios({
method: 'GET',
url: url + this.input,
}).then(response => {
this.result = response.data;
}).catch(error => {
//handle error
})
}
So this is a very basic example. you can do the same process in different ways, you could pass the input to the method or loop over the results, but the idea is taking advantage of Vue.js data driven system and think data first.
Hopefully this will help you, remember to escape your input and add necessary validations. Good luck

Related

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.

Pulling JSON data from API server in Angular 1

Struggling to get http:get to pull a request from a API server in an Ionic app, can anyone help with the code. Here is what I have:
<form ng-submit="getOrders()">
<label class="item item-input item-stacked-label">
<span class="input-label">Search Order #</span>
<input type="text" name="order number" placeholder="enter order number" ng-model="query">
</label>
<input class="button button-block button-positive" type="submit" name="submit" value="Submit">
</form>
$scope.getOrders= function(){
$http.get('http://example.com/api/booking/orders/'+ $scope.query).success(function(data) {
$scope.orders = [ data.data ];
$scope.query = query;
console.log(query);
})
}
Here are a few http get code blocks I have tried without success
//$http.get('http://example.com/api/booking/get/orders/').success(function(data) {
//$http({ url: 'http://example.com/api/booking/orders/', method: "GET", params: {query} }).success(function(data) {
//$http.get('http://example.com/api/booking/get/orders/+ $scope.query').success(function(data) {
//$http.get('http://example.com/api/booking/get/orders/121137').success(function(data) {
//$http.get('js/121137.json').success(function(data) {
Also, here is an example of some working POST code to an API which may provide some extra clues in performing a successful GET query from an API server:
https://plnkr.co/edit/w0cyfzGij8SgcsnbXqsj?p=catalogue
use promise as follows
.then(function(success){
//handle success
})
.catch(function(error){
//handle error
})
this is currect code.
$scope.getOrders= function(){
$http.get('http://example.com/api/booking/orders/'+$scope.query).success(function(data) {
$scope.orders = data.data;
console.log(data);
console.log($scope.query);
})
}

Ember Data not sending data on submit

When I'm submitting the form, I get the following response:
{"data":{"attributes":{"title":null,"description":null},"type":"cards"}}
I'm not sure why I am getting title and description as null.
routes/cards/new.js:
actions: {
save() {
const newCard = this.get('store').createRecord('card', this.get('model'));
newCard.save().then((card) => {
this.transitionTo('cards.all');
});
},
cancel() {
this.transitionTo('cards');
}
}
templates/cards/new.hbs:
<form>
<div>
<label>Title:</label>
{{input type="text" value=model.title}}
</div>
<div>
<label>Body:</label>
{{textarea rows="5" value=model.description}}
</div>
<div>
<button {{action 'save'}}>Speichern</button>
<button {{action 'cancel'}}>Abbrechen</button>
</div>
</form>
Repo link: https://github.com/ghoshnirmalya/hub-client
You are not passing title and description from your .hbs to the route properly. You are creating the model after you fire the action save. Change model.title for title and do the same for the description. Pass them up to your route: {{ save title description }}. Then define two parameters in your save action like: save(title, description). I'm sure you can figure out the rest.
Here is what I usually do in my routes:
setupController(controller /*, model */ ) {
this._super(...arguments);
Ember.set(controller, 'newCard', {}); //newCard is an empty object
},
actions: {
save(newCard) {
Ember.assert('Model is missing or undefined', newCard);
let newCard = this.store.createRecord('card', newCard);
newCard.save().then(( /* response */ ) => {
this.transitionTo('cards.all');
}, (error) => {
//handle error
});
}
}
And in your template you could do something like this:
<form id="save" {{action "save" newCard on="submit"}}>
{{input name="title" id="title" value=newCard.title type="text"}}
<button class="button" type="submit">Save</button>
</form>
Hope this helps. Jeff
In comment you mentioned
doing a console.log(this.get('model')) just prints the model function
That's the answer to your question!. since in route you might have model hook function. so this.get('model') will return function instead of model.
So create controller for cards/new.js and you can move existing save actions. this should work.

SilverStripe submit HTML form through Ajax

I want to pass data from a simple HTML form to a controller through Ajax, then process the data and return a response back.
At the moment I have the following:
HomePage.ss
<form method="POST" class="form-horizontal submit-form" onsubmit="return checkform(this);">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Name</label>
<div class="col-md-8">
<input id="name" name="name" type="text" placeholder="insert full Name" class="form-control input-md" required="" />
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="send-btn"></label>
<div class="col-md-8">
<button id="send-btn" name="send-btn" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
JavaScript
$('form.submit-form').submit(function() {
$.ajax({
type: 'POST',
url: 'processForm',
data: $(this).serialize(),
success: function(data) {
alert('data received');
}
});
});
HomePage.php
class HomePage_Controller extends Page_Controller {
public function events() {
$events = CalendarEvent::get();
return $events;
}
public function processForm() {
if (Director::is_ajax()) {
echo 'ajax received';
} else {
//return $this->httpError(404);
return 'not ajax';
}
}
}
In developer tools I can see that I got the xhr processForm with a 404 not found error.
How do I get this Ajax form working correctly with the SilverStripe controller?
Spider,
I've done something similar to below. This is a quick and dirty demo and hasn't been tested, but it may get you going in the right path. If you're unfamiliar with how forms work within SilverStripe there is a lesson for front end forms in SilverStripe. I've found the lessons useful personally and provide the code for the lesson as well: http://www.silverstripe.org/learn/lessons/introduction-to-frontend-forms?ref=hub
Page.php
<?php
class Page extends SiteTree
{
}
class Page_Controller extends Content_Controller
{
private static $allowed_actions = array(
'MyForm',
);
public function MyForm()
{
Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.min.js');
Requirements::javascript(THIRDPARTY_DIR . '/jquery-validate/jquery.validate.min.js');
Requirements::javascript('/path/to/your/validation/script.js');
$fields = FieldList::create(
TextField::create('name')
->setTitle('Name')
);
$actions = FieldList::create(
FormAction::create('doSubmit')
->setTitle('Submit')
);
$requiredFields = RequiredFields::create(
'name'
);
$form = Form::create($this, 'MyForm', $fields, $actions, $requiredFields);
return $form;
}
public function doSubmit($data, $form)
{
//process $data or create your new object and simpley $form->saveInto($yourObject); then $yourObject->write()
//then deal with ajax stuff
if ($this->request->isAjax()) {
return $this->customise(array(
'YourTemplateVar' => 'Your Value'
))->renderWith('YourIncludeFile');
} else {
//this would be if it wasn't an ajax request, generally a redirect to success/failure page
}
}
}
YourValidationScript.js
(function ($) {
$(function () {
$('#MyForm_Form').validate({
submitHandler: function (form) {
$.ajax({
type: $(form).attr('method'),
url: $(form).attr('action') + "?isAjax=1",
data: $(form).serialize()
})
.done(function (response) {
$('.content').html(response);
})
.fail(function (xhr) {
alert('Error: ' + xhr.responseText);
});
},
rules: {
name: "required"
}
});
})
})(jQuery);
You need to understand how HTTP request routing is handled in SilverStripe.
When you send request POST /processForm, it is treated as page and managed by ModelAsController. That is why you get 404 error - there is no SiteTree record with URLSegment = processForm.
Solution 1
Use Form object. It creates all routing configuration automatically during runtime. Read more
https://docs.silverstripe.org/en/3.3/tutorials/forms/
https://docs.silverstripe.org/en/3.3/developer_guides/forms/
Solution 2
Use this approach, when you really want to go down to the simple one method request handler. Register custom controller and routing.
You specify your route in mysite/_config/routing.yml
---
Name: siteroutes
---
Director:
rules:
processCustomForm: CustomFormController
Handle your request
class CustomFormController extends Controller
{
public function handleRequest( SS_HTTPRequest $request, DataModel $model ) {
if (!$request->isPost()) {
// handle invalid request
}
$name = $request->postVar('name')
// process your form
}
}

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