AJAX sends null values - php

Register form:
{!! Form::open(['route' => 'api.register', 'method' => 'post', 'id' => 'register_form']) !!}
<div class="form-group">
<div class="inputer">
<div class="input-wrapper">
<input id="register_name" type="text" class="form-control" placeholder="Enter your full name">
</div>
</div>
</div>
<!--.form-group-->
<div class="form-group">
<div class="inputer">
<div class="input-wrapper">
<input id="register_email" type="email" class="form-control" placeholder="Enter your email address">
</div>
</div>
</div>
<!--.form-group-->
<div class="form-group">
<div class="inputer">
<div class="input-wrapper">
<input id="register_pass" type="password" class="form-control" placeholder="Enter your password">
</div>
</div>
</div>
<!--.form-group-->
<div class="form-group">
<div class="inputer">
<div class="input-wrapper">
<input id="register_confirm" type="password" class="form-control" placeholder="Enter your password again">
</div>
</div>
</div>
<!--.form-group-->
<div class="form-group">
<label>
<input type="checkbox" name="remember" value="1"> I have read and agree to the term of use.
</label>
</div>
<div class="form-buttons clearfix">
<button class="btn btn-white pull-left show-pane-login">Cancel</button>
<button id="register_submit" class="btn btn-success pull-right">Sign Up</button>
</div>
<!--.form-buttons-->
{!! Form::close() !!}
JS:
$("#register_form").submit(function(e) {
e.preventDefault();
});
$('#register_submit').click(function()
{
var address = $('#register_form').attr('action');
var method = $('#register_form').attr('method');
var user_name = $('#register_name').val();
var mail = $('#register_email').val();
var pass = $('#register_pass').val();
var pass_confirm = $('#register_confirm').val();
var name = $("input[name=_token]").val();
$.ajax({
url: address,
type: method,
data:
{
name: user_name,
email: mail,
password: pass,
password_confirm : pass_confirm,
_token: name
},
success:function(response) {
alert(response);
},
error:function(response) {
alert(response);
},
});
});
Route:
Route::post('/processregister', ['as' => 'api.register', 'uses' => 'AuthController#register']);
Register function:
public function register(Request $request)
{
return $request->name;
}
At webportal.dev/processregister it gives blank page. It means request parameters sends remains null. Where I am going wrong?
(Maybe conflicts? There is also a login form on same page but it is submitted by seperate function and that login form works correctly.)

