Double insertion of data using modal - php

I`m working on PHP + MYSQL + AJAX project. I used Bootstrap Modal when adding data. After first time I click add, it will insert two records however it only occurs in its first time click.
Is there any way to prevent saving two records.
I appreciate your help and suggestion. Thanks
This is my modal
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data" class="form-horizontal">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="col-lg-3 control-label">Name</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sName" maxlength="150" id="sName" placeholder="Enter your Name" />
<span id='remainingC'></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sUsername" maxlength="20" id="sUsername" placeholder="Enter your Username"/>
<span id='remainingCu'></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Birthday</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sBirthday"
onchange ="getAge();" maxlength="20" id="sBirthday" placeholder="YYYY-mm-dd"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Age</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="iAge" maxlength="3" id="iAge" placeholder="Autofill when you fill Birthday"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sEmail" id="sEmail" placeholder="Enter your Email - eg. jb#gmail.com"/>
</div>
</div>
My AJAX requests
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
$('#operation').val("Add");
// $('#user_uploaded_image').html('');
});
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 4],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var sName = $('#sName').val();
var sUsername = $('#sUsername').val();
var sBirthday = $('#sBirthday').val();
var iAge = $('#iAge').val();
var sEmail = $('#sEmail').val();
if(sName != '' && sUsername != '' && sBirthday != '' && iAge != '' && sEmail != '')
{
$.ajax({
url:"insert.php",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Both Fields are Required");
}
});
This is my Function for adding (insert.php)
if($_POST["operation"] == "Add")
{
$statement = $connection->prepare("
INSERT INTO users (sName, sUsername, sBirthday, iAge, sEmail)
VALUES (:sName, :sUsername, :sBirthday, :iAge, :sEmail)
");
$result = $statement->execute(
array(
':sName' => $_POST["sName"],
':sUsername' => $_POST["sUsername"],
':sBirthday' => $_POST["sBirthday"],
':iAge' => $_POST["iAge"],
':sEmail' => $_POST["sEmail"]
)
);
if(!empty($result))
{
echo 'Data Inserted';
}
}
Duplicate data after 1st click of add button in modal:
Duplicate

Related

Insert multiple values in row php

I can`t find a solution for this formular, so i am asking you guys how i can solve this: (1)I have this formular:
<form id="formRetur" action="" method="POST" novalidate="novalidate">
<div id="mail-status" style="color: black;text-align: center;"></div>
<h3><strong>
Detalii client
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nume_prenume" id="nume_prenume" placeholder="Nume Prenume">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_tlf" id="nr_tlf" placeholder="Numar telefon">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="adresa_email" id="adresa_email" placeholder="Adresa email">
</div>
</div>
</div>
<h3><strong>
Detalii comanda
</strong></h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_comanda" id="nr_comanda" placeholder="Numar comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="data_comanda" id="data_comanda" placeholder="Data comanda">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="nr_factura" id="nr_factura" placeholder="Numar factura">
</div>
</div>
</div>
<h3><strong>
Detalii produse
</strong></h3>
<div class="row">
<i class="fa fa-plus" aria-hidden="true" style="position: absolute;z-index:999;"></i>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="den_prod" id="den_prod" placeholder="Denumire produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="culoare_prod" id="culoare_prod" placeholder="Culoare produs">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" name="cantitate" id="cantitate" placeholder="Cantitate">
</div>
</div>
</div>
<div class="maimulte">
</div>
<h3><strong>
Motiv retur
</strong></h3>
<div class="row">
<div class="col-md-12">
<textarea name="motiv" id="motiv" class="form-control" cols="30" rows="10"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-12" style="margin-top:10px;margin-bottom:10px;"><div class="g-recaptcha" data-sitekey="<?php echo SITE_KEY; ?>"></div> </div>
<div class="col-md-12">
<button type="submit" id="send-message" class="btn btn-default">Trimite </button>
</div>
<div id="loader-icon" style="display:none;"><img src="images/loader.gif"></div>
</div>
</form>
I use ajax to insert data in DB, but i have an option where you can add more products when user press + adding +1 row with 3 fields name,color, qty and i want to insert also these in db, here is my ajax:
<script>
$(document).ready(function (e){
$("#formRetur").on('submit',(function(e){
e.preventDefault();
$("#mail-status").hide();
$('#send-message').hide();
$('#loader-icon').show();
$.ajax({
url: "valid_retur.php",
type: "POST",
dataType:'json',
data: {
"nume_prenume":$('input[name="nume_prenume"]').val(),
"nr_tlf":$('input[name="nr_tlf"]').val(),
"adresa_email":$('input[name="adresa_email"]').val(),
"nr_comanda":$('input[name="nr_comanda"]').val(),
"data_comanda":$('input[name="data_comanda"]').val(),
"nr_factura":$('input[name="nr_factura"]').val(),
"den_prod":$('input[name="den_prod"]').val(),
"culoare_prod":$('input[name="culoare_prod"]').val(),
"cantitate":$('input[name="cantitate"]').val(),
"motiv":$('textarea[name="motiv"]').val(),
"g-recaptcha-response":$('textarea[id="g-recaptcha-response"]').val()},
success: function(response){
// $( '#frmContact' ).each(function(){
// this.reset();
// });
$("#mail-status").show();
$('#loader-icon').hide();
if(response.type == "error") {
$('#send-message').show();
$("#mail-status").attr("class","alert alert-danger");
} else if(response.type == "message"){
// grecaptcha.reset();
$('#send-message').show();
$("#mail-status").attr("class","alert alert-success");
}
$("#mail-status").html(response.text);
},
error: function(){}
});
}));
});
</script>
Here is my db:enter image description here
And there is my php file who insert in db with values from ajax:
<?php
if($_POST)
{
include('config.php');
$nume_prenume = filter_var($_POST["nume_prenume"], FILTER_SANITIZE_STRING);
$nr_tlf = filter_var($_POST["nr_tlf"], FILTER_SANITIZE_STRING);
$adresa_email = filter_var($_POST["adresa_email"], FILTER_SANITIZE_STRING);
$nr_comanda = filter_var($_POST["nr_comanda"], FILTER_SANITIZE_STRING);
$data_comanda = filter_var($_POST["data_comanda"], FILTER_SANITIZE_STRING);
$nr_factura = filter_var($_POST["nr_factura"], FILTER_SANITIZE_STRING);
$den_prod = filter_var($_POST["den_prod"], FILTER_SANITIZE_STRING);
$culoare_prod = filter_var($_POST["culoare_prod"], FILTER_SANITIZE_STRING);
$cantitate = filter_var($_POST["cantitate"], FILTER_SANITIZE_STRING);
$motiv = filter_var($_POST["motiv"], FILTER_SANITIZE_STRING);
if(empty($nume_prenume)) {
$empty[] = "<b>nume_prenume</b>";
}
if(empty($nr_tlf)) {
$empty[] = "<b>nr_tlf</b>";
}
if(empty($adresa_email)) {
$empty[] = "<b>adresa_email</b>";
}
if(empty($nr_comanda)) {
$empty[] = "<b>nr_comanda</b>";
}
if(empty($data_comanda)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($den_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(empty($culoare_prod)) {
$empty[] = "<b>data_comanda</b>";
}
if(!empty($empty)) {
$output = json_encode(array('type'=>'error', 'text' => implode(", ",$empty) . ' obligatoriu!'));
die($output);
}
// if(!filter_var($email2, FILTER_VALIDATE_EMAIL)){ //email validation
// $output = json_encode(array('type'=>'error', 'text' => '<b>'.$email2.'</b> is an invalid Email, please correct it.'));
// die($output);
// }
//reCAPTCHA validation
if (isset($_POST['g-recaptcha-response'])) {
require('component/recaptcha/src/autoload.php');
$recaptcha = new \ReCaptcha\ReCaptcha(SECRET_KEY, new \ReCaptcha\RequestMethod\SocketPost());
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$output = json_encode(array('type'=>'error', 'text' => '<b>Captcha</b> Validation Required!'));
die($output);
}
}
// bag in db
$sql0 = "INSERT INTO retur (nume_prenume, nr_tlf, email, nr_comanda, data_comanda, nr_factura, den_prod, culoare_prod, cantitate_prod, motiv_retur)
VALUES ('$nume_prenume', '$nr_tlf', '$adresa_email', '$nr_comanda', '$data_comanda', '$nr_factura', '$den_prod', '$culoare_prod', '$cantitate', '$motiv')";
mysqli_query($conn, $sql0);
}
So basically this is a formular for returns products and if he have more products to return i added that jquery to add more fields and i want to be inserted in databased then i will fetch data and display it in my CMS.
1.You don't have to write that much code in ajax. You can easily use serialize():
Reduce you ajax code with below code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#your_form_id");
$("#Your_submit_id").click(function(){
$.ajax({
type:"POST",
url:"URL",
data:form.serialize(),
success: function(response){
console.log(response);
}
});
});
});
</script>
2.To add multiple product:
-You have to create every input field as array for product info like:
<input type="text" name="prod_name[]">
This array statement store you every product info index wise. If you
used normal variable then it will post only you last product
details.
In Php code you have to take the count of posted
product title & use for loop to get the every product information.
for($i=0;$i<count($prod_name);$i++)
{
//Insert/fetch All Values like : $prod_name[$i]
}
-When you click on add, just create clone of the prev available div.

