PHP is not returning data to AJAX - javascript

I'm testing a login form that submits data via Ajax to the PHP processing file. Once I click the submit button it just redirects me to PHP file and not returning data from PHP. The form is inside a bootstrap modal. I'm just new to jquery and ajax so I hope someone helps. Thanks
HTML
<form action="login-process.php" id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>
JQuery script is placed at site footer after jquery.js cdn
$(document).ready(function(){
// Process form
$('#test-form').submit(function(event){
// get form data
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
// process the form
$.ajax({
type : 'POST', // define the HTTP method we want to use
url : 'process.php', // url to send data
data : formData, // data object
dataType : 'json', // what type of data to expect back from server
encode : true
})
// using done promise call back
.done(function(data){
// log data to console
console.log(data);
if (data.email-msg) {
alert("success");
}
});
// stop the form from submitting and refresing the page
event.preventDefault();
});
});
process.php
<?php
$data = array(); // array to hold pass back data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['login-email'];
$password = $_POST['login-pass'];
$data['email-msg'] = $email;
$data['pw-msg'] = $password;
echo json_encode($data);
} ?>

try this brother
$(document).ready(function(){
$('#test-form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"action="login-process.php" ",
method:"POST",
data:$(this).serialize(),
success:function(data){
console.log("data send");
}
})
});
});
<form id="test-form" method="post">
<div class="form-group">
<input type="hidden" name="login-form">
<input type="email" class="form-control form-control-lg" name="login-email" id="loginEmail" placeholder="Email address" required>
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="login-pass" id="loginPassword" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-primary mb-4">Sign in</button>
</form>

You Have syntax error in javascript code.
change your code
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val();
};
to
var formData = {
'email' : $('input[name=login-email]').val(),
'password' : $('input[name=login-pass]').val()
};
It will solve the problem

Related

JS - recaptcha v3 - how to verify captcha and submit form data to another file

I'm just starting with JS and like to implement a form that verifies for robots/humans by using captcha v3 on the client side and if verification succeeds the data should be submitted to another file.
This is what I got so far. I know it's wrong, but unsure what the correct logic is. Hope someone can shed a light. Thx!
<script src="https://www.google.com/recaptcha/api.js?render=6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></script>
<script type="text/javascript" src="/js/libs/jquery-1.11.3.min.js"></script>
<section class="cc-column-component regular-grid">
<form id="bank-form" class="form clear one-full cf-contact-form" action="?" method="POST" data-tracking="contact_sales">
<div>
<label class="label mandatory bank-color bank-label" for="firstName">First Name</label>
<input id="firstName" value="Pepe" type="text" class="one-full bank-color-grey bank-input" name="firstName" placeholder="First Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getFirstName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="lastName">Last Name</label>
<input id="lastName" value="Chanches" type="text" class="one-full bank-color-grey bank-input" name="lastName" placeholder="Last Name" autocomplete="off" data-validate="true" data-type="text" data-min="3" value="<?php isset($this) ? print $this->getLastName() : print ''; ?>">
<br/>
<label class="label mandatory bank-color bank-label" for="email">Email</label>
<input value="asdf#asdf.com" id="email" type="text" class="one-full bank-color-grey bank-input" name="email" placeholder="Email" autocomplete="off" data-validate="true" data-type="email" value="<?php isset($this) ? print $this->getEmail() : print ''; ?>">
<br/>
</div>
<div class="row inline one-full">
<br/>
<!-- <div class="g-recatpcha" data-sitekey="6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ"></div> -->
<button type="submit"
id="form-submit"
value="submit"
>
<a>Submit form</a>
</button>
<div class="field inline one-full">
<br/>
</div>
<!-- <input type="hidden" name="recaptcha_response" id="recaptchaResponse"> -->
</div>
</form>
</section>
<script>
$('#bank-form').submit(function(event) {
console.log('subtmitting');
event.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('6Lc3UZkeAAAAAMt6wcA-bYjLenFZPGv3K5AqfvuQ', {action: 'submit'}).then(function(token) {
console.log('🚀 ~ grecaptcha.execute ~ token', token)
$('#bank-form').prepend('<input type="hidden" name="token" value="' + token + '">');
$('#bank-form').prepend('<input type="hidden" name="action" value="submit">');
// $('#bank-form').unbind('submit').submit();
});;
});
CheckCaptcha(token)
});
function CheckCaptcha(token) {
var token = $("#token").val()
console.log('🚀 ~ token', token)
var action = $("#action").val()
var RECAPTCHA_V3_SECRET_KEY = "6Lc3UZkeAAAAAIG8bVZDpkheOxM56AiMnIKYRd6z"
$.ajax({
type: "POST",
url: "http://www.google.com/recaptcha/api/siteverify",
data: JSON.stringify([{secret: RECAPTCHA_V3_SECRET_KEY }, {response : token }]),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// __doPostBack('form-submit', '');
if(response["score"] >= 0.7) {
console.log('Passed the token successfully');
}
},
failure: function (response) {
// set error message and redirect back to form?
console.log('Robot submit', response);
}
})
return false;
}
</script>