It's due to a very common mistake in Submit button.
A button <button> with type=submit will submit the form by default, unless you stop the default behavior via event.preventDefault() in your $('#register_submit').click() function. The default behavior runs before your AJAX call is responded and forwarded to the URL in action attribute specified in <form> tag (i.e. http://webportal.dev/processregister)
In your case, you can also change the type of the button to button to avoid this form submission behavior.

Remove type="submit" in this line:
<button id="register_submit" type="submit" class="btn btn-success pull-right">Sign Up</button>
Also be sure that your ajax code is really called.

Based on the comments the issue was due to your view being cached. Since i was able to run the exact same code to generate the result intended. Next time try to run php artisan view:clear to clear the cached views as the first step in debugging view errors. Also always post the code used when seeking help and not the code being generated.
Another tip is to assign names instead of id to the form inputs and then serialize the form data in the ajax request. You save all the work of fetching the value of each input by it's id and then using it.

Why not moving all your code inside your .submit function, and just add return false; at the end?
$("#register_form").submit(function(e) {
var address = $('#register_form').attr('action');
var method = $('#register_form').attr('method');
var user_name = $('#register_name').val();
var mail = $('#register_email').val();
var pass = $('#register_pass').val();
var pass_confirm = $('#register_confirm').val();
var name = $("input[name=_token]").val();
$.ajax({
url: address,
type: method,
data:
{
name: user_name,
email: mail,
password: pass,
password_confirm : pass_confirm,
_token: name
},
success:function(response) {
alert(response);
},
error:function(response) {
alert(response);
},
});
return false;
});
Please then watch what happens with your ajax request in the Developer Tools (F12) > Network tab. Perhaps there is an error on the server side.

Related

Problem with data transfer by jquery to php

I want to use Ajax to get data from #f1 (.Val()) and show it by PHP (echo) and it is successful in Ajax but I cant get data in PHP.
and it always says : false. here is the code:(line 86~93 is not important). can anybody help please...?
<form action="index.php" method="post" id="submit-form">
<div class="d4">
username:
</div>
<div class="d5">
<input type="text" , class="in" , name="username" placeholder="username" id="f1">
</div>
<div class="d4">
password:
</div>
<div class="d5">
<input type="text" , class="in" , name="sing2" placeholder="password">
</div>
<div class="d4">
email:
</div>
<div class="d5">
<input type="email" , class="in" , name="sing3" placeholder="email">
</div>
<div class="d5">
<input type="button" , class="in1" , name="sing4" value="submit">
</div>
</form>
<script type="text/javascript">
$("#f1").keypress(function(){
$.ajax({
type:'POST',
url:'index.php',
data:{
uen:$("#f1").val(),
},
success: function(data) {
alert($("#f1").val());
},
failure: function(data) {
alert("0");
},
});
});
});
</script>
<?php
if(isset($_POST['uen'])){
echo $_POST['uen'];
}else{
echo 'false';
}
?>
success: function(data) {
alert($("#f1").val());
},
The response to the Ajax request will be placed in the data argument to the success function, but you are ignoring it.
Unless you are examining the data in the Network tab of the browser's developer tools, you can't know if it is returning false or something else.
When you make the initial GET request to render the page, this chunk of code:
<?php
if(isset($_POST['uen'])){
echo $_POST['uen'];
}else{
echo 'false';
}
?>
… will render false on the HTML document (because it is a GET request).
Subsequent Ajax requests will not travel back in time and alter the response to the earlier request to cause the browser to update the DOM.
To do that you need to read the value of data in the success function and use JavaScript to modify the DOM based on it.
I see some errors in your code, including commas in the form input tags. Here is the code as it should be written:
<form action="form_request.php" method="post" id="submit-form">
<div class="d4">
username:
</div>
<div class="d5">
<input type="text" class="in" name="username" placeholder="username" id="f1">
</div>
<div class="d4">
password:
</div>
<div class="d5">
<input type="text" class="in" name="sing2" placeholder="password">
</div>
<div class="d4">
email:
</div>
<div class="d5">
<input type="email" class="in" name="sing3" placeholder="email">
</div>
<div class="d5">
<input type="button" class="in1" name="sing4" value="submit">
</div>
You also have some syntax errors in the jquery code, the correct way is the following:
$("#f1").keypress(function () {
$.ajax({
type: 'post',
url: 'ajax_request.php',
data: {
async : true,
uen: $("#f1").val()
},
success: function (data) {
console.log($("#f1").val());
}
});
});
At the end, modify your PHP snippet so that it only interprets requests that are sent with the "async" post variable, this in my example should be in a file called "ajax_request.php" as follows:
if (isset($_POST['async'])) {
echo $_POST['uen'];
}
Typing to the username field will asynchronously send the "keypress" event to the PHP code and the response to the browser console (it was originally shown in alert).
I hope to be helpful

JQuery Form Validator's toggleDisabled module does not work on buttons that are not type 'submit'