Assigning a unique id on different modal content PHP

I have a table which is being populated by book information using a while loop to fetch and display the results. The table consist of Book information and an Action Column which handles some functions like adding of quantity and deduction of quantity , etc..
Each button on the Action Column is using a modal to show the needed contents
like text boxes.
So my main problem right now is the contents of the modal only works on the first data of the table. I don't know if I'm missing something here or im doing it wrong. Any help would be great! (Im using ajax to insert data)
I can update this post if you need the php code on binding data on the table.
HTML code for the modal
<!-- ADD STOCK QUANTITY -->
<div class="modal fade" id="addqty<?php echo $bookisbn;?>" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content ">
<div class="modal-header">
<h3 style="text-align: center;">Add Stock/s
</h3>
</div>
<div class="modal-body">
<!-- <form role="form" id="add_stock_form" name="add_stock_form"> -->
<div class="row clearfix">
<div class="col-md-12">
<div class="form-group form-float">
<div class="form-line">
<label for="book_isbn1" class="form-label">Book ISBN
</label>
<input type="text" class="form-control text-center" id="book_isbn_as" name="book_isbn_as" value="<?php echo $bookisbn;?>" readonly>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-12">
<div class="form-group form-float">
<div class="form-line">
<input type="hidden" class="form-control" id="book_title_as" name="book_title_as" value="<?php echo $booktitle;?>" readonly>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-md-6">
<div class="form-group form-float">
<div class="form-line">
<input type="number" class="form-control text-center" id="currentstock_as" name="currentstock_as" value="<?php echo $bookquantity;?>" readonly>
<label for="currentstock" class="form-label">Current Stock/s
</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-float">
<div class="form-line">
<input min="0" class="form-control text-center" type="text" id="book_quantity_as" name="book_quantity_as" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57" required>
<label for="book_quantity_as" class="form-label">Enter Stock
</label>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="btn_add_stock" name="btn_add_stock" class="btn btn-success waves-effect">
<i class="material-icons">add
</i> ADD
</button>
<button type="button" class="btn btn-danger waves-effect" data-dismiss="modal">
<i class="material-icons">clear
</i> CLOSE
</button>
</div>
</div>
</div>
</div>
<!-- END OF ADD STOCK QUANTITY -->
Ajax Script
// //add quantity
$(document).on("click", "#btn_add_stock", function() {
var getbookisbn = $("#book_isbn_as").val();
var getbooktitle = $("#book_title_as").val();
var getbookquantity = $("#book_quantity_as").val();
var getcurrentquantity = $("#current_stock_as").val();
var whatprocess = "ADDBOOKQUANTITY";
if (validationaddquantity == 1) {
$.ajax({
url: "adminfunctions.php",
method: "POST",
data: {
getbookisbn: getbookisbn,
getbooktitle: getbooktitle,
getbookquantity: getbookquantity,
whatprocess: whatprocess
},
success: function(data) {
var getdata = data.trim();
if (getdata == "SUCCESS") {
swal({
title: 'Success!',
text: 'Quantity Added',
type: 'success',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).then(function() {
/////REFRESH DATATABLE
$("#datatables").load(window.location + " #datatables");
$('#book_quantity_as').val("");
});
} else if (getdata == "ERROR") {
swal({
title: 'Sorry...',
text: "You cannot perform that action right now",
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).then(function() {
fetch_data();
});
} else {
swal({
title: 'Sorry for the inconvenience!',
text: "There's a problem. Please contact the technical support for any concerns and questions.!",
type: 'error',
confirmButtonClass: "btn btn-danger",
buttonsStyling: false
}).catch(swal.noop)
}
},
error: function(jqXHR, exception) {
console.log(jqXHR);
}
});
} else if (validationaddquantity != 1) {
swal({
title: 'Oops..!',
text: 'You must enter a value to proceed',
type: 'warning',
confirmButtonClass: "btn btn-success",
buttonsStyling: false
}).catch(swal.noop)
}
});
on.show.bs.modal function trigger call you must re-assign value your row data (via ajax or get by td value on a table then post )to modal element input (i see is hidden input).
So every time call a modal your content data is shown based on click row table.
Maybe can solve ur problem..

Ajax file upload without formdata

when i try to upload a file, all data send to database but the input file is empty and won't upload the file how can i send file with my
actual ajax submit form ? without dataForm i'm new to ajax and mysql
here's my code:
function getUsers(){
$.ajax({
type: 'POST',
url: 'tpl/add.php',
data: 'action_type=view&'+$("#userForm").serialize(),
success:function(html){
$('#userData').html(html);
}
});
}
function userAction(type,idb){
id = (typeof idb == "undefined")?'':idb;
var statusArr = {add:"ajouter",edit:"mises à jour",delete:"supprimer"};
var userData = '';
if (type == 'add') {
userData = $("#addForm").find('.form').serialize()+'&action_type='+type+'&idb='+idb;
}else if (type == 'edit'){
userData = $("#editForm").find('.form').serialize()+'&action_type='+type;
}else if (type == 'view'){
userData = $("#viewForm").find('.form').serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&idb='+idb;
}
$.ajax({
url: 'tpl/add.php',
cache: false,
data: userData,
type: 'POST',
contentType: false,
processData: false,
success:function(msg){
if(msg == 'ok'){
alert('Le model a été '+statusArr[type]+' avec succès.');
getUsers();
$('.form')[0].reset();
$('#myModal2').modal('hide');
$('#myModal').modal('hide');
}else{
alert('Un probleme à été detecter, veuillez reessayer.');
}
}
});
}
function editUser(idb){
$.ajax({
type: 'POST',
dataType:'JSON',
url: 'tpl/add.php',
data: 'action_type=data&idb='+idb,
success:function(data){
$('#idbEdit').val(data.idb);
$('#modelEdit').val(data.model);
$('#urldemoEdit').val(data.urldemo);
$('#modelfichEdit').val(data.modelfich);
$('#etatEdit').val(data.etat);
$('#editForm').slideDown();
}
});
}
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Ajouter un modele</h4>
</div>
<div class="modal-body" id="addForm">
<form class="form form-horizontal" method="post" id="userForm" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-3">Modele HTML</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="model" id="model"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Aperçu</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="urldemo" id="urldemo"/>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Fichier HTML </label>
<div class="col-sm-9">
<input type="file" name="file" id="file" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Etat</label>
<div class="col-sm-9">
<select name="etat" id="etat" class="form-control">
<option value="0">activé</option>
<option value="1">désactivé</option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
Ajouter
<button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
</div>
</form>
</div>
</div>
</div>

Jquery ajax posts twice

I got an ajax issue I can't get my head around. I'm using a ajax post method to send an email. But everytime I send one the post happens 2 times. I've tried adding preventDefault and stopPropagation but it doesn't seem to do the trick.
Jquery
$(document).ready(function()
{
$("#submit_btn").click(function(event)
{
event.preventDefault();
event.stopPropagation();
var proceed = true;
var submit = $('#submit_btn');
$("#contact_form input, #contact_form textarea").each(function () {
$(this).closest("div").removeClass('has-error');
if(!$.trim($(this).val())) {
$(this).closest("div").addClass('has-error');
proceed = false;
}
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).closest("div").addClass('has-error');
proceed = false;
}
});
if(proceed){
post_data = {
'user_name' : $('input[name=name]').val(),
'user_email' : $('input[name=email]').val(),
'subject' : $('select[name=subject]').val(),
'msg' : $('textarea[name=message]').val()
};
$.ajax({
type: 'POST',
url: "./mail.php",
data: post_data,
beforeSend: function() {
submit.html('Sending...');
},
success: function(data){
output = '<div class="alert alert-success" role="alert">Hi ' + $('input[name=name]').val() + ' Thank you for your email</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
},
error: function(){
output = '<div class="alert alert-danger" role="alert">Something went wrong. Please try again</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
submit.html("Send");
}
});
return false;
}
else{
output = '<div class="alert alert-danger" role="alert">Please fill in the required fields so I can get back to you !</div>';
$("#contact_form").find("#contact_results").html(output).slideDown();
}
});
$("#contact_form input, #contact_form textarea").keyup(function() {
$(this).closest("div").removeClass('has-error');
$("#contact_form").find("#contact_results").slideUp();
});
});
HTML
<div class="clear" id="contact">
<h3>Contact Me</h3>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<form role="form" id="contact_form" action="">
<div class="form-group">
<label for="name">Name</label><input name="name" type="text" placeholder="Name" class="form-control" id="name" />
</div>
<div class="form-group">
<label for="email">Email address</label>
<input name="email" type="email" placeholder="E-Mail" class="form-control" id="email" />
</div>
<div class="form-group">
<label for="subject">Subject</label>
<select name="subject" class="form-control" id="subject">
<option value="General Question">General Question</option>
<option value="Hire me!">Hire me !</option>
<option value="Partner with me!">Partner with me !</option>
</select>
</div>
<div class="form-group">
<label for="message">Message</label><textarea name="message" placeholder="Message" id="message" class="form-control" rows="5"></textarea>
</div>
<button type="submit" class="btn btn-default" id="submit_btn">Send</button>
<div id="contact_results"></div>
</form>
</div>
</div>
</div>
</div>
If someone could point me in the right direction that would be much appreciated.
Try changing $("#submit_btn").click(function(event) to $("#submit_btn").one('click',function(event)
If that doesn't work, check that the JS is not being loaded twice

Trouble with registration using codeigniter

I have a registration form for my website, and it is showing username, password and password confirmation required although i am providing all of these. This is the controller code:
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]|xss_clean');
$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_rules('pass1','Password','trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('pass2','Password Confirmation','trim|required|matches[pass1]');
if ($this->form_validation->run() === FALSE)
{
$password = $this->input->post('pass1');
echo json_encode(array('error' => '1', 'message' => validation_errors('<div class="alert alert-error"><strong>Error!</strong> ', '</div>')));
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('pass1');
$email = $this->input->post('email');
$date = date('Y/m/d H:i:s');
$this->load->model('ui_model');
$this->ui_model->register_user($username,$password,$email,$date);
echo json_encode(array('error' => '0', 'message' => '<div class="alert alert-success"><strong>Success!</strong> You have been registered!</div>'));
}
and this is the view code:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Registration</h3>
</div>
<div class="modal-body">
<div id="registerModalerror" style="display: none;"></div>
<?php
$attributes = array('class' => 'form-horizontal','id' => 'registerModalform');
echo form_open('',$attributes);
?>
<div class="control-group">
<label class="control-label" for="Username">Username</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" id="inputUser" placeholder="Username" name="username" value ="" >
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-envelope"></i></span>
<input type="text" id="inputEmail" placeholder="email" name="email" value = "">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" id="inputPassword" placeholder="Password" name="pass1" value = "">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword2">Retype Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" id="inputPassword2" placeholder="Retype Password" name="pass2" value = "">
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Register</button>
</div>
</div>
</div>
<?php echo form_close(); ?>
<div class="modal-footer">
</div>
</div>
<script>
$(document).ready(function() {
$('#myModalReg').removeData('modal');
$('#myModalReg').hide();
$('#registerModalform').submit(registerUser);
});
function registerUser(event)
{
//Stop the form from submitting
event.preventDefault();
//Collect our form data.
var form_data = {
username : $("[name='username']").val(),
password1 : $("[name='pass1']").val(),
password2 : $("[name='pass2']").val(),
email : $("[name='email']").val()
};
//Begin the ajax call
$.ajax({
url: "http://localhost/fys/index.php/ui/do_register",
type: "POST",
data: form_data,
dataType: "json",
cache: false,
async : false,
success: function (json) {
// alert(json.pass);
if (json.error==1)
{
$('#registerModalerror').html(json.message).show();
}
else {
//Hide our form
$('#registerModalform').slideUp();
//Show the success message
$('#registerModalerror').html(json.message).show();
}
},
error: function(json)
{
alert(json.message);
}
});
}
</script>
I am not sure where it went wrong, and it is bugging me for almost 24 hours. Can anyone provide some help?
Thanks!
Your POST object is
{
username : $("[name='username']").val(),
password1 : $("[name='pass1']").val(),
password2 : $("[name='pass2']").val(),
email : $("[name='email']").val()
}
But your Controller's POST name is pass1 and pass2. You're passing up password1 and password2
:P

Categories