I can't send ajax request using XAMP - php

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 .

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");
}
}
});
});

Different values returned for php session variable

I have been having this problem for the last two days now. I have two files on my local host.
http://localhost/project/sign-in.php and
http://localhost/project/form-handle/index.php
When a user lands on sign-in page a session variable is created
<?php
ob_start();
session_start();
$token = strtoupper(uniqid());
$_SESSION['token-string'] = $token;
I then put the session value in a hidden field
<input type='hidden' name='token-string' value='<?php echo $token; ?>'>
So far, so good. However, when I send the form values to http://localhost/project/form-handle/index.php
and return the value of the token string session, its different from what is in the hidden field. I am using jquery ajax to send the request.
Here is how I check for it in the form-handle page:
<?php
ob_start();
session_start();
if(isset($_SESSION['token-string'])){
$token = $_SESSION['token-string'];
echo $token;
}
?>
The value returned is totally different! Its important to know also that the wrong value returned is a string generated by the function
strtoupper(uniqid());
Am I doing something wrong here?
Here is the jQuery that submits the form
$('#service-login').click(function (evt) {
evt.preventDefault();
var form = $('#Ads-Login');
var data = form.serialize();
var url = 'form-handle/index.php';
var method = form.attr('method');
$.ajax({
type: method,
url: url,
data: data,
success: function (response) {
alert(response);
},
error: function () {
}
})
});
The html form is here
<form action="" method="post" id="Ads-Login">
<div class="form-group">
<input type="email" name="email" id="" class="form-control" placeholder="Email Address">
</div>
<div class="form-group">
<input type="hidden" name="token-string" value="<?php echo $token; ?>">
<input type="password" name="Password" id="" class="form-control" placeholder="Account Password">
<a class="btn btn-white dark-grey-text font-bold ml-0" href="" id="service-login"><i class="fa fa-play mr-1"></i> Login</a>
</div>
</form>

Getting a null value in my input file type field

I downloaded a web application and i found out that it is created using Smarty Template Engine. I want to add an avatar field when creating new company so i added enctype="multipart/form-data" and <input type="file" name="avatar"> to the existing <form> and i also added avatar to my companies table in my database. Here is the HTML code:
<form class="form-horizontal" id="ib_modal_form" enctype="multipart/form-data">
<div class="form-group"><label class="col-lg-4 control-label" for="company_name">{$_L['Company Name']}<small class="red">*</small></label>
<div class="col-lg-8"><input type="text" id="company_name" name="company_name" class="form-control" value="{$val['company_name']}"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="avatar">{$_L['Avatar']}</label>
<div class="col-lg-8"><input type="file" name="avatar"></div>
</div>
<div class="form-group"><label class="col-lg-4 control-label" for="email">{$_L['Email']}</label>
<div class="col-lg-8"><input type="text" id="email" name="email" class="form-control" value="{$val['email']}"> </div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-danger">{$_L['Cancel']}</button>
<button class="btn btn-primary modal_submit" type="submit" id="modal_submit"><i class="fa fa-check"></i> {$_L['Save']}</button>
</div>
I found out that the form goes to this javascript code when clicking the Save Button:
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
$.post( _url + "contacts/add_company_post/", $("#ib_modal_form").serialize())
.done(function( data ) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
});
});
Here is the code in the Controller:
case 'add_company_post':
$data = ib_posted_data();
$company = Model::factory('Models_Company')->create();
$company->company_name = $data['company_name'];
$company->url = $data['url'];
$company->email = $data['email'];
$company->phone = $data['phone'];
$company->logo_url = $data['logo_url'];
$company->avatar = $_FILES['avatar']['name'];
$company->save();
break;
The problem is that it does not recognize $_FILES['avatar']['name']; in the Controller Whenever i add a new company, i get a NULL value in my database. I cant seem to solve this problem. Any help would be appreciated. Thanks.
Change
From
$("#ib_modal_form").serialize()
To
new FormData($("#ib_modal_form")[0])
You should use FormData for uploading files using ajax. $(form).serialize() will give you just key and value.
Can you change your ajax call below way
$modal.on('click', '.modal_submit', function(e){
e.preventDefault();
var formData = new FormData($("#ib_modal_form")[0]);
$.ajax({
url: _url + "contacts/add_company_post/",
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
if ($.isNumeric(data)) {
location.reload();
}
else {
$modal.modal('loading');
toastr.error(data);
}
},
});
});

AJAX sends null values

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.

Categories