I have a form that uses the jquery form validator plugin (http://www.formvalidator.net/) to perform client side pre-submit validation. I have the toggleDisabled module activated so that the submit button is disabled until all required fields are filled out and formatted correctly. My jquery then sends the form data to a processing page via ajax. The storeData.php code stores the data in a table. On success, the ajax should open a modal. I have verified that the data is being stored in my table.
The issue lies (I suspect) with the form submit button. In order for my toggleDisabled module to work correctly, the button has to be of type 'submit.' But because of the nature of a submit button the success function of my ajax is effectively being bypassed so that the modal will never be displayed.
I have tested this by changing the submit button to a regular button. At the expense of my toggleDisabled module not functioning this way, my modal is displayed.
I have found many solutions here for enabling/disabling buttons and also for preventing form submit by changing the button type to button. However, I want to use the validator module to disable/enable the button because it is designed to listen to the data-validation attributes for my form fields. But it won't work unless it's a submit button. Is there a simple solution that I'm overlooking?
index.php
<form method="post" name="talentForm" id="talentForm">
<div class="form-row">
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="first" class="form-control" placeholder="First name" data-validation="required">
</div>
<div class="col-auto"> </div>
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="last" class="form-control" placeholder="Last name" data-validation="required">
</div>
</div>
<div class="row rowtm20"></div>
<div class="form-row">
<div class="col-auto redtext">*</div>
<div class="col">
<input type="text" id="email" class="form-control" placeholder="E-mail" data-validation="email">
</div>
<div class="col-auto"> </div>
<div class="col-auto"> </div>
<div class="col">
<input type="text" id="phone" class="form-control" placeholder="Phone">
</div>
</div>
<div class="form-row">
<button type="submit" id="registerButton" class="btn btn-primary mb-2 biggertext">Register</button>
</div>
</form>
<script>
$.validate({
modules : 'security,toggleDisabled',
showErrorDialogs : false
});
$('#registerButton').on('click', function(){
var inputData = $('#last').val()+"|"+$('#fist').val()+"|"+$('#email').val()+"|"+$('#phone').val();
$.ajax({
type: 'post',
url: 'storeEntry.php',
data: {registration:inputData},
success: function(response){
if(response == "1"){
$("#thankyouModal").modal("show");
}
else{
alert("Error");
}
}
});
});
</script>
storeEntry.php
if(isset($_POST)){
$data = explode("|",$_POST['registration']);
$addRegistration = "insert into talent (Last,First,email,Phone) values('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."')";
$entry = $dbConn->query($addRegistration) or die ("Error performing addRegistration query: ".mysqli_error($dbConn));
if($entry){
echo "1";
} else{
echo "0";
}
}
Well, I found the answer. I added an argument to the click function and then called the preventDefault method, which will effectively 'turn off' the submit action of a submit button. This allows my toggleDisabled module in the validator to function correctly while also allowing my modal to appear and my ajax to execute. Hre is my revised click function:
$('#registerButton').on('click', function(e){
e.preventDefult();
var inputData = $('#last').val()+"|"+$('#fist').val()+"|"+$('#email').val()+"|"+$('#phone').val();
$.ajax({
type: 'post',
url: 'storeEntry.php',
data: {registration:inputData},
success: function(response){
if(response == "1"){
$("#thankyouModal").modal("show");
}
else{
alert("Error");
}
}
});
});

Laravel, how to show forms error with ajax submit?

I use ajax to submit a form without having to reload the page after, but I really don't know how to get the forms errors, especially for the required fields.
Here is my form, it's a simple form with two datepicker:
<form>
<div class="form-group row">
<label for="date_debut" class="col-md-4 col-form-label text-md-right">Date de début</label>
<div class="col-md-6">
<input type="text" id="date_debut" name="date_debut" class="datepicker-here form-control" data-timepicker="true" data-language='fr' placeholder="Choisir une date" />
</div>
</div>
<div class="form-group row">
<label for="date_fin" class="col-md-4 col-form-label text-md-right">Date de fin</label>
<div class="col-md-6">
<input type="text" id="date_fin" name="date_fin" class="datepicker-here form-control" data-timepicker="true" data-language='fr' placeholder="Choisir une date" />
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button id="ajoutDispoButton" onclick="myfunction()" type="button" class="btn btn-primary">
Ajouter
</button>
</div>
</div>
<input type="hidden" id="user_id" name="user_id" class="form-control" value="{{$user->id}}" required>
</form>
And here is my Ajax call :
function myfunction(param){
var date_debut = $('#date_debut').val();
console.log(date_debut);
var date_fin = $('#date_fin').val();
var user_id = $('#user_id').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ route('createDispo') }}',
type: 'POST',
dataType: "json",
data: {
user_id: user_id,
date_debut: date_debut,
date_fin: date_fin,
},
success: function (data) {
$("#centralModalSuccess").modal();
$("#date_fin").val("");
$("#date_debut").val("");
},
error: function (data) {
var errors = data.responseJSON;
console.log(errors);
}
});
}
And here my controller :
public function createDispo(Request $request){
$user = User::find($request->user_id);
$disponibilite = new Disponibilite();
$disponibilite->date_debut = Carbon::createFromFormat('d/m/Y H:i',$request->date_debut);
$disponibilite->date_fin = Carbon::createFromFormat('d/m/Y H:i',$request->date_fin);
$user->disponibilites()->save($disponibilite);
return response()->json(['ok' => 'ok']); // Return OK to user's browser
}
I think this is not the right way to proceed, but this work. The problem is that I want to handle the validations errors, my fields are required but I can send the ajax call even if they are empty.
Anyone know how to do that?
you can make form validation with jquery instead of laravel validation
Look at this question : A simple jQuery form validation script
Add validation in controller function
public function createDispo(Request $request){
$request->validate([
'date_debut' => 'required',
'date_fin' => 'required',
]);
// your code
}
and display the errors in html.

How to retrieve form fields in php if the data sent contains more than the form

