how to get data from form serialize codeigniter controller - php

I try to get data from ajax pass from front page to my controller but i got only string to my controller so how can i separate it one by one.
this is form:
<form class="form-horizontal form" action="<?php print base_url() ?>insertCategory" method="post" enctype='multipart/form-data'>
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">name</label>
<div class="col-sm-10">
<input type="text" name='name' required class="form-control" id="inputEmail3" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">name</label>
<div class="col-sm-10">
<input type="text" name='test' required class="form-control" id="inputEmail3" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Category Detail</label>
<div class="col-sm-10">
<textarea id="txtEditor" ></textarea>
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Image</label>
<div class="col-sm-10">
<input type="file" name="img" required class="form-control" >
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right submit">Submit</button>
</div>
<!-- /.box-footer -->
</form>
this my code ajax:
$(".submit").click(function (e) {
e.preventDefault();
var data = $('.form').serialize();
var val = $("#txtEditor").Editor("getText");
var page = "<?php echo $page ?>";
var url = "<?php echo base_url(); ?>insertCategory"
$.ajax({
type: "POST",
url: url,
data:{
"data" : data
},
success: function (data) {
console.log(data);
}
});
return false;
});
and this is my controller:
public function insertCategory()
{
if($this->session->userdata('logged_in')==1){
$data = $this->input->post('data');
var_dump($data);
and this my data respond by ajax:
C:\....\AdminController.php:308:string 'name=dsfdsfs&test=dfsdf' (length=23)

Use this instead,
var_dump($_POST);
it is posted as same as post work

For reference, use this code below.
type: "POST",
url: url,
data: $('.form').serialize(),
success: function (data) {
console.log(data);
}
Use
data: $('.form').serialize()
instead of
var data = $('.form').serialize();
data:{
"data" : data
},

At the controller the contents of your form will be available in the $_POST array. So the "name" field on your form can be accessed with $_POST['name'].
That said, you will be better off using CodeIgniter's methods to retrieve this data.
For example:
$name = $this->input->post('name');
If, for learning purposes, you wanted to see everything "posted" to the controller this will do the trick.
public function insertCategory()
{
if($this->session->userdata('logged_in')==1)
{
$posted = $this->input->post(); //get all $_POST items
var_dump($posted);
}
}

use parse_str(); that can return array after parse string
public function insertCategory()
{
if($this->session->userdata('logged_in')==1){
$data = $this->input->post('data');
parse_str($data, $parseData);
var_dump($parseData);

Related

Using 2 recaptcha on same page and getting different values for both via AJAX

I have 2 Google Recaptcha's on same page in different forms (Login and Register Forms). I had to put both the forms on the same page due to the designing requirements which can't be changed. Now the problem is that the 1st form is the login form followed by the register form in the 2nd. Now, the recaptcha on the login form takes effect for register form as well. I mean that I can see recaptcha on both the forms but the one in register form doesn't work (which means it doesn't sends the correct value to the PHP page where the form will be processed). When I tried verifying the recaptcha on the login form and submitting the register form it worked. This means that the 1st loaded recaptcha (on the login form) is working for both which should not be. Both the recaptchas should work separately for each forms. Also, when I get the values of both the recaptchas via AJAX to send to the PHP page for the server side validation I am using captcha: grecaptcha.getResponse() for both. THIS CAN BE THE ACTUAL PROBLEM I GUESS. If I could get separate values for both maybe the things would have gone down well. Any help would be appreciated.
Here are my codes.
<div class="container">
<div class="row">
<div class="col-md-6">
<h3 class="com-reps cr-panel">Login Now</h3>
</div>
<div class="col-md-6">
<h3 class="com-reps cr-panel">Register Now</h3>
</div>
<div class="col-md-6">
<div class="post-holder">
<div class="login-message"></div>
<div class="post-content">
<form method="post" action="">
<div class="form-group">
<input type="text" id="uname" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input type="password" id="pass" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="<?php echo $mainf['set_recaptcha_sitekey']; ?>"></div>
</div>
<div class="form-group">
<input type="submit" id="login" value="Log In" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
<div class="col-md-6">
<div class="post-holder">
<div class="register-message"></div>
<div class="post-content">
<form method="post" action="">
<div class="form-group">
<input type="text" id="name" class="form-control" placeholder="Full Name">
</div>
<div class="form-group">
<input type="text" id="username" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input type="password" id="password" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="password" id="cpass" class="form-control" placeholder="Confirm Password">
</div>
<div class="form-group">
<input type="text" id="email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="text" id="dob" class="form-control" placeholder="Date of Birth">
</div>
<div class="form-group">
Sex
<input type="radio" id="sex" name="sex"> Male
<input type="radio" id="sex" name="sex"> Female
</div>
<div class="form-group">
<input type="checkbox" id="legal" name="legal"> I accept the Terms of Service and Privacy Policy.
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="<?php echo $mainf['set_recaptcha_sitekey']; ?>"></div>
</div>
<div class="form-group">
<input type="submit" id="submit" value="Register" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#login").click(function(){
var dataString = {
uname: $("#uname").val(),
pass: $("#pass").val(),
captcha: grecaptcha.getResponse()
};
$.ajax({
type: "POST",
//dataType : "json",
url: "processes/login.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#login").val("Please wait...");
$(".login-message").hide();
},
success: function(html){
$('.login-message').html(html).fadeIn();
if($('.login-message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
window.location.replace("index.php");
}, 500);
}else{
$("#login").val("Log In");
}
}
});
return false;
});
$("#submit").click(function(){
var dataString = {
name: $("#name").val(),
uname: $("#username").val(),
pass: $("#password").val(),
cpass: $("#cpass").val(),
email: $("#email").val(),
dob: $("#dob").val(),
sex: $("input[name='sex']:checked").val(),
captcha: grecaptcha.getResponse()
};
$.ajax({
type: "POST",
//dataType : "json",
url: "processes/register.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").val("Please wait...");
$(".register-message").hide();
},
success: function(html){
$('.register-message').html(html).fadeIn();
$("#submit").val("Register");
}
});
return false;
});
});
</script>
I got the solution. In case someone comes looking for this it will help them.
In both HTML Forms replace
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
to
<div id="recaptcha1"></div> and <div id="recaptcha2"></div> respectively.
Then replace your script calling from
<script src="https://www.google.com/recaptcha/api.js></script>
to
<script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
And insert these code in your <script></script>. Note that this should be outside of $(document).ready(function() { and above your next form submission AJAX codes.
var recaptcha1;
var recaptcha2;
var myCallBack = function() {
recaptcha1 = grecaptcha.render('recaptcha1', {
'sitekey' : 'YOUR_SITE_KEY'
});
recaptcha2 = grecaptcha.render('recaptcha2', {
'sitekey' : 'YOUR_SITE_KEY'
});
};
Next and last thing, change the captcha: grecaptcha.getResponse() in your form submission AJAX code to captcha: grecaptcha.getResponse(recaptcha1) and captcha: grecaptcha.getResponse(recaptcha2) respectively (for both AJAX codes of login and register forms in my case). For full form submission code please refer to the code in my question above. Just replace the captcha: part here as said.
Done! Now you can proceed to server side validation in your language (PHP or ASP whatever).

Post edit form data and get it in controller using angularjs

I want to post edit form data to codeigniter controller using angularjs
this is my angularjs controller where i collect and post form data
$scope.editlist = function(id){
$http({
method:'post',
url:'http://localhost/Angular_demo/admin/index.php/welcome/get_edit_data/'+
id
}).then(function success(response){
$scope.sid = parseInt(response.data[0]['id']);
$scope.firstname = response.data[0]["first_name"];
$scope.lastname = response.data[0]['last_name'];
$scope.email = response.data[0]['email'];
});
}
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:'id='+ id + '&first_name='+firstname+
'&last_name='+lastname+'&email='+email,
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
My view where i bind and post form data
<form name="editItem" class="form-horizontal">
<input ng-model="sid" type="hidden" placeholder="Name" name="name"
class="form-control" />
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">First
Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="firstname"
id="inputEmail3" placeholder="First name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Last
Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="lastname"
id="inputEmail3" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-
label">Email</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="email"
id="inputEmail3" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" data-
dismiss="modal">Close</button>
<button type="submit" ng-disabled="editdata.$invalid"
class="btn btn-primary create-crud" data-dismiss="modal" ng-
click="saveEdit(sid,firstname,lastname,email)">Submit</button>
</div>
</div>
</form>
This is my codeigniter controller where i want to get form data
public function update_data(){
$requests = json_decode(file_get_contents('php://input'), TRUE);
$ids= array('id' =>$requests['id']);
echo json_encode($ids);
}
When i submit my form data will show null in my controller,so please help how to get form data in controller.
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:'id='+ id + '&first_name='+firstname+
'&last_name='+lastname+'&email='+email,
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
This should be like this:-
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:{"id": id,"first_name":firstname,
"last_name":lastname,"email":email}
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
Since the codeigniter code uses json_decode, the $http service should use a JavaScript object to post the data:
$scope.saveEdit = function(id,firstname,lastname,email) {
var url = 'http://localhost/Angular_demo/admin/index.php/welcome/update_data';
var data = {
id: id,
first_name: firstname,
last_name: lastname,
email: email,
};
$http.post(url, data
).then(function success(response){
console.log(response.data);
});
}
The AngularJS framework will automatically encode the JavaScript object as a JSON string.

cannot input textarea with CKeditor on Codeigniter

when i want to input textarea with CKeditor , the string is Null , but when i delete class="CKeditor" in textarea the string successfully filled.
i have check in controller and database but it does not matter
My Controller
function AddNews(){
$data = array(
'title_news' => $this->input->post('title_news'),
'text' => $this->input->post('text_news'),
'date' => $this->input->post('date'),
);
$insert = $this->m_news->save($data);
echo json_encode(array("status" => TRUE));
}
My View
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id_news"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title News </label>
<div class="col-md-9">
<input name="title_news" placeholder="Title Name" class="form-control" type="text"><span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Title News </label>
<div class="col-md-9">
<textarea class="ckeditor" name="text_news" rows="3" placeholder="Enter text . . . "></textarea><span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date</label>
<div class="col-md-9">
<div class="input-group">
<input class="form-control date-picker" name="date" type="text" data-date-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" /><span class="input-group-addon"><i class="fa fa-calendar bigger-110"></i></span>
</div>
</div>
</div>
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
</div>
</form>
My Ajax Input
function save()
{
var formData = new FormData($('#form')[0]);
$.ajax({
url : "<?php echo base_url('admin-spot/news/AddNews')?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
redirect: true,
success: function(data){
if(data.status){
$('#modal_form').modal('hide');
}
else
{}
error: function (jqXHR, textStatus, errorThrown){
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
My Model
function Save($data)
{
$sql = $this->db->insert($this->table, $data);
return $sql;
}
hello guys,
when I want to input textarea with CKeditor , the string is Null , but when I delete class="CKeditor" in textarea the string successfully filled.
I have check in controller and database but it does not matter
Add this to your script
function save()
{
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
var formData = new FormData($('#form')[0]);
$.ajax({
....
});
}

PHP ajax post data empty

I am posting form data from create.php as below using $.ajax.
$(document).ready(function () {
var request;
$("#create-pto").submit(function(e) {
// Abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: 'index.php',
type: 'POST',
contentType : 'application/json',
data: serializedData
}).done(function (response, textStatus, jqXHR) {
// Log a message to the console
console.log("Hooray, it worked!");
});
e.preventDefault();
});
});
I can see the posted data and i can log post success.
But in index.php could not retrieve posted data.
This is what i am trying in index.php
var_dump($_POST);
Form :
<form class="form-horizontal" id="create-pto" >
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control- label">App ID</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="app-id" id="app-id" placeholder="App ID">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">App Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="app-name" id="app-name"
placeholder="App Name">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Instance Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="inputPassword3" name="ins-name"
placeholder="Instance Name">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="create" class="btn btn-success">Create PTO</button>
</div>
</div>
</form>
Pls help.
Try changing the contentType on your JavaScript code:
contentType : 'application/x-www-form-urlencoded',
And if you want to keep the contentType to json, try this way on your PHP file:
echo file_get_contents('php://input');
If you use .serialize() you need to change contentType to 'application/x-www-form-urlencoded'.
If you want to keep contentType: 'application/json' you have to use JSON.stringify instead.
Also note that JSON strings in POST requests are retreived using file_get_contents('php://input'); not $_POST
Change your
contentType : 'application/json'
to
dataType: "JSON"
It will start work.. I tested code on my system.
try type:GET instead of type:POST,also call var_dump($_GET) in index.php

how to load html page using ajax code

i use the following code to load the form as below code
as Ajax code as below
function assessment_form() {
$this = $(this);
$.ajax({
url: 'view/assessment/assessment_form.php',
datatype: 'html',
success: function (data) {
$box = $('.span12');
$box.after(data);
$box.remove();
}
});
}
$(document).on('click', '#assessment_form', $(this), assessment_form);
and the form page as below in directory view/assessment/assessment_form.php
Add New User
<div class="box span12">
<div class="box-header well" data-original-title>
<h2> Add New User</h2>
</div>
<div class="box-content">
<form class="form-horizontal" id="user_form_data" enctype="multipart/form-data">
<fieldset>
<div class="control-group">
<label class="control-label" for="firstname">ROTC NO</label>
<div class="controls">
<input class="input-xlarge focused" id="rotc_no" name="rotc_no" type="text" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="lastname">Password</label>
<div class="controls">
<input class="input-xlarge focused" id="password" name="password" type="text" />
</div>
</div>
Simply, You can load html page into a div by using jquery's load() function.
Try this:
$('#yourDiv').load('pages/page1.html');
use this $(document).on('click','#assessment_form', assessment_form);
instead of $(document).on('click','#assessment_form',$(this),assessment_form);
Take a look for more information $.get()
// Make it little more flexible and easy
function assessment_form() {
$.get('your_url', function(data){
$box = $('.span12');
$box.after(data);
$box.remove();
});
}

Categories