How would I get the value from the hidden input using Cypress? - cypress

I need to save the token which is stored in this hidden input.
This is my request:
cy.request({
method: 'GET',
url: '/auth/login',
body: {
email: email,
password: password,
},
}).then((response) => {
const page = response.body;
});
The response.body returns:
<!DOCTYPE html>
<html>
<body>
<form class="form" action="" method="post" autocomplete="off">
<input id="email" class="form-control" type="text" name="email" placeholder="Email" />
<input id="password" class="form-control" type="password" name="password" placeholder="Password" />
<input type="hidden" name="_token" value="c5LWQtrMVkKXxBFKs1zFzrJYq4PgNifndvcV0F6O">
<button type="submit">Login</button>
Other Login
</form>
</body>
</html>
I'm not sure how I find/grab the value from the hidden input with the name _token

From the cypress CSRF example:
it('strategy #1: parse token from HTML', function () {
// to fetch the login page, and then parse the HTML contents
// to find the CSRF token embedded in the page
cy.request('/auth/login')
.its('body')
.then((body) => {
// we can use Cypress.$ to parse the string body
// thus enabling us to query into it easily
const $html = Cypress.$(body)
const token = $html.find('input[name=_token]').val()
...[see link for full code]
})

Related

Ajax is not submitting the form after button click

I have this form here I am trying to send data to the controller using Ajax but something keeps failing and ajax is not working at all. I am trying to insert a question and sending the quiz id through the form and to the controller
<div id="form_two" class="container col-sm-8">
<div class="row card border-secondary align-items-center">
<div class="form-group col-sm-7">
<br><br>
<form id="report">
#csrf
<input type="hidden" name="quizTest" value="{{ \Illuminate\Support\Facades\Session::get('testID') }}">
<input class="form-control" id="question" type="text" name="question" placeholder="Question" size="40" required><br>
<input class="form-control" id="answerA" type="text" name="answerA" placeholder="Option A" size="40" required><br>
<input class="form-control" id="answerB" type="text" name="answerB" placeholder="Option B" size="40" required><br>
<input class="form-control" id="answerC" type="text" name="answerC" placeholder="Option C" size="40" required><br>
<input class="form-control" id="answerD" type="text" name="answerD" placeholder="Option D" size="40" required><br>
<input class="form-control" id="correct_answer" type="text" name="correct_answer" placeholder="Correct Answer" size="40" required><br>
<button class="btn btn-primary" id="registraion-form" >ADD A QUESTION </button>
</form>
</div>
</div>
</div>
Here is my ajax code that I am trying to send data to the /test endpoint, but when I am submitting the form nothing is printing on the console.log and nothing is being returned from the response from the controller which leads to the conclusion that ajax is not working. When I am pressing the submit button only the URL is changing, what I am doing wrong?
$('#registraion-form').click(function (e) {
e.preventDefault();
let question = $("input[name=question]").val();
let answerA = $("input[name=answerA]").val();
let answerB = $("input[name=answerB]").val();
let answerC = $("input[name=answerC]").val();
let answerD = $("input[name=answerD]").val();
let quizTest = $("input[name=quizTest]").val();
let correct_answer = $("input[name=correct_answer]").val();
$.ajax({
type: "POST",
url: "/test",
data : {
quizTest: quizTest,
question : question,
answerA:answerA,
answerB:answerB,
answerC:answerC,
answerD:answerD,
correct_answer : correct_answer
},
success: function(response) {
console.log(response);
console.log(response.message);
$("#report")[0].reset();
},
error : function (error) {
console.log(error);
}
})
})
just because you have added #csrf to your form, doesn't mean that you're ok on everything.
Since AJAX is submitting a POST request, also that request should have with it the csrf token, otherwise it won't work.
Check for example this question.

reCAPTCHA v3: g-recaptcha-response is outsite the form

With this example of reCAPTCHA v3, the g-recaptcha-response textarea is outsite the form...
<form method="post">
<input type="text" name="name" placeholder="Name">
<input type="text" name="email" placeholder="E-Mail">
<script type="text/javascript">
var onloadCallback = function() {
console.log('onloadCallback');
grecaptcha.execute(
"SITEKEY",
{action: "homepage"})
.then(function(token) {
console.log('verifyCallback')
console.log(token);
}
);
};
</script>
<script src="https://www.google.com/recaptcha/api.js?render=SITEKEY&onload=onloadCallback"></script>
<input type="submit" value="Send">
</form>
So there's no $_POST["g-recaptcha-response"]
What adjustments are necessary to provide the textarea inside the form tags?
You need the hidden input in your form that receives the response and you also need to set the token to the hidden input value
<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" value="" />
document.getElementById('g-recaptcha-response').value = token;
However, I'm also having issues with the recaptcha v.3 implementation in Magento 2.

500 (Internal Server Error) For Ajax POST in Laravel

Please can someone provide a simple example for ajax in laravel 5.1. I have tried everything and still no success. Tried the other solutions here but no luck, maybe it is my copy of laravel, I really don't understand. I just want to see how its done correctly. Please help me out. Thanks.
Route: Route::post('/signin', 'UserController#ajax');
<form action="signin" method="POST" id="form1">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<fieldset>
<p><label for="email">E-mail address</label></p>
<p><input type="email" value="{{ old('email') }}" onBlur="if(this.value=='')this.value='mail#address.com'" onFocus="if(this.value=='mail#address.com')this.value=''" name="email"></p> <!-- JS because of IE support; better: placeholder="mail#address.com" -->
<p><label for="password">Password</label></p>
<p><input type="password" name='password' value="password" onBlur="if(this.value=='')this.value='password'" onFocus="if(this.value=='password')this.value=''"></p> <!-- JS because of IE support; better: placeholder="password" -->
<p><input type="submit" value="Login" name="submit" id="sign"></p>
</fieldset>
</form>
for the controller:
public function ajax(Request $request)
{
if(Request::ajax()) {
$data = Request::all();
print_r($data);
]);
}
And ajax:
$('#sign').click(function(event) {
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
var inputs = $('#form1').serialize();
$.ajax({
url: 'http://localhost/laravel/public/signin',
type: 'POST',
dataType: 'json',
data: inputs,
success: function (data) {
console.log(data);
}
})
return false;
});

AJAX form submitting working but not reaching PHP page

I am trying to submit a form to a PHP file to call a query and submit the form details into the database, however I grabbed this AJAX code off stackoverflow and adjusted it but it seems to be working in a weird way, I'm receiving the alert message whcih I should be receiving when the php page returns "success" (as far as i understand) but the PHP page itself is never reached, I know that because I added a "die" there.
So here's my simplified form:
<form role="form" id="promoProspectForm" type="post">
<div class="form-group">
<label for="name">Full name *</label>
<input name="name" type="text" class="form-control" id="name" placeholder="Enter your name" required>
</div>
<div class="form-group">
<label for="company">Company *</label>
<input name="company" type="text" class="form-control" id="company" placeholder="Enter your company's name" required>
</div>
<div class="form-group">
<label for="url">Website URL *</label>
<input name="url" type="text" class="form-control" id="url" placeholder="Enter your website URL" required>
</div>
<div class="form-group">
<label for="number">Contact number *</label>
<input name="number" type="text" class="form-control" id="number" placeholder="Enter your contact number" required>
</div>
...Some more inputs
</form>
And here's my AJAX code which is included in the HTML page in the footer
$(function() {
$('#promoProspectForm').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'php/submit-prospect.php',
data: $('#promoProspectForm').serialize(),
success: function() {
alert('form was submitted');
}
});
});
});
And here's my submit-prospect.php file:
<?php
die("REACH");
if(isset($_POST) && !empty($_POST))
{
include_once(db.php);
$result = insert_prospect($_POST);
if(!$result)
{
return "fail";
}
else
{
return "success";
}
}
?>
I have also suspected that I have the wrong url to the php file so I tried changing it, basically my index.php is on the root, that ajax function is in js/ajax.js, and the php file i'm trying to reach is in php/submit-prospect.php, so to simplify it:
index.php
js/ajax.js
php/submit-prospect.php
So I tried changing the URL in the ajax to point at "../php/submit-prospect.php" but that also returned the same result.
What am I doing wrong? Thanks.
$(function() {
$('#promoProspectForm').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'php/submit-prospect.php',
data: $('#promoProspectForm').serialize(),
success: function(data) {
alert(data);
}
});
return false; // difference
});
});
return false
in in function "submit" of form, to cancel submit action of html code action .. I hope this help.