I have a simple form in which the user can enter a search term:
<form class="form-inline justify-content-center" id="searchForm">
<div class="form-group">
<label class="sr-only text-info" for="searchTerm">Search term</label>
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" name="searchTerm" id="searchTerm" placeholder="Search">
</div>
<button type="submit" class="btn btn-info">Search</button>
</form>
And I send the form using ajax like this:
$form = $(e.target);
$.ajax({
url: "searchmovielist.php",
type: "GET",
data: {form: $form.serialize(), username: getCookie('username')},
success: function (response) {
console.log(response);
}
});
My question is how do I retrieve the fields from the form in php if I get the form using $_GET['form']?
You can use PHP function parse_str to split the string to array. So the code would be like
$username = $_GET['username']
parse_str($_GET['form'], $form_data);
var_dump($form_data);
But I'm wondering why are you reading username from a cookie and then sending it again in the request? Why not just read it from $_COOKIE in PHP?

I can't send ajax request using XAMP

i'm using an ajax login which work perfectly on Wamp Server windows , but when i 've passed to Xamp on kali linux it doesn't work :
$.ajax({
url: baseurl + 'index.php?login/ajax_login',
method: 'POST',
dataType: 'json',
data: {
username: $("input#username").val(),
password: $("input#password").val(),
},
error: function () {
alert("An error occoured!");
},
when i click on login button it shows :An error occoured!
i don't know where is the problem , cause the app work perfectly on wampserver.
i wish that you gonna help me.
for the frameworks i m using codeIgniter .
here it is the form:
<form method="post" role="form" id="form_login">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="entypo-user"></i>
</div>
<input type="text" class="form-control" name="username" id="username" placeholder="nom.prenom" autocomplete="off" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="entypo-key"></i>
</div>
<input type="password" class="form-control" name="password" id="password" placeholder="Password" autocomplete="off" />
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block btn-login">
<i class="entypo-login"></i>
Login
</button>
</div>
</form>
here it is the ajax_login.php:
function ajax_login() {
$response = array();
//Recieving post input of email, password from ajax request
$username = $_POST["username"];
$password = $_POST["password"];
$response['submitted_data'] = $_POST;
//Validating login
$login_status = $this->validate_login($username, $password);
$response['login_status'] = $login_status;
if ($login_status == 'success') {
$response['redirect_url'] = $this->session->userdata('last_page');
}
//Replying ajax request with validation response
echo json_encode($response);
}
it is a function within a controller named login ,and this is the baseurl:
$config['base_url'] = 'http://localhost/elit';
i am using codeIgniter framework
Ok found few things that are missing in the HTML form code :
Edit : After reading Quentin comments and the information that he provided which is right i had to take the part where i said :
First you did not include the action in the form tag , the action
means where this form data are going to be either submitted or
whatever the is going to happen on that form , where it going ?
The correct info is this :
The action attribute is optional. If omitted, the form is submitted to
the current URL. That's irrelevant though since the form isn't being
submitted. JavaScript is reading the data from it and making the HTTP
request instead. For correcting my information about the Action
attribute .
Thank you Quentin for the correct information .
I edited the Form code and the AJAX code with a new one but with few changes , this code works perfect for me on XAMP:
<form action="" method="post" role="form" id="form_login" onsubmit="return UserSignIn();">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="entypo-user"></i>
</div>
<input type="text" class="form-control" name="username" id="username" placeholder="nom.prenom" autocomplete="off" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">
<i class="entypo-key"></i>
</div>
<input type="password" class="form-control" name="password" id="password" placeholder="Password" autocomplete="off" />
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block btn-login">
<i class="entypo-login"></i>
Login
</button>
</div>
</form>
The AJAX Code :
<script>
function UserSignIn()
{
var username = document.getElementByI('username').value;
var password = document.getElementByI('username').value;
if(username && password )
{
$.ajax({
type: 'POST',
url: '',
data: {
username,
password
},
success: function(response) {
alert("Code Works");
},
error: function(response){
console.log(response);
}
});
}
return false;
}
</script>
Note : In this part url: '' plz put the target page that will receive the data from the AJAX code . For example , if the php page were in the same folder as the page that this form is in ,just type that name page with , ex : url: 'login.php' , if login.php exisst in another folder lets assum that folder name was login you will do this : url: 'login/login.php' .
Now when you do what i asked you to do click on submit , if it show alert box that says " code works "!! thats mean the code works perfect and you are good to go and edit it with your needs , but if it did not , then we have to see your php code .
Hope that fix your issue , let me know if you need more explanation .

Categories