thanks for reading my question, i have some issues trying to validate a recaptcha, with codeigniter with jquery ajax method, i always get invalid-requste-cookie, here is part of my code
Part of "welcome" controller
public function anunciese()
{
$data['recaptcha_html'] = $this->recaptcha->recaptcha_get_html();
$data['main_content'] = 'welcome/anunciese';
$this->load->view('includes/'.$this->config->config["tema"].'/template' , $data);
}
public function validar_recaptcha()
{
$this->recaptcha->recaptcha_check_answer(
$_SERVER['REMOTE_ADDR'],
$this->input->post('recaptcha_challenge_field'),
$this->input->post('recaptcha_response_field'));
if ($this->recaptcha->getIsValid() == false)
{
$datos['success'] = false;
$datos['titulo'] = "ERROR";
$datos['mensaje'] = $error = $this->recaptcha->getError();
}
else
{
$datos['success'] = true;
$datos['titulo'] = "";
$datos['mensaje'] = "";
}
echo json_encode($datos);
}
Here is the view (part of It)
<form class="form-horizontal" method="post">
<fieldset>
<div class="form-group">
<label for="inputEmail" class="col-lg-2 control-label">Email</label>
<div class="col-lg-10">
<input class="form-control" id="inputEmail" placeholder="Email" type="text">
</div>
</div>
<div class="form-group">
<label for="inputNombre" class="col-lg-2 control-label">Nombre</label>
<div class="col-lg-10">
<input class="form-control" id="inputNombre" placeholder="Nombre" type="text">
</div>
</div>
<div class="form-group">
<?php echo $recaptcha_html; ?>
</div>
<div class="form-group">
<input type="button" class="btn btn-primary" value="Suscribirme Gratis" onClick="SalvarProspecto()" />
</div>
And finally my js code
function ValidarRecaptcha()
{
var phpencode = true;
var urlx = base_url + 'welcome/validar_recaptcha';
$.ajax({
type: "POST",
url: urlx,
data: {},
async: false,
success: function (data) {
if (phpencode == true) {
data = $.parseJSON(data);
}
console.log(data) //Solo para propositos de debug
if (data.success) {
return true;
} else {
return false;
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Failed " + urlx);
alert(xhr.responseText);
alert(thrownError);
}
});
}
I am using this library https://github.com/Cnordbo/RECaptcha-for-Codeigniter
Any help would be appreciated
Just made it without ajax requests, and making it a basic form, with the form helper, and the codeigniter documentation here, like that example https://github.com/Cnordbo/RECaptcha-for-Codeigniter
Related
Iam Working on a project using OO php and i want to display success message when submit is clicked
I've searched all on the web but the solutions am getting are not working for me!!
I tried using both jquery and ajax but i keep on getting the same error
Here is my html
<form method="post" id="postForm" class="form-horizontal" action = "index.php">
<div class="form-group">
<label for="Title" class="control-label col-sm-3">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Enter Title of your Post"/>
</div>
</div>
<div class="form-group">
<label for="Title" class="control-label col-sm-3">Body</label>
<div class="col-sm-9">
<Textarea type="text" class="form-control" name="body" id="body" placeholder="Enter Body of your Post"></textarea>
</div>
</div>
<button type="submit" class="btn btn-default" name="submit">submit</button><br/>
<div class="text-center">
<span id="success" class="text-success"></span>
<span id="wanings" class="text-danger"></span>
</div>
</form>
This is my jquery script file inserted into the same page index.php
<script>
$(document).ready(function(){
$('#postForm').submit(function(event){
event.preventDefault();
var $form = $(this),
var title = $('#title').val();
var body = $('#body').val();
var url = $form.attr('action');
var method = $form.attr('method');
if(title == '' || body == ''){
$('#warnings').html('All Fields are Required');
}else{
$('#warnings').html('');
$.ajax({
url: url,
method:method,
data:{title: title, body:body},
success:function(data){
$('#postForm').trigger('reset');
$('#success').fadeIn().html(data);
setTimeout(function function_name() {
$('#success').fadeOut('slow');
}, 3000);
}
});
}
});
});
</script>
And the Php is just above the Html also in the same page. Its supposed to get the post title and insert it into the database but echo the message that data has been successfully added if submit is clicked.
Here is the Snippet
<?php
require 'classes/Database.php';
$database = new Database;
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if($post['submit']){
$title = $post['title'];
$body = $post['body'];
$database->query('INSERT INTO posts (title, body) VALUES(:title, :body)');
$database->bind(':title', $title);
$database->bind(':body', $body);
$database->execute();
if($database->lastInsertId()){
echo "<h1>Post added Successfully To the Database</h1>";
}
}
?>
When i run the page in the browser, it displays the whole html in the div.
instead of a message set and then it throws the following error in the console.
Could any of you be knowing why it can't show the message? thanks
As you notice by the image, all the text is green, this is because you are rendering the response within that text-success span. Not ideal.
Instead of responding with HTML respond with JSON, and do your checks within the javascript to determine whether it was successful or a warning.
Some other issues:
You're not sending up submit so it will always skip passed the if statement.
So try something like:
$(document).ready(function() {
$('#postForm').submit(function(event) {
event.preventDefault();
var $form = $(this);
var title = $('#title').val();
var body = $('#body').val();
var url = $form.attr('action');
var method = $form.attr('method');
if (title == '' || body == '') {
$('#warnings').html('All Fields are Required');
if (title == '') {
$('#title').closest('.form-group').find('.help-block').html('Title is a required field')
}
if (body == '') {
$('#body').closest('.form-group').find('.help-block').html('Body is a required field')
}
} else {
$('#warnings').html('');
$form.find('.help-block').html('')
$.ajax({
url: url,
method: method,
data: {
title: title,
body: body
},
success: function(response) {
// got errors from server
if (response.status === 'error') {
if (response.errors.title) {
$('#title').closest('.form-group').find('.help-block').html(response.errors.title)
}
if (response.errors.body) {
$('#body').closest('.form-group').find('.help-block').html(response.errors.body)
}
if (response.errors.global) {
$('#warnings').html(response.errors.global)
}
}
// all good, assign message to success
else {
$('#success').fadeIn().html(response.msg);
setTimeout(function() {
$('#success').fadeOut('slow');
}, 3000);
$('#postForm').trigger('reset');
}
}
});
}
});
});
<form method="post" id="postForm" class="form-horizontal" action="index.php">
<div class="form-group">
<label for="title" class="control-label col-sm-3">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Enter Title of your Post" />
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="body" class="control-label col-sm-3">Body</label>
<div class="col-sm-9">
<textarea type="text" class="form-control" name="body" id="body" placeholder="Enter Body of your Post"></textarea>
</div>
<span class="help-block"></span>
</div>
<button type="submit" class="btn btn-default">submit</button><br/>
<div class="text-center">
<span id="success" class="text-success"></span>
<span id="warnings" class="text-danger"></span>
</div>
</form>
PHP code, basically validate and return as JSON.
<?php
require 'classes/Database.php';
$database = new Database;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$response = [];
$errors = [];
// validate inputs
if (empty($post['title'])) {
$errors['title'] = 'Title is a required field';
}
if (empty($post['body'])) {
$errors['body'] = 'Body is a required field';
}
// errors is empty so its all good
if (empty($errors)) {
//
$database->query('INSERT INTO posts (title, body) VALUES(:title, :body)');
$database->bind(':title', $post['title']);
$database->bind(':body', $post['body']);
$database->execute();
if ($database->lastInsertId()) {
$response = [
'status' => 'success',
'msg' => 'Post added successfully added'
];
} else {
$response = [
'status' => 'error',
'errors' => [
'global' => 'Failed to insert post, contact support'
]
];
}
} else {
$response = [
'status' => 'error',
'errors' => $errors
];
}
exit(json_encode($response));
}
// guessing after this is your rendering of that form
You need to check if($_POST) instead of if($post['submit']) because in your case its not going into if condition and echo out your result. Also after echo add "exit" statement so that form will not be printed in division.
Before I start, sorry for my English. i am developing a website using CI on Backend. And i want to make a registration system without refreshing the page. If i try with post form submit i got no error and everything went good. but when I try using with ajax request, I can't use form validation because form validation return false and validation_errors is empty. if I disable form validation, ajax request works well. here is my controller and ajax request. Please help me.
User.php (My Controller)
public function register(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
$data = json_encode(array('status'=> false,'info'=>validation_errors()));
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
$data = json_encode(array('status' => true,'info' => 'Successfully Registered'));
} else {
$data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration'));
}
}else{
$data = json_encode(array('status'=> false,'info'=>'This is not Ajax request'));
}
}
echo $data;
}
}
And here is my ajax request in js
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: url + 'User/register', //url is correct i tested without form validation
data: $('#register-form').serialize(),
dataType: "json",
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
edit: and here is my form:
<!-- Register Form -->
<?php echo form_open(base_url('index.php/User/register'),array('id' => 'register-form','name' => 'register-form')); ?>
<?php echo form_hidden($this->security->get_csrf_token_name(), $this->security->get_csrf_hash()); ?>
<div class="md-form">
<input type="text" id="name_kyt" name="name_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="name_kyt" >Name</label>
</div>
<div class="md-form">
<input type="text" id="surname_kyt" name="surname_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="surname_kyt" >Surname</label>
</div>
<div class="md-form">
<input type="text" id="username_kyt" name="username_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="username_kyt" > Username </label>
</div>
<div class="md-form">
<input type="email" id="email_kyt" name="email_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="email_kyt" >Email</label>
</div>
<div class="md-form">
<input type="password" id="password_kyt" name="password_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="password_kyt" >Password</label>
</div>
<div class="md-form">
<input type="password" id="password_confirm" name="password_onay" class="form-control">
<label for="password_confirm" >Password Confirm</label>
</div>
<div class="form-group text-center">
<div class="row">
<div class="col-sm-10 col-sm-offset-3 mr-auto ml-auto">
<input type="submit" name="btn_register" id="btn_register" tabindex="4" class="btn btn-register mr-auto ml-auto" value="Register">
<p><span id="span_validate" class="label label-default mr-auto ml-auto"></span></p>
</div>
</div>
</div>
<!-- End of Register Form -->
<?php echo form_close(); ?>
Please refer below example to validate a form in CodeIgniter using ajax call.
1. ajax code.
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
var formData = $("#register-form").serialize();
$.ajax({
type: 'get',
url: url + 'User/register',
data: formData,
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
2. Controller code :
Load form_validation library and form helper
$this->load->library('form_validation');
$this->load->helper('form');
Now write your controller as ...
public function register(){
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
echo $data = json_encode(array('status'=> false,'info'=>validation_errors())); die;
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
echo $data = json_encode(array('status' => true,'info' => 'Successfully Registered')); die;
} else {
echo $data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration')); die;
}
}else{
echo $data = json_encode(array('status'=> false,'info'=>'This is not Ajax request')); die;
}
}
}
}
I have solved this problem. Form validation only works with post method. If you use get method it won't work.
I am very new to Codeigniter. I m trying to create a form with some text input field along with two image upload field. The image uploading working fine but the text input field value are not coming. Can anyone please check my code and tell me where I am doing wrong Here is my Code:
Front End
<body>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data"">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
</script>
Controller Script is this
public function upload(){
$uploadData = "";
//Get the details
$productName = $_POST['product_name'];
$productCode = $this->input->post('product_code');
$productLink = $this->input->post('product_link');
$uploadData = $productName.','.$productCode.','.$productLink;
// setting cofig for image upload
$config['upload_path'] = 'uploads/profile/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE;
//$config['max_size'] = '1024'; //1 MB
// Get the profile image
$errorMsg = "";
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
$errorMsg = 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/profile/' . $_FILES['file']['name'])) {
$errorMsg = 'File already exists : uploads/profile/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
$errorMsg = $this->upload->display_errors();
} else {
$data = $this->upload->data();
$errorMsg = 'File successfully uploaded : uploads/profile/' . $_FILES['file']['name'];
$uploadData = $uploadData.','.$data['full_path'];
}
}
}
} else {
$errorMsg = 'Please choose a file';
}
//upload product screenshots
$config['upload_path'] = 'uploads/';
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
$link="";
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
$errorMsg = "Error: " . $_FILES["files"]["error"][$i] . "<br>";
} else {
if (file_exists('uploads/' . $_FILES["files"]["name"][$i])) {
$errorMsg = 'File already exists : uploads/' . $_FILES["files"]["name"][$i];
} else {
$fileOriginalNmame = $_FILES["files"]["name"][$i];
$explodeFile = explode(".",$fileOriginalNmame);
$fileExtenstion = end($explodeFile);
$fileName = md5(md5(uniqid(rand(), true)).$_FILES["files"]["name"][$i]).'.'.$fileExtenstion;
move_uploaded_file($_FILES["files"]["tmp_name"][$i], 'uploads/' . $fileName);
$link= $link.$fileName.',';
}
}
}
$uploadData =$uploadData .','. $link;
$errorMsg = $uploadData;
} else {
$errorMsg = 'Please choose at least one file';
}
echo $errorMsg;
}
And if anyone can improve my controller code that will be very helpful tnx.
FormData() Method:
As per our definition .FormData() submit a element data in a Key/Value form. The Form element must have a name attribute. One advantage of FormData() is now you can post a files on next page.
Simple Syntax:
var formData = new FormData(form);
Highlight Points:
This method does post files.
This method post complete form using Get & Post method including files.
var formData = new FormData();
formData.append('username', 'joe');
In addition you could add a key/value pair to this using FormData.append.
So your code broke because you need to pass value of input as key/pair format that you missed except for file.
Hope this will help you.
Please find solution describe below.
$(document).ready(function(){
$('#add-product').click(function(e){
e.preventDefault();
var formData = new FormData();
//for product profile images
var productProfile = $('#product-image').prop('files')[0];
formData.append('file',productProfile);
// for product detail image
var imageCount = document.getElementById('product-screen').files.length;
for (var i = 0; i< imageCount; i++) {
formData.append("files[]", document.getElementById('product-screen').files[i]);
}
var inputs = $('#product-upload input[type="text"],input[type="email"]');
$.each(inputs, function(obj, v) {
var name = $(v).attr("name");
var value = $(v).val();
formData.append(name, value);
});
//AJAX Call
$.ajax({
url: 'http://localhost/ci/index.php/uploadproduct/upload/', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
beforeSend: function() {
// setting a timeout
$('#msg').html('Loading');
},
success: function (response) {
$('#msg').html(response); // display success response from the server
$('input').attr('value').html();
},
error: function (response) {
$('#msg').html("no response"); // display error response from the server
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="custom-container">
<div id="msg"></div>
<form id="product-upload" action="/index.php/uploadproduct/upload" method="POST" accept-charset="utf-8" enctype="multipart/form-data">
<div class="form-group">
<label for="product-name">Product name</label>
<input type="text" name="product_name" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Code</label>
<input type="text" name="product_code" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Link</label>
<input type="text" name="product_link" class="form-control">
</div>
<div class="form-group">
<label for="product-image">Product image</label>
<input type="file" id="product-image" name="product_image" class="form-control">
</div>
<div class="form-group">
<label for="product-name">Product Screenshots</label>
<input type="file" id="product-screen" name="product_screen" class="form-control" multiple>
</div>
<div class="form-group">
<input id="add-product" type="Submit" class="btn btn-primary" value="Add new product">
</div>
</form>
</div>
Let me know if it not works for you.
I want to validate my form's input with database, so when user type on form's input and contain email already in use or exists it will display an alert and cant submit. I use CodeIgniter framework and jQuery.
I've tried using the code below to check if name exists and this could work. But when I apply it to the other case for email, it doesn't work and display message "The URI you submitted has disallowed characters."
How is the correct way to fix this?
View (kasir_halaman.php) :
<div id="addModal" class="modal fade" role="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title"><span class="glyphicon glyphicon-plus"></span> Tambah Kasir</h3>
</div>
<div class="modal-body">
<form action="<?php echo site_url('admin/kasir/addpetugas'); ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Nama</label>
<input type="text" id="nama" name="nama" class="form-control" maxlength="100" required>
</div>
<div class="form-group">
<label>E-mail</label>
<input type="email" id="email" name="email" class="form-control" maxlength="150" required>
</div>
<div class="form-group">
<label>Kategori</label>
<select class="form-control" name="kategoripetugas" required>
<option value=""> -- Pilih Kategori -- </option>
<option value="1">Admin</option>
<option value="2">Kasir</option>
</select>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" maxlength="30">
</div>
<div class="form-group">
<label>Ulangi Password</label>
<input type="password" name="confirmpassword" class="form-control" maxlength="30">
</div>
<button type="submit" class="btn btn-primary" style="width:100%;">Tambah</button>
</form>
</div>
</div>
</div>
</div>
Controller (kasir.php) :
public function cekData($table, $field, $data)
{
$match = $this->Crud->read($table, array($field=>$data), null, null);
if($match->num_rows() > 0){
$report = 2;
}else{
$report = 1;
}
echo $report;
}
public function register_email_exists()
{
if (array_key_exists('email',$_POST)) {
if ($this->Crud->email_exists($this->input->post('email')) == TRUE ) {
echo false;
} else {
echo true;
}
}
}
Model (Crud.php) :
function email_exists($email)
{
$this->db->where('email', $email);
$query = $this->db->get('petugas');
if( $query->num_rows() > 0 ){ return TRUE; } else { return FALSE; }
}
jQuery AJAX (petugas.js) :
$(document).ready(function(){
var check1=0; var id;
$("#nama").bind("keyup change", function(){
var nama = $(this).val();
$.ajax({
url:'kasir/cekData/petugas/nama/'+nama,
data:{send:true},
success:function(data){
if(data==1){
$("#report1").text("");
check1=1;
}else{
$("#report1").text("*nama petugas sudah terpakai");
check1=0;
}
}
});
});
var check2=0;
$("#email").bind("keyup change", function(){
//var email = $(this).val();
$.ajax({
url:'kasir/register_email_exists',
data:{send:true},
success:function(data){
if(data==1){
$("#report2").text("");
check2=1;
}else{
$("#report2").text("*email sudah terpakai");
check2=0;
}
}
});
});
var check4=0;
$("#confirmpassword").bind("keyup change", function(){
var password = $("#password").val();
var confirmpassword = $(this).val();
if (password == confirmpassword){
$("#report4").text("");
check4=1;
}else{
$("#report4").text("*Password tidak sama");
check4=0;
}
});
$("#submit").click(function(event){
if(check1==0){
event.preventDefault();
}
if(check4==0){
event.preventDefault();
}
});
});
Use ajax post method instead and take data at php side from POST request
you can check more about jquery ajax here: http://api.jquery.com/jquery.post/
and about php post here: http://php.net/manual/en/reserved.variables.post.php
//JS
$("#email").bind("keyup change", function(){
var email = $(this).val();
$.ajax({
url:'kasir/register_email_exists',
type: "POST",// <---- ADD this to mention that your ajax is post
data:{ send:true, email:email },// <-- ADD email here as pram to be submitted
success:function(data){
if(data==1){
$("#report2").text("");
check2=1;
}else{
$("#report2").text("*email sudah terpakai");
check2=0;
}
}
});
});
// PHP
// At php side take your data from $_POST
$send = $_POST['send'];
$email = $_POST['email'];
...
This is a part of the code from a form requesting data to check if the email alredy exist. The thing is, the program is supposed to return 0 if there is no any mail like this. It dont work properly, because the program keep sending the data, even if the mail is not correct.
If you want more info, or i am missing something let me know. Thanks in advance.
$(document).ready(function () {
$("#enviar").click(function(e) {
e.preventDefault();
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = false;
}else{
$("form").unbind('submit').submit();
}
}
});
if (error){
return false;
}
});
});
And here is my compruebaEmail.php
<?php require_once('connections/vinoteca.php'); ?>
<?php
mysql_select_db($database_vinoteca, $vinoteca);
$user = $_POST['b'];
if(!empty($user)) {
comprobar($user);
}
function comprobar($b) {
$sql = mysql_query("SELECT * FROM usuarios WHERE email = '".$b."'");
$contar = mysql_num_rows($sql);
if($contar == 0){
echo 0;
}else{
echo 1;
}
}
?>
And here goes the POST
<form method="POST" name="form1" action="validarUsu.php">
<div class="row">
<span class="center">Email</span>
</div>
<div class="row">
<input type="text" name="email" id="email2" value="" size="32" />
</div>
<div class="row">
<span class="center">Contraseña</span>
</div>
<div class="row">
<input type="password" name="password" id="id2" value="" size="32" />
</div>
<div class="row">
<span id="error"> </span>
</div>
<div class="row">
<input type="submit" value="Acceder" id="enviar" size="20">
</div>
<div class="row">
Recuperar contraseña
</div>
</form>
The problem is you're returning false from your Ajax function. You need to return false from your click function. Give this a try:
$("#enviar").click(function() {
var error = false;
consulta = $("#email2").val();
$.ajax({
type: "POST",
url: "compruebaEmail.php",
data: "b="+consulta,
dataType: "html",
error: function(){
alert("error petición ajax");
},
success: function(data){
if(data==0){
$("#error").html("Email incorrecto");
error = true;
}
}
});
if (error)
return false;
});
If all you want is canceling the submitting event, then :
Either :
1 - Add the event arg to your click handler :
$("#enviar").click(function(event){
2 - use event.preventDefault(); when you want to cancel the submit message :)
or change the "return false;" location so that it will be triggered in the "click" handler scope and note the "success" scope e.g with a boolean that would represent if there is an error (EDIT : that is Styphon' solution)
Documentation here : http://api.jquery.com/event.preventdefault/