i built a registration form and validated it using javaScript. but i want after a user filled the form, it should post to the server. i am confused on where to place my httpRequest function. i don't know if its after validation or inside the validation function
This is my validation function
function formregister(e){
if (first_name.value=== "" || last_name.value=== "" || user_id.value==="" || id_type.value=== ""
|| id_no.value=== "" || address.value==="" || !terms.checked) {
var fPassResult = '1';
} else{
var fPassResult = '0';
}
if(fPassResult === "1") {
window.location = "register.html";
}else{
Swal.fire({
type: 'success',
title: 'Your Registration has been Submitted Successfully',
text: 'Click Ok to Login',
timer: 10000
}
).then(function(){
window.location="Login.html";
})
}
e.preventDefault();
};
**And this is my post request function**
function registerationApiCall(e){
var data = {
"user_id":"user_id.value",
"user_pin": "user_pin.value",
"first_name":"first_name.value",
"last_name":"last_name.value",
"address":"address.value",
};
fetch("jehvah/api",{
type : 'POST',
data : data,
dataType : 'JSON',
encode : true,
success: function (response, status, xhr) {
if (result==="OK") {
console.log("success");
}else{
console.log("bad");
}
},
error: function (xhr, status, error) {
console.log("something went wrong");
}
});
}
Please kindly check my post request function, i dont know if i am doing it the right way
Hi ✌ when fPassResult === "0" in this case inside else{} call registerationApiCall()
you tell the user it's a success after you get OK from the server which is Asynchronous call
& inside fetch response you call swal.fire
for this code to work your server when checks the database & every thing is ok returns a msg like this {"msg":"OK"}
CODE:
else{
registerationApiCall()
}
function registerationApiCall becomes
fetch('jehvah/api',
{ method: 'POST',headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)})
.then((response) => response.json())
.then((result) => {
console.log('Success:', result);
if (result.msg="OK") {
console.log("success");
Swal.fire({
type: 'success',
title: 'Your Registration has been Submitted Successfully',
text: 'Click Ok to Login',
timer: 10000
}).then(function(){window.location="Login.html";})
}else{ console.log("usres exsists / etc");}
})
.catch((error) => {
console.log("something went wrong");
});
}
Also in the request payload you sent a group of strings not the variables containing the form values
Here
var data = {
"user_id":"user_id.value",
"user_pin": "user_pin.value",
"first_name":"first_name.value",
"last_name":"last_name.value",
"address":"address.value",
};
Change that to
var data = {
"user_id":user_id.value,
"user_pin": user_pin.value,
"first_name":first_name.value,
"last_name":last_name.value,
"address":address.value
};
Looking at the fetch documentation (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch), success and error does not exists.
The fetch function returns a Promise, so you can handle results as any Promise should do:
fetch("jehvah/api", {
method: 'POST',
body : JSON.stringify(myDataObject)
})
.then(blob => blob .json())
.then(result => console.log('Success!!))
.catch(e => console.log('Failure :('))
Related
i want to apply validations on email if email is valid or not , and after that check in db using ajax to verify email already exist and email already exixt check should work if first check is passed , here is what i did , iam stucked in email_already_exist check that how to validate only if above check is passed , if anyone have idea how to do that
// code which checking email is valid
email: ko.observable((ref = REGISTRY.unsavedUser) != null ? ref.email : void 0).extend({
required: true,
email: {
params: true,
message: 'Please enter a valid email.'
},
focus:true
}),
// function to check email exists
var email_exist_check = function() {
var errorElement = $('#parent-email-signup');
var emzil = errorElement.val();
return = $.ajax({
url: '/api/v3/email_exists',
method: 'POST',
async: false,
data: {
email: emzil
},
success: function(data){
console.log(data);
},
error: function (response, status) {
showFlashMessage('An error occured, please try again later.', 'error');
}
});
};
email exist function is ready iam stucked that how to use in the above code
please help
Never, never never use async: false on Ajax calls.
What you need:
An API wrapper, for convenience and code readability later.
const API = {
email_exists: function (email) {
return $.post('/api/v3/email_exists', {
email: email
}).then(function (result) {
// evaluate result & return true (email exists) or false (email is free)
return ...;
}).fail(function (jqXhr, status, error) {
showFlashMessage('An error occured, please try again later.', 'error');
console.log('Error in email_exists', email, jqXhr, status, error);
});
},
// add other API functions in the same way
};
and async validation rule that calls your API:
ko.validation.rules.emailFromAPI = {
async: true,
validator: function (val, params, callback) {
API.email_exists(val).done(function (exists) {
callback(!exists); // validation is successful when the email does not exist
});
},
message: 'Please enter a valid email.'
};
an observable that uses this rule:
email: ko.observable((ref = REGISTRY.unsavedUser) != null ? ref.email : void 0).extend({
required: true,
emailFromAPI: true,
focus:true
}),
Since ajax is asynchronous you'll have to wait for the server response, returning the ajax call will not wait for the server call to resolve. One way to solve this is using a callback (another would be promises with async/await)
var email_exist_check = function(email, onSuccess, onError) {
$.ajax({
url: '/api/v3/email_exists',
method: 'POST',
async: false,
data: { email },
success: function(data){
console.log(data);
if (data && !data.error) { return onSuccess(); }
return onError(data && data.error);
},
error: function (response, status) {
onError(response);
}
});
};
// After doing a front-end email verification
email_exist_check(ref.email, () => {
console.log('Email is valid');
}, (error) => {
console.error('Something went wrong', error);
});
I have a function which uses jquery to call API and get a result. My API end is programmed to return the number "19" just for testing.
export function clientAdd(data) {
return (dispatch) => {
return $.ajax({
url: "http://api.example.com/client/add/",
headers: {'AUTHORIZATION': `${sessionStorage.jwt}`},
type: 'POST',
cache: false,
data: data,
dataType: 'json',
success: function (data) {
let redirectUrl = '/client/' + data
return redirectUrl';
},
error: function(xhr, status, err) {
if (xhr.status === 401) {
sessionStorage.removeItem('jwt');
return '/signin';
}
console.log('xhr',xhr.responseText);
console.log('status',status);
console.log('err',err);
return dispatch({type: GET_CLIENT_FAIL, err});
}
})
}
}
Then in my component, upon clicking on the submit button, it will call the onSave function as follows
onSave(event) {
//event.preventDefault();
this.props.actions.clientAdd(this.state.credentials).then((result) => {
return this.setState({redirect: true, newCustomerId: result})
}).catch((result) => {
return this.setState({redirect: false, errorMessage: result})
});
}
Where the result is supposed to be the redirectUrl or ErrorMessage.
However, I'm keep getting the number 19 which is returned by my API.
I read online if I want to use promise in my component, i have to add return infront of $.ajax, if not "then" will be undefined.
What you can do is, create your own promise and put the ajax call inside it
Then call resolve and pass data that you want when then is called
resolve(data_passed_to_then)
Like this :
return new Promise((resolve,reject) => {
$.ajax({
...
success: function (data) {
let redirectUrl = '/client/' + data
resolve(redirectUrl);
},
error: function(xhr, status, err) {
...
// return dispatch({type: GET_CLIENT_FAIL, err});
reject(err);
}
})
})
I have a REST API running and I am posting some data to it using JQuery.
This is how my JQuery code looks:
$(document).ready(function () {
$('#login-form').submit(function () {
var user = $('#uname').val();
var pass = $('#pwd').val();
alert('username = ' + user);
alert('password = ' + pass);
var JSONObject = { 'userName': user, 'password': pass };
var jsonData = JSON.parse(JSONObject);
$.ajax({
url: 'http://127.0.0.1:8080/user/login',
method: 'POST',
data: { userName: user, password: pass },
dataType: 'JSON',
contentType: 'application/json',
success: function (data, status, jqXHR) {
//Do something
console.log('data = ' + data);
},
error: function (jqXHR, status, errorThrown) {
alert('error ' + errorThrown);
}
});
});
});
However, this code is unable to access the API. I do not get the expected message in the server log.
When the Submit button of the form is clicked, the browser gets reloaded and it shows the form inputs in the url. That is all.
My API is written using Java and this is the relevant method.
#RequestMapping(value = "/user/login", method = RequestMethod.POST)
public ResponseEntity<User> logUser(#RequestBody User user){
User loggedUser = loginService.authenticateUser(user);
if(loggedUser != null){
System.out.println("User found");
return new ResponseEntity<User>(loggedUser, HttpStatus.ACCEPTED);
}else{
//user does not exsits
System.out.println("User not found");
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
I really can't understand what is wrong. No any error is shown. Can somebody point me out why this happens and how to fix this issue.
The issue is that the browser is reloading on submit event.
You need to add preventDefault() method like this
$("#login-form").submit(function (event) {
event.preventDefault()
//further code here
This will prevent the browser from reloading
I'm trying to send data to the server API from a webpage but it keeps falling to
'No Connection!' as you will see in the code.
Note:The server, database and the API are working, because I also use it on a phone application that do the same as I'm trying to do here which is post an event to the database.
Here is the webpage code:
function onAddEvent(){
var title = document.getElementById("title").value;
var desc = document.getElementById("desc").value;
var date = document.getElementById("date").value;
var userid = localStorage.getItem("userid");
$.ajax({
url: API_URL,
type: 'POST',
data: {eventname: title, eventdate: date, eventdesc: desc, user_id: userid},
async: true, // set the property here
success: function(data) {
if(data.result == "success"){
alert("Add Event Successfully!");
}
else{
alert("Can't add event");
}
},
error: function(xhr, error) {
//It is falling here
alert('No Connection!');
}
});
}
And here is the PHP API that it will connect to:
function addevent()
{
$new_member_insert_data = array(
'eventname' => $this->input->post('eventname'),
'eventdate' => $this->input->post('eventdate'),
'eventdesc' => $this->input->post('eventdesc'),
'user_id' => $this->input->post('user_id')
);
$insert = $this->db->insert('event', $new_member_insert_data);
return $insert;
}
Remove the code from the function or try calling the function in the API.
//Call the function from your API
addevent();
function addevent()
{
$new_member_insert_data = array(
'eventname' => $this->input->post('eventname'),
'eventdate' => $this->input->post('eventdate'),
'eventdesc' => $this->input->post('eventdesc'),
'user_id' => $this->input->post('user_id')
);
$insert = $this->db->insert('event', $new_member_insert_data);
return $insert;
}
When the session is expired, User cant log back in without a page refresh because the _token in ajax headers is expired(AKA TokenMismatchException). I cant handle the exception by redirecting user to a log in page because the login is an overlay modal and the request is handled via ajax.
I thought i could catch the mismatch exception in Handler.php and return a json response with a session token. and on the client side, use the new token to continue the intended process. However, when i use the new token passed from server, the session token will be changed again on server side which results another TokenMismatchException.
So how should i handle the exception in a secured way without refreshing a page?
Here's what i have right now:
setup csrf_token in a global js file:
$(function () {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf_token"]').attr('content') }
});
});
render method in app/exceptions/handler.php:
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else if ($e instanceof TokenMismatchException)
{
if ($request->ajax()) {
return response()->json([
'message' => 'TokenMismatchException',
'token' => csrf_token()
]);
}
}
else
{
return parent::render($request, $e);
}
}
in authentication.js:
$.ajax({
type: "POST",
url: "/auth/login",
data: {
"email" : $('#login_email').val(),
"password" : $('#login_password').val(),
'remember': $('#login_remember').is(':checked')
},
success: function(response) {
if (response.message === 'TokenMismatchException') {
console.log(response); //message and token exist
//if catch the exception, use the new token to set up the ajax headers and login again
$.ajaxSettings.headers["X-CSRF-TOKEN"] = response.token;
console.log($.ajaxSettings.headers["X-CSRF-TOKEN"]);
$.ajax({
type: "POST",
url: "/auth/login",
data: {
"email" : $('#login_email').val(),
"password" : $('#login_password').val(),
'remember': $('#login_remember').is(':checked'),
},
success: function(res) {
console.log(res);
},
error: function(err) {
console.log(err);
}
});
}
console.log('logged in');
},
error: function(xhr, status, err) {
}
});
thanks in advance.
In your render function, you've to check for a specific TokenMismatchException. So may be you can try something like this:
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return response()->json('msg', 'Your session has expired. Please try again.');
}
You may also pass a new csrf_token along with the json so that you can replace the old one with the new one and send the form request again.
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return response()->json(['msg'=> 'Your session has expired. Please try again.', 'token'=> csrf_token()]);
}
I haven't tested this code. But this should get you started.
Also, if you want, you can use a package: https://github.com/GeneaLabs/laravel-caffeine