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.
Related
I have a modal for entering user information. A user should be linked to a building. After user information has been entered and submit button has been clicked, I am preventing the default action and am overlaying/showing a building modal over the user modal.
Code for doing so follows.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
}
});
$('#modalConnectBuilding').modal('show');
});
})(window.jQuery);
console.log() logs the input information correctly, however in 'modalConnectBuilding.php' the following does not work:
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];
?>
Producing the following errors:
Undefined index: name_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: address_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: city_user in
C:\laragon\www\modals\modalConnectBuilding.php
My intent is to do a classic 'form action="./php/processConnectBuilding.php" method="post"' but would need access to the three undefined variables as seen above. Adding users and buildings works in isolation but not when connected in this way. Any help would be greatly appreciated and if you need any more info, please ask. Thank you!
Code for the form (within the modal) I'm submitting follows (please note, default action is being suppressed by preventDefault() so action attribute is never "called", also the form for connecting a building is basically the same, but the action attribute is not suppressed):
<form role="form" id="formAddUser" action="./php/processAddUser.php" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<form role="form" id="formAddUser" action="" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" id="name" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>
</body>
</html>
<script>
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: 'tariffdetaildata.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function(data) {
alert(data)
}
});
});
</script>
tariffdetaildata.php
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];
Try this way I think you need to open the modal popup once you get the response back from the ajax.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
$('#modalConnectBuilding').modal('show');
$("#modalConnectBuilding .modal-body #name_user").val( name_user);
$("#modalConnectBuilding .modal-body #address_user").val( address_user);
$("#modalConnectBuilding .modal-body #city_user").val( city_user);
}
});
});
})(window.jQuery);
Right now I am facing a problem : I am trying to insert records in the database with the help of jQuery & Ajax. Unfortunately, I tried to alert inserted values but It doesn't show. I also checked through serialize function and I am unable to do that.
Here is my code of ajax
<script type="text/javascript">
$(document).ready(function(){
$("#add_new").click(function(){
$("#add").slideToggle();
});
$("#submit").click(function(){
var stud_no=$("#roll").val();
if(stud_no==''){
$("#msg").html("Input Roll Number");
} else {
var datastr = $("#sampleform").serialize();
alert(datastr);
$.ajax({
type:'POST',
url:'add_it.php',
data:datastr,
success:function(response){
$("#my_form")[0].reset();
$("#msg").html("Student Successfully Added");
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
});
});
</script>
Here is body code :
<body>
<a id="add_new">+add new item</a><br /><br />
<div id="msg"></div><br />
<div id="add">
<form id="sampleform">
<fieldset>
<div class="form-group row">
<label for="roll" class="col-sm-2 col-form-label">Roll Number</label>
<div class="col-sm-6">
<input type="text" name="roll" class="form-control" id="roll">
</div>
</div>
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-6">
<input type="text" name="name" class="form-control" id="name">
</div>
</div>
<div class="form-group row">
<label for="clas" class="col-sm-2 col-form-label">Class</label>
<div class="col-sm-6">
<input type="text" name="standard" class="form-control" id="standard">
</div>
</div>
<div class="form-group row">
<label for="mail" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-6">
<input type="email" name="mail" class="form-control" id="mail">
</div>
</div>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</fieldset>
</fieldset>
</form>
</div>
Here is my add_it.php
<?php
include('connectdb.php');
$stud_no = trim($_POST['stud_no']);
$name = trim($_POST['name']);
$standard = trim($_POST['standard']);
$mail = trim($_POST['mail']);
$query = "insert into student (stud_no,name,standard,email) values ('$stud_no','$name','$standard','$mail')";
mysqli_query($con,$query) or die (mysqli_error());
?>
Your HTML form fields doesnt have any of these variables sent. You need to add name="email" etc to your form fields.
So for example the email field has to look like this:
<input type="email" name="email" class="form-control" id="mail">
id, class etc is not sent in POST - and therefor can not be recieved in the other end.
Jquery's serialize() function also only handles "name" fields.
https://api.jquery.com/serialize/
Snippet :
For a form element's value to be included in the serialized string, the element must have a name attribute
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({
....
});
}
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);
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