submit ajax using anchor tag to spring mvc controller

I am trying to apply ajax with my spring mvc, but couldn't find where I make thing wrong. I try to follow several tutorials but couldn't customize mine to work. It always falls to error state.
So this is my ajax call
function doAjax() {
var username = $('#username').val();
var email = $('#email').val();
var password = $('#password').val();
var json = {
"username" : useranme,
"email" : email,
"password" : password
}
//alert("username: " + username + " email: " + email + " password: " + password);
$.ajax({
type: "POST",
url: $('form').attr('action'),
data: JSON.stringify(json),
dataType: "JSON",
success: function(data) {
},
error:function(data, status, err) {
alert("error");
}
});
};
And this is my form:
<div class="form">
<spring:url var="registerUrl" value="http://localhost:9004/Project/register" htmlEscape="true" />
<form method="post" action="${registerUrl}">
<div class="form_field">
<label for="username">Username</label><br/>
<input class="field" id="username" type="text" name="userName" autocomplete="off"/>
</div>
<div class="form_field">
<label for="email">Email</label><br/>
<input class="field" id="email" type="email" name="email" autocomplete="off" />
</div>
<div class="form_field">
<label for="password">Password</label><br/>
<input class="field" id="password" type="password" name="password" />
</div>
<div class="form_field prefix_clear">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<input id="submit" class="action_button" type="submit" value="Register"/>
</div>
</form>
Click me
</div>
So if I submit the form using the input, it works perfectly. But it doesn's work when I try to submit it using anchor tag. Please help.
To make your ajax call work exactly as a form submit, you should, instead of using the JSON, just replace your data:JSON.stringify to
data:$("form").serialize();
If you have to make a request with JSON data, than you'll have to edit your question with the mapping method and command object to get help, but one thing that is obviously wrong with your code, is that you're not including the _csrf parameters in your ajax request

Resources