Sorry for my English!
I work with Axios not so long ago, I am constantly tormented. Actually, I need to transfer the “data” from Vue through Axios for myself to the PHP controller, after the Axios method is triggered, I do dd ($ request) and see the void, tell me what could be the problem, thanks!
P.S. I am still confused that the 'data' in the console is displayed in 'config' and in the field 'data' above some kind of giant script is above the config. So it should be? or is there a problem? (see screenshots of the console below).
<div id="blank">
<form>
<div class="form-grup">
<label></label>
<input type="text" class="myform" name="kladr" v-model="kladr">
</div>
<div class="form-grup">
<label></label>
<input type="text" class="myform" name="ownerKladr" v-model="ownerKladr">
</div>
<div class="form-grup">
<label></label>
<input type="text" class="myform" name="insurancePeriod" v-model="insurancePeriod">
</div>
<button #click.prevent="storeBlank">Accept</button>
</form>
</div>
var blankjs = new Vue({
el: '#blank',
data() {
return {
kladr: '',
ownerKladr: '',
insurancePeriod: ''
}
},
methods: {
storeBlank() {
let url = '/blank/' + encodeURIComponent(this.user) + '/save';
let data = {
kladr: this.kladr,
ownerKladr: this.ownerKladr,
insurancePeriod: this.insurancePeriod
}
axios.post(url, data)
.then(function (response) {
console.log(response)
})
}
}
})
// PHP
/**
* #Route("/blank/{user}/save", name="save_blank")
*/
public function storeBlank(Request $request, User $user): Response
{
dd($request); //or dd(json_encode($request));
}
This is what I get in console.log:
data: "<script> Sfdump = window.Sfdump || (function (doc)…re><script>Sfdump("sf-dump-1008019515")</script>↵", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
config:
adapter: ƒ (e)
data: "{"data":{"kladr":"", "ownerKladr":"", "insurancePeriod":""}}"
headers:
Accept: "application/json, text/plain, */*"
Content-Type: "application/json;charset=utf
Your data is inside of data object. Here is example:
axios.post(url, data)
.then(function (response) {
console.log(response.data);
});
Also your request can be failed. You can handle error witch catch method.
axios.post(url, data)
.catch(function(error){
//if your request fail this block will be executed. otherwise 'then' statement will work
})
.then(function (response) {
console.log(response.data);
});
Related
My Goal
I would like to display the error messages in the Form. But for this I would need to have access to the JSON?
Code
HTML blade
<form>
<input name="name">
<p class="text-red-500 text-xs italic">Please fill out this field.</p> {{-- $message --}}
<button id="submit">SUBMIT</button>
</form>
javascript
<script>
const submitBtn = document.getElementById('submit');
submitBtn.addEventListener('click', (e) => {
e.preventDefault();
const fel = document.getElementById('commentForm');
const formData = new FormData(fel);
const url = '/api/comments';
let fetchData = {
method: 'POST',
body: formData,
headers: new Headers()
}
fetch(url, fetchData)
.then(response => {
if (!response.ok) {
return Promise.reject(response);
}
return response.json();
})
.then(data => {
console.log("Success");
console.log(data);
})
.catch(error => {
if (typeof error.json === "function") {
error.json().then(jsonError => {
console.log("Json error from API");
console.log(jsonError);
}).catch(genericError => {
console.log("Generic error from API");
console.log(error.statusText);
});
} else {
console.log("Fetch error");
console.log(error);
}
});
</script>
Response after a faulty request
HttpStatus: 400
// console.log(res) output
Response { type: "basic", url: "http://127.0.0.1:8000/api/comments", redirected: false, status: 400, ok: false, statusText: "Bad Request", headers: Headers, body: ReadableStream, bodyUsed: false }
body: ReadableStream { locked: false }
bodyUsed: false
headers: Headers { }
ok: false
redirected: false
status: 400
statusText: "Bad Request"
type: "basic"
url: "http://127.0.0.1:8000/api/comments"
<prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }
repellendus-dolor-quibusdam-sint-qui-news:147:29
Problem
In the Devtool Network tab, when I go to response of the request, I get a JSON
JSON: {"comment_content":["The comment content field is required."],"comment_name":["The comment name field is required."]}
When I output res.json() via the console within my fetch method, I get a Promise:
XHRPOSThttp://127.0.0.1:8000/api/comments
[HTTP/1.1 400 Bad Request 100ms]
Promise { <state>: "pending" }
<state>: "fulfilled"
<value>: Object { comment_content: (1) […], comment_name: (1) […] }
comment_content: Array [ "The comment content field is required." ]
comment_name: Array [ "The comment name field is required." ]
<prototype>: Object { … }
Additional question:
Is there a better way to display the errors from the response in the form? Maybe with the help of the form data object?
Considering you are making the request from JavaScript means you will also need to update the UI to reflect any error states. This includes targeting the right input elements based on the validation errors and appending them to the DOM. There may be libraries which can make this easier on the JS side but ultimately, you will need to write this logic.
As an aside, if you were using a traditional POST request, Laravel provides the $errors variable and #error blade directive. These help check for / display validation errors and are available in your application views. Since you are using blade, you may want to consider this.
I am trying to learn AWS and practice using a static website to query Cloudtrail data via a Lambda function. However whenever I input data from my website and from my GET API function and query it, it only returns status code 300(which is a failure alert). I am not sure if it is something to do with my API gateway, my HTML/AJAX, or my Lambda function itself. I am using Python for my Lambda function with Boto3. Any advice or help be greatly appreciated as I am stuck. Thanks!
AJAX Code
<script>
function retrieveFromAPI(){
var param1 = $("#EventName").val()
$.ajax({
type: "GET",
data: param1,
datatype: "json",
url: "GET API URL",
success: function(data){
console.log("Got it", param1)
$("#lbl").html(data)
},
error: function(data){
alert("Unsuccessful Search....Try Again Please. " + param1 +(" was not found") + JSON.stringify(data.responseText));
}
});
};
</script>
HTML Form
<form id="retrieve-form" method="GET">
<h2>Select a Service to Query From</h2>
<label for="CloudTrail">CloudTrail Name: </label>
<input type="text" id="EventName" placeholder="Enter Cloudtrail Name" name="EventName">
<button id="submit" type="button" Onclick="retrieveFromAPI(event)" value="submit">Submit</button>
<label id="lbl"></label>
</form>
Lambda Function
import boto3
client = boto3.client('cloudtrail')
#If the event name is in the list then return event name, or return nothing
def lambda_handler(event, context):
if 'EventName' in event :
EventName = event['EventName']
response = client.lookup_events(
LookupAttributes=[
{
'AttributeKey': 'EventName',
'AttributeValue': EventName,
},
]
)
else :
EventName = '*';
response = client.lookup_events(
LookupAttributes=[
{
'AttributeKey': 'EventName',
'AttributeValue': EventName,
},
]
)
#If the length of the response is greater than zero, it will make a list of the events
if len(response['Events']) > 0 :
events = []
for event in response['Events']:
CloudTrailEvent = json.loads(event['CloudTrailEvent']);
events.append({ "awsRegion" : CloudTrailEvent['awsRegion'] , "EventId" : event['EventId'], "EventName" : event['EventName'] , "EventTime" : str(event['EventTime']), "requestID" : CloudTrailEvent['requestID']})
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
'Access-Control-Allow-Origin': '*'
},
'body': events
}
else :
return {
'statusCode': 300,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
'Access-Control-Allow-Origin': '*'
},
'body' : 'No record found.',
}
```s
im working on a rails API + Javascript project, with a simple form on html. Everytime I hit the submit button, all my code is executed but then the browser page reloads.
Here is the HTML code:
<form id="create-player">
<h3>Enter Your Name</h3>
<input
type="text"
name="name"
value=""
placeholder="Enter your name..."
class="input-text"
/>
<br />
<input
type="submit"
name="submit"
value="SUBMIT"
class="submit"
/>
</form>
Then my js code:
document.addEventListener("DOMContentLoaded", () => {
//submit form action
player_form.addEventListener("submit", function(a){
a.preventDefault();
console.log('submit pressed')
fetchNewPlayer(a.target.name.value);
});
})
function fetchNewPlayer(name){
console.log('start fetch')
let formData = {
name: name
}
let configObj = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(formData)
};
fetch('http://localhost:3000/players', configObj)
.then(function(response) {
console.log('fetching', response);
return response.json();
})
.then(function(object) {
console.log('then', object);
})
.catch(function(error) {
console.log('failed', error);
alert("Error");
});
}
Crazy part is, that if I comment the fetchNewPlayer, the page doesnt reloads. Can someone help me understand whats wrong?
You need to use an AbortController:
let abortController = new AbortController();
let configObj = {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify(formData),
signal : abortController.signal
};
window.onbeforeunload = function(e) { abortController.abort(); };
fetch('http://localhost:3000/players', configObj)
...
I wrote a rest webservice and to avoid the error I got in my java code which is:
The registered message body readers compatible with the MIME media type, I have to add to my $http.post a 'Content-Type': 'application/x-www-form-urlencoded' or 'Content-Type': 'application/json'.
I am using Angularjs 1.3.5 and whenever I tried to add the headers {content-type.... }, I failed. What can I do exactly to solve my problem?
$scope.save = function(url,data) {
var data_stack = $scope.stack;
$http.post(url, data_stack)
.then(
function(response){
},
function(response){
});
}
<form ng-submit="save()">
<input ng-model="stack"></input>
<button type="submit">Save</button>
</form>
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type':'application/x-www-form-urlencoded'
// or 'Content-Type':'application/json'
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
I have a some problem with authorization in my app. I realize it through factory and controller, post method send request, but in response i have log from server, that values are wrong.
But if I change body of doLogin function to jQuery ajax method and don't use factory, all is OK. What is wrong with my Angular way?
My AngularJS Code
Form:
<form ng-submit="doLogin(credentials)">
<div class="list">
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" ng-model="credentials.email">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" ng-model="credentials.password">
</label>
<label class="item">
<button class="button button-block button-positive" type="submit">Log in</button>
</label>
</div>
</form>
Factory:
.factory('Somepost', function ($http) {
return{
doPost: function (credentials, callback) {
console.log('service');
console.log(credentials);
return $http({
url:'http://cronicls.ru/auth/login',
method: 'POST',
data: credentials,
async : true
}).success(callback);
}}})
Login function in controller:
$scope.doLogin = function(credentials) {
var successCallback = function (data) {
console.log(data);
}
Somepost.doPost(credentials, function(data) {
console.log(data);
});
};
Function doLogin with $.ajax (working successfully):
$scope.doLogin = function(credentials) {
var successCallback = function (data) {
console.log(data);
}
var login = function(credentials, successCallback) {
$.ajax({
type: "POST",
url: 'http://cronicls.ru/auth/login',
async : true,
data: credentials,
success: function(data){
console.log('login success');
console.log(data);
successCallback();
},
error: function(data){
console.log('/auth/login: error');
console.log(data);
}
});
};
login(credentials, successCallback);
};
but in response i have log from server, that values are wrong.
Actually not, because it returns a promise and you have to do something like this in your callback:
As per your comment :
It's PHP with ZF on server side. Actually you need to change the default content Type header from application/json to application/x-www-form-urlencoded
Change in factory:
.factory('Somepost', function ($http) {
return{
doPost: function (credentials, callback) {
console.log('service');
console.log(credentials);
return $http({
url:'http://cronicls.ru/auth/login',
method: 'POST',
data: credentials,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}, // <-- override the default contentType header
async : true
}).then(callback); // change to then instead of success
}}})
I found the answer of my problem. Thanks to #Jai for hint about ZF. Actually we need to wrap data in $.param(). So, working factory is:
.factory('Somepost', function ($http) {
return{
doPost: function (credentials, callback) {
return $http({
url:'http://cronicls.ru/auth/login',
method: 'POST',
data: $.param(credentials),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(callback);
}
}
})