Laravel Ajax request throwing MethodNotAllowedException with post method

I am new to the Laravel and I am trying to submit post data via Ajax in Laravel and it throws
MethodNotAllowedException but when I submit the form via post it does work but refresh the page although I have used Ajax.
my Code is as below:
My JavaScript Ajax code:
function collect(){
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $("input#token").val()
}
});
const user = [{"fname": $("input#fname").val(), _token: $("input#token").val(), _method:"POST", "lname": $("input#lname").val(),
"email": $("input#email").val(), "pass": $("input#pass").val(),
"confirm-pass": $("input#confirm-pass").val()
}];
var form = $('form#add-user-form');
var send_button = $('button#send').text();
$.ajax({
url: '/users/store',
method: 'post',
data: user,
processData: false,
dataType: 'json',
contentType: false,
beforeSend:function(){
$(form).find('span.error-text').text('');
},
success:function(data){
alert('data sent');
if (data.code == 0 || data.status == 400 ){
$.each (data.error, function(prefix, value){
alert(prefix + ' ' + value[0]);
$(form).find('span.'+prefix+'_error').text(value[0]);
});
}else {
$(form)[0].reset();
alert(data.msg)
}
}
});
}
--- Controller Code ------------------------
$validator = \Validator::make($request -> all(), ['fname' => 'required|min:5|max:25',
'lname' => 'required|min:5|max:25',
'email' => 'required|email|unique:users',
'pass' => 'required|min:8|max:20|',
'confirm-pass' => 'required|min:8|max:20'
]);
if (!$validator -> passes() ){
return response()->json(['code'=> 0, 'error'=> $validator->errors()->toArray()]);
}else {
$user = new users();
$user -> name = $request -> fname ;
$user -> email = $request -> email ;
$user -> password = $request -> pass;
$query = $user -> save();
if ( !$query ){
return response() -> json(['code'=> 0, 'msg' => 'something went wrong']);
}else {
return response() -> json(['code' => 1, 'msg' => 'users has been successfully
added']);
--------------- HTML Code which -------------
<div id="registeration-form">
<div id="form-holder container">
<form action="{{ route('users.store') }}" method="post" class="registration needs-`
validation" id="add-user-form">
<input type="text" class="form-control" id="fname" name="fname" placeholder="
First Name" required> </input>
<span class="text-danger error-text fname_error"></span>
<input type="text" id="lname" class="form-control" name="lname" placeholder="
Last Name " required> </input>
<span class="text-danger error-text lname_error"></span>
<input type="text" class="form-control" id="email" name="email"
placeholder="Your Email " required> </input>
<span class="text-danger error-text email_error"></span>
<input type="password" class="form-control" id="pass" name="pass"
placeholder="Password " required> </input>
<span id="text-danger error-text pass-span pass_error"> </span>
<input type="password" class="form-control" id="confirm-pass" name="confirm-
pass" placeholder="Confirm Password " required> </input>
<span id="text-danger error-text con-pass confirm-pass_error"> </span>
<input type="hidden" id="token" name="_token" value="{{ csrf_token() }}" />
<button type="button" class="btn btn-outline-primary" id="send"
onClick="collect();">Create Account </input>
</form>
</div>
</div>
My Route web.php file
Route::post('/store', 'usersController#store');
Route::post('store',[usersController::class, 'store'])->name('users.store');
What I want is that the Ajax should work without page refresh and
> it does through MethodNotAllowedException Line 251
Thank you all for your cooperation in this matter, I have resolved this issue with below changes.
I have added a route in route/api.php
Route::post('store', [usersController::class,'store']);
I have changed my Ajax sent url as below.
url: $('form#add-user-form').attr('action'),
That worked for me to resolve the issue.
#steven7mwesigwa Thank you for your answer, it was really helpful.
You must provide route for ajax request into route/api.php
use this instead of your current ajax configs:
url: '{{route('users.store')}}',
type: 'post',
data: user,
processData: false,
dataType: 'json',
contentType: false,
first of all it's better to use blade routes instead of writing the url, and secondly it's "type" not "method" when you're trying to use POST method in ajax
The route below doesn't exist.
$.ajax({
// ...
url: '/users/store',
// ...
});
Use this instead:
Note that you don't have to construct the data manually.
$.ajax({
// ...
type: form.attr("method"),
url : form.attr("action"),
data: form.serializeArray(),
// ...
});
NOTES:
Note that the 2 routes are the same:
Route::post('/store', 'usersController#store');
Route::post('store',[usersController::class, 'store'])->name('users.store');
You may want to remove one of them. If you're working with Laravel 8 and above, the format used in the second one is preferable.
Though not necessary, you may want to include the HTML markup below in your form as well. The value sent with the _method field will be used as the HTTP request method.
<input type="hidden" name="_method" value="POST">
I believe you have mismatching HTML tags on your submit button.
<button type="button" class="btn btn-outline-primary" id="send"
onClick="collect();">Create Account </input>
To avoid page reload. pass the event to the method call. In addition, prevent the default behaviour from your method definition.
<!-- HTML code. -->
<button type="button" class="btn btn-outline-primary" id="send"
onClick="collect(event);">Create Account </button>
// JavaScript Ajax code.
function collect(event){
event.preventDefault();
$.ajax({
// ...
});
// ...
}

Dropzone js validate on submit

I have a form where I am using dropzone.js for file upload. Now I am validating all the input fields. But i'm not able to validate the file before submission. If the file is uploaded, then the submission should work. Otherwise it should throw an error like - "please upload the file". How can i achieve this?
HTML code:
<form action="/action">
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" class="form-control" id="first_name" name="first_name" placeholder="First Name" required>
</div>
<div class="form-group col-md-6">
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last Name" required>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-12">
<textarea class="form-control" id="message" name="message" placeholder="Message"></textarea>
</div>
</div>
<div class="form-row">
<div id="resume" class="dropzone form-control"></div>
</div>
<input type="submit" class="btn btn-primary mt-10" id="item-submit" value="submit">
</form>
Javascript :
<script type="text/javascript">
$(document).ready(function () {
$("div#resume").dropzone({ url: "/change-this-later" });
var dropzone3;
Dropzone.autoDiscover = false;
dropzone3 = new Dropzone('#resume', {
maxFiles: 1,
});
$('#item-submit').click(function(e) {
e.preventDefault();
e.stopPropagation();
if ($('form#resume').valid()) {};
});
});
</script>
You can add a callback event which is called if the upload is successful
//indicates file upload is complete and is successful
var uploaded = false;
$("div#resume").dropzone({
url: "/change-this-later",
success: function (file, response) {
uploaded = true;
}
});
//Check the value of 'uploaded' when validating rest of fields
So I come around this. Since I submit all my images and fields in the same button, I just acceded to the files array in side the dropzone and validate that it's lenght wasn't 0. $animalImage is my dropzone.
var validateImages = function (animal) {
if ($animalImage.files.length == 0) {
swal({
title: 'Advertencia',
type: 'info',
html: "Debe de guardar al menos una imágen",
showCloseButton: true,
focusConfirm: false
});
return false;
}
return animal;
};
Hope it helps, side note a submit trough ajax so I just used dropzone for the user experience.

Get values from HTML to javascript

So I have a simple form where I ask the user some info to register and make an account, this is the part of the form I am using to achieve that:
<form class="login-form2" action="index.html">
<div class="center sliding"><img style='width:20%; margin: 42%; margin-top: 8%; margin-bottom: 0%;'src="./images/logoTemporal.png"></div>
<div class="login-wrap">
<p class="login-img"><i class="icon_lock_alt"></i></p>
<!-- Name -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_profile"></i></span>
<input type="text" id="Name" name="Name" class="form-control" placeholder="Name or Name.Corp" autofocus>
</div>
<!-- Email -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="email" id="Email" name="Email" class="form-control" placeholder="Email">
</div>
<!-- Passwrod -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="password" id="Password" name="Password" class="form-control" placeholder="Password">
</div>
<!-- Confirm password -->
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input type="password" class="form-control" placeholder="Confirm Password">
</div>
<!-- Tipo -->
<div class="item-content input-group-addon">
<div class="item-media"><i class="icon f7-icons">Tipo Usuario</i></div>
<br>
<div class="item-input">
<select id="Tipo" name="Tipo">>
<option value="0" selected>Empresa</option>
<option value="1">Usuario</option>
</select>
</div>
</div>
<br>
<!-- Button-->
<!-- <a class="btn btn-primary btn-lg btn-block" href="register.html">Register</a> -->
<p> <input type="button" class="btn btn-primary btn-lg btn-block" id="signup" value="Send"/></p>
</div>
</form>
I am trying to get the values into some variables in a jc, but for some reason I am not getting them:
$(document).ready(function() {
$("#signup").click(function() {
alert("Im in the function");//this is the only alert showing when I test the page...
//From here on it is not working
var Name = $('#Name').val();
var Email = $('#Email').val();
var Password = $('#Password').val();
var Tipo = $('#Tipo').val();
if (Name == '' || Email == '' || Password == '' || Tipo == '')
{ alert("please complete the information"); }
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: 'dummy url',
crossDomain: true,
beforeSend: function(){ $mobile.loading('show')},
complete: function(){ $mobile.loading('hide')},
data: ({Name: Name, Email: Email, Password: Password, Tipo: Tipo}),
dataType: 'json',
success: function(html){
alert("Thank you for Registering with us! you
can login now");
},
error: function(html){
alert("Not Working");
}
});
}//else end
});
});
I am still trying to learn many things here but what I need to know is why the variables are not getting the values from the form, could be something dumb but I just cant see it... Would appreciate some help...
EDIT:
Adding my php code, now I get an error when trying to send the data to my host´s php using JSON, the javascript prints the "not working" alert, what I think is that my php is not really getting the json so its not working but im not 100% sure so here is my php code:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS');
require 'data/DataCollector.php';
$varData = json_decode($data);
$Name = $varData->Name;
$Email = $varData->Email;
$Password = $varData->Password;
$Tipo = $varData->Tipo;
$database = new DataCollector([
'database_name' => 'dummy url',
'server' => 'dummy server',
'username' => 'dummy username',
'password' => 'dummy password',
'charset' => 'utf8',
]);
if($_POST){
$database->insert("Usuario", [
"nombre" => $_POST[$Name],
"email" => $_POST[$Email],
"password" => $_POST[$Password],
"tipoUsuario" => $_POST[$Tipo]
]);
}
?>
I have never used JSON and I am trying to learn about it, there is probably A LOT of issues with my code but any help will be very much appreciated! thanks!
your dictionary does not seem to be correct.
try this:
data: {"Name": Name, "Email": Email, "Password": Password, "Tipo": Tipo}

Form doesn't submit on callback

I am trying to send an e-mail after an ajax call has been successfully completed. I do not have access to the file that I am making the AJAX call to.
I am preventing the first submit, making the ajax call and submitting the form again upon competition. When doing this, I can't seem to figure out why I have to press the submit button twice for the email to be sent.
Here is my code:
"use strict";
var submitted = '';
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var firstName = $('#firstName').val(),
lastName = $('#lastName').val(),
email = $('#email').val(),
phone = $('#primaryPhone').val(),
weight = $('#weight').val(),
origin = $('#originPostalCode').val(),
destination = $('#destinationPostalCode').val(),
notes = $('#whatsTransported').val()
if( submitted != 1 )
{
e.preventDefault();
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
crossDomain: true,
dataType: "json",
data: {"key": "my secret key","first": firstName, "last": lastName, "email": email, "phone": phone, "weight": weight, "origin_postal": origin, "dest_country": destination, "note": notes }
})
.done(function(data){
if(data[1][0][0] == 2)
{
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
})
.fail(function(data) { console.log(data); });
}
submitted = '1';
});
});
Here is the form HTML
<form action="<?php echo bloginfo($show='template_url').'/includes/form-email.php'; ?>" class="span6 offset1" id="quote" method="post">
<div class="row formRow">
<div class="firstName span3">
<label for="firstName"><?php _e('First Name:','StreamlinedService'); ?></label>
<input type="text" name="firstName" id="firstName">
</div>
<div class="lastName span3">
<label for="lastName"><?php _e('Last Name:','StreamlinedService'); ?></label>
<input type="text" name="lastName" id="lastName">
</div>
</div>
<div class="row formRow">
<div class="email span3">
<label for="email"><?php _e('Email Address:','StreamlinedService'); ?></label>
<input type="text" name="email" id="email">
</div>
<div class="primaryPhone span3">
<label for="primaryPhone"><?php _e('Phone Number:','StreamlinedService'); ?></label>
<input type="text" name="primaryPhone" id="primaryPhone">
</div>
</div>
<div class="row formRow">
<div class="weight span2">
<label for="weight"><?php _e('Weight (lbs):','StreamlinedService'); ?></label>
<input type="text" name="weight" id="weight">
</div>
</div>
<div class="row formRow">
<div class="originPostalCode span3">
<label for="originPostalCode"><?php _e('Origin:','StreamlinedService'); ?></label>
<input type="text" name="originPostalCode" id="originPostalCode">
</div>
<div class="destinationPostalCode span3">
<label for="destinationPostalCode"><?php _e('Destination:','StreamlinedService'); ?></label>
<input type="text" name="destinationPostalCode" id="destinationPostalCode">
</div>
</div>
<div class="row">
<div class="whatsTransported span6">
<label for="whatsTransported"><?php _e('What can we help you transport?','StreamlinedService'); ?></label>
<textarea name="whatsTransported" id="whatsTransported" rows="5"></textarea>
</div>
<input type="hidden" name="formType" value="quote" />
<input type="hidden" name="siteReferer" value="<?php echo $blog_id ?>">
<input type="submit" id="submit" name="submit" value="<?php _e('Get Freight Quote','StreamlinedService') ?>" class="btn btn-primary btn-large span3 offset3" style="float:right;">
</div>
</form>
My question is two-fold: Is there a more efficient way to do this? If not, why isn't this working?
Just use the .submit directly on the form node (note the [0])
$('#quote #submit').submit();
becomes
$('#quote')[0].submit();
this bypasses the jQuery bound event and forces a postback.
You use the wrong approach to Jquery
You miss the key : Write Less Do More, the heart of JQuery.
Anyway try this:
"use strict";
/* Send info to the portal */
jQuery(function($) {
$('#quote').submit(function(e){
var tis = $(this);
$.ajax({
type: "POST",
url: "https://somewhere.on/the/internet.php",
cache: true,
dataType: "json",
data: tis.serialize(),
success: function(data){
if(data[1][0][0] == 2){
$('.alert').append( data[1][0][1].message ).addClass('alert-error').show();
} else if(data[1][0][0] == 0) {
console.log("Made it.");
$('#quote #submit').submit();
} else {
$('.alert').append( "Appologies, it seems like something went wrong. Please, <strong>call (877) 419-5523</strong> for immediate assistance or a free quote.");
}
},
error: function(data){console.log(data);}
});
e.stroPropagation();
e.preventDefault();
});
});
Last thin.. you CAN'T request a remote page that's not hosted on the same domain of the script.. For that ther's This answer

Categories