I want to insert row in database using ajax jquery post method for that i am using the below code in Codeigniter, but my data is not inserted in a database.
Please help to sort out my issue.
View:
$("#Submit_Course_Goal").on("click", function (e) {
e.preventDefault();
var dataString = $("form#courseGoalForm").serializeArray();
alert("datastring"+dataString);
$.ajax({
type: "post",
url: "<?php echo base_url();?>create_course/create_course_goal",
cache: false,
data: dataString,
success: function(data){
alert("data"+data);
},
error: function(){
alert('Error while request..');
}
});
});
<form name="courseGoalForm" id="courseGoalForm" action="" method="post" enctype="multipart/form-data">
<input type="hidden" name="c_id" value="<?=$result;?>" />
<textarea data-focus="false" rows="8" name="description1"> </textarea>
<textarea data-focus="false" rows="8" name="description2"> </textarea>
<textarea data-lang="en" rows="8" name="description3"> </textarea>
<input type="submit" name="submit" value="Save" class="btn btn-primary btn btn-success" id="Submit_Course_Goal" />
</form>
Model:
public function create_course_goal($data,$id) {
$this->load->database();
$this->db->where('id', $id);
$this->db->update('course', $data);
$course_id=$id;
if ($this->db->affected_rows() > 0) {
return $course_id;
}
else
{
return false;
}
}
Controller:
public function create_course_goal(){
$course_goal1=$this->input->post('description1');
$course_goal2=$this->input->post('description2');
$course_goal3=$this->input->post('description3');
$id=$this->input->post('c_id');
$data=array('course_goal1'=>$course_goal1,'course_goal2'=>$course_goal2,'course_goal3'=>$course_goal3);
$result_course = $this->course_model->create_course_goal($data,$id);
if($result_course!='false')
{
return true;
}
else
{
return false;
}
}
have you tried this !
var dataString = $("#courseGoalForm").serialize();
instead of
var dataString = $("form#courseGoalForm").serializeArray();
Try these codes.
("#Submit_Course_Goal").on("click", function (e) {
e.preventDefault();
var description1 = $("#description1").val();
var description2 = $("#description2").val();
var description3 = $("#description3").val();
$.ajax({
type: "post",
url: "<?php echo base_url();?>create_course/create_course_goal",
cache: false,
data: {
desc1 : description1,
desc2 : description2,
desc3 : description3
},
success: function(data){
console.log(data);
},
error: function(){
alert('Error while request..');
}
});
});
<!-- Form -->
<form name="courseGoalForm" id="courseGoalForm" action="" method="post" enctype="multipart/form-data" onclick="return false">
<input type="hidden" name="c_id" value="<?=$result;?>" />
<textarea data-focus="false" rows="8" name="description1" id="description1"> </textarea>
<textarea data-focus="false" rows="8" name="description2" id="description2"> </textarea>
<textarea data-lang="en" rows="8" name="description3" id="description3"> </textarea>
<input type="submit" name="submit" value="Save" class="btn btn-primary btn btn-success" id="Submit_Course_Goal" />
</form>
<!-- Controller -->
<?php
public function create_course_goal(){
$data=array(
'ID' => $this->input->post('c_id'),
'course_goal1'=> $this->input->post('desc1'),
'course_goal2'=> $this->input->post('desc2'),
'course_goal3'=> $this->input->post('desc3')
);
$result = $this->course_model->create_course_goal($data);
if ($result) {
echo 'success';
}else echo 'fail';
}
/*MODEL*/
function create_course_goal($data = array())
{
return $this->db->insert('course',$data);
}
?>
Try this.
Controller.
public function create_course_goal(){
$data=array(
'ID' => $this->input->post('c_id'),
'course_goal1'=> $this->input->post('description1'),
'course_goal2'=> $this->input->post('description2'),
'course_goal3'=> $this->input->post('description3')
);
$result = $this->course_model->create_course_goal($data);
if ($result) {
echo 'success';
}else echo 'fail';
}
Model
function create_course_goal($options = array())
{
if(isset($options['course_goal1']))
$this->db->set('course_goal1',$options['course_goal1']);;
if(isset($options['course_goal2']))
$this->db->set('course_goal2',$options['course_goal2']);;
if(isset($options['course_goal3']))
$this->db->set('course_goal3',$options['course_goal3']);;
$this->db->where('ID',$options['ID']);
$this->db->update('course');
return $this->db->affected_rows();
}
Note : course_goal1, course_goal2, course_goal3 should be same as in database. and course should be database table's name.
This was for update database if you want to insert new data use this model
function addNewData($data = array())
{
return $this->db->insert('course',$data);
}
Note 2 : in your database 'id' should be primary and auto incrementing
your table name should be 'course'
and row names should be 'course_goal1', 'course_goal2', 'course_goal3'
Have you tried removing method='post' from the Form and submit your data with ajax
Related
I'm trying to post input data and display it on the same page (view_group.php) using AJAX but I did not understand how it works with MVC, I'm new with MVC if anyone could help me it would be very helpful for me.
view_group.php
<script type = "text/javascript" >
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
var status_content = $('#status_content').val();
$.ajax({
type: "POST",
url: "view_group.php",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {}
});
});
}); </script>
if(isset($_POST['postStatus'])){ $status->postStatus($group_id); }
?>
<form class="forms-sample" method="post" id="form-status">
<div class="form-group">
<textarea class="form-control" name="status_content" id="status_content" rows="5" placeholder="Share something"></textarea>
</div>
<input type="submit" class="btn btn-primary" id="submit" name="submit" value="Post" />
</form>
<span id="result"></span>
my controller
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
}
first in the ajax url you must set your controller url , then on success result value will be set on your html attribute .
$.ajax({
type: "POST",
url: "your controller url here",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {
$('#result).text(result);
}
});
Then on your controller you must echo the result you want to send to your page
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
echo $status;
}
I am storing the unicode values in java script array but when I pass it to the ci controller it is not showing in proper language.
How to pass javascript unicode array to php using form post?
My code is:-
var myTableArray = [];
$("table#search_result_table tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
var myJSON = JSON.stringify(myTableArray);
$.post("<?php echo base_url("Purchase/addnew"); ?>",{data:
myJSON},$("#purform").serialize(),function(data)
Santosh, to post Unicode Array through AJAX and JSON, you need 3 files i.e. Javascript file, html file and a php file. Below is the samle code,
JS file
// make the AJAX request
// #dataform : it is a html data form id
var dataString = $('#dataform').serialize();
$.ajax({
type: "POST",
url: 'php_file.php',
data: dataString,
dataType: 'json',
success: function (data) {
if (data.success == 0) {
var errors = '';
if (data.err_msg != '')
alert('Error');
}
else if (data.success == 1) {
alert('Success');
}
},
error: function (x,e) {
alert('Error: '+x.status+','+x.responseText);
}
});
HTML file
<form id="dataform" name="dataform" method="post" action="" role="form">
<input type="text" name="field1" id="field1" />
<input type="text" name="field2" id="field2" />
<input type="text" name="field3" id="field3" />
<input type="text" name="field4" id="field4" />
<button type="button" name="submit" id="submit" onclick="return false;">Submit</button>
</form>
PHP file
$field1=$_REQUEST["field1"];
$field2=$_REQUEST["field2"];
$field3=$_REQUEST["field3"];
$field4=$_REQUEST["field4"];
//Your Validation Logic
$return_array = validate($field1);
if($return_array['success'] == '1') {
//Your SQL Query //
}
function validate($field1)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['err_msg'] = '';
//Validate Field Logic
if($field1=='')
{
$return_array['success'] = '0';
$return_array['err_msg'] = 'Field1 is required!';
}
return $return_array;
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
I have a form and it have 2 submit button.
<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
<input type="text" name="title" id="title" class="form-control" required="required">
....some form fields...
<input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
<input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>
i am using ajax to send/receive data.
$('#posting input[type="submit"]').on("click", function(e) {
e.preventDefault;
var btn = $('#publish');
var el = $(this).attr('id');
$.ajax({
type: 'post',
url: $('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: {
data: $('form#posting').serialize(),
action: el
},
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if (data.success == false) {
var arr = data.errors;
$.each(arr, function(index, value) {
if (value.length != 0) {
$("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto Edit. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
this is my php file. posting_bk.php
if ($_POST['action'] == 'publish') {
if($title == 'test'){
array_push($res['errors'], 'data received by php.');
}else{
array_push($res['errors'], 'No data received by php.');
}
$res['success'] = true;
echo json_encode($res);
}
elseif ($_POST['action'] == 'save') {
array_push($res['errors'], 'Save button clicked.');
$res['success'] = true;
echo json_encode($res);
}
All the time if i click on publish button i am getting
No data recived by php
When I check in firebug it is showing data under post.
Like this
action publish
data title=test&
I am not sure what am i doing wrong here. Please advise.
Change the AJAX call to use:
data: $('form#posting').serialize() + '&action=' + el,\
Then access the parameter using
$title = $_POST['title'];
The way you're doing it, the form data is being nested a level down in the POST data, so you would have had to do:
$data = parse_str($_POST['data']);
$title = $data['title'];
I want select result Ajax request and Replace it on my input.
result display in result div,I want selected one of them and insert to mobile input and hidden results
<form method="post" action="#" class="form-horizontal" id="adduser">
<div class="form-group"><label class="col-sm-2 control-label">Mobile</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="mobile" id="mobile" autocomplete="off" />
<div id="result"></div></div>
</div>
<input type="submit" name="useradd" id="useradd" class="btn btn-block btn-w-m btn-success" value="add">
</form>
ajax jquery :
<script>
$(document).ready(function(){
var req = null;
$('#mobile').on('keyup', function(){
var mobile = $('#mobile').val();
if (mobile && mobile.length > 2)
{
$('#loading').css('display', 'block');
if (req)
req.abort();
req = $.ajax({
url : 'ajax.php',
type : 'POST',
cache : false,
data : {
mobile : mobile,
},
success : function(data)
{
console.log(data)
if (data)
{
$('#loading').css('display', 'none');
$("#result").html(data).show();
}
}
});
}
else
{
$('#loading').css('display', 'none');
$('#result').css('display', 'none');
}
});
});
</script>
fetch data and return in Ajax.php
if(isset($_POST['mobile'])) {
$user = new User();
$result = $user->Searchuser($_POST['mobile']);
$mobiles= array();
$names = array();
while ($info = $result->fetch(PDO::FETCH_ASSOC)) {
echo $info['firstname'].'-'.$info['mobile'].'<br/>';
}
}
Look this pic :
I want select Dany and insert that to mobile input
I'm getting the following error on Ajax call in Laravel 5:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,
The form is as follows:
<form id="comment_form">
<input type="textarea" class="form-control_comment" id="comment" placeholder="Type your comment here...">
<input type="hidden" name="uid" id="uid" value="{{$user->id}}">
<input type="hidden" name="pid" id="pid" value="{{$post->id}}">
<input type="hidden" id="token" value="{{$csrf_token()}}">
<button type="button" class="btn btn-sm btn-success" id= "comment_button">Submit</button>
</form>
The Ajax part:
<script>
$("#comment_button").click(function(e){
e.preventDefault();
var token = $("#token").val();
var a= $("#comment").val();
var uid= $("#uid").val();
var url = "<?php echo Request::root();?>";
$.ajax({
url: url+"post/comment_action",
type: "POST",
async: false,
data: {newComment:a, uid:uid, pid:pid, _token: token},
success: function (newResult){
if(newResult!="")
{
newResult= JSON.parse(newResult);
$("#all_responses").append(newResult);
}
}
}).error(function()
{
alert("Error");
});
});
</script>
in routes.php:
Route::post('post/comment_action', array('as'=>'post/comment_action', 'uses'=>'PostController#postComment_action'));
And the action part in PostController:
public function postComment_action()
{
if(Auth::check())
{
if(Request::ajax())
{
$inputs= Input::all();
}
$new_comment= $inputs['newComment'];
$uid= $inputs['uid'];
$pid= $inputs['pid'];
$com= new Comment;
$com->content= $new_comment;
$com->userId= $uid;
$com->postId= $pid;
$com->save();
$data= array();
$all_comments= Comment::where('postId', $pid)->first();
$u= User::where('id', $uid);
foreach($all_comments as $coms)
{
$data= $coms->content;
}
$data= json_encode($data);
echo $data;
}
else
{
return Redirect::route('signin_user')->withErrors("You must sign in to perform this action");
}
}
Any help would be greatly appreciated :)