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 :)
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 a begineer of laravel and ajax i can do the system well in core php. i just converted to laravel.
i creating simple crud using laravel with ajax but i don't know how call the path through ajax request. what i tried so fat i attached below.pls give me the solution for it.
Screen shot of folder structure
this is view part. i name it
list.blade.php
div class="row">
<div class="col-sm-4">
<form class="card" id="frmProject">
<div class="form-group" align="left">
<label class="form-label">First name</label>
<input type="text" class="form-control" placeholder="first_name" id="first_name" name="first_name" size="30px" required>
</div>
<div class="form-group" align="left">
<label class="form-label">Last name</label>
<input type="text" class="form-control" placeholder="last_name" id="last_name" name="last_name" size="30px" required>
</div>
<div class="form-group" align="left">
<label class="form-label">Address</label>
<input type="text" class="form-control" placeholder="Address" id="address" name="address" size="30px" required>
</div>
<div class="card" align="right">
<button type="button" id="save" class="btn btn-info" onclick="addProject()">Add</button>
</div>
</form>
</div>
Ajax Call
function addProject() {
if ($("#frmProject").valid())
{
var _url = '';
var _data = '';
var _method;
if (isNew == true) {
_url = '/student';
_data = $('#frmProject').serialize();
_method = 'POST';
}
else {
_url = '/student',
_data = $('#frmProject').serialize() + "&project_id=" + project_id;
_method = 'POST';
alert(project_id);
}
$.ajax({
type: _method,
url: _url,
dataType: 'JSON',
data: _data,
beforeSend: function () {
$('#save').prop('disabled', true);
$('#save').html('');
$('#save').append('<i class="fa fa-spinner fa-spin fa-1x fa-fw"></i>Saving</i>');
},
success: function (data) {
$('#frmProject')[0].reset();
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Add');
get_all();
var msg;
console.log(data);
if (isNew)
{
msg="Brand Created";
}
else{
msg="Brand Updated";
}
$.alert({
title: 'Success!',
content: msg,
type: 'green',
boxWidth: '400px',
theme: 'light',
useBootstrap: false,
autoClose: 'ok|2000'
});
isNew = true;
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr.responseText);
$.alert({
title: 'Fail!',
content: xhr.responseJSON.errors.product_code + '<br>' + xhr.responseJSON.msg,
type: 'red',
autoClose: 'ok|2000'
});
$('#save').prop('disabled', false);
$('#save').html('');
$('#save').append('Save');
}
});
}
}
Student Controller
class StudentController extends Controller
{
public function index()
{
$data['students'] = Student::orderBy('id','desc')->paginate(5);
return view('student.list',$data);
}
public function create()
{
}
public function store(Request $request)
{
$student = new Student([
'first_name' => $request->post('first_name'),
'last_name'=> $request->post('lastname'),
'address'=> $request->post('address')
]);
]);
$student->save();
return Response::json($student);
}
routes
Route::get('/', [App\Http\Controllers\StudentController::class, 'index']);
Route::get('student', [App\Http\Controllers\StudentController::class, 'index']);
Route::post('student', [App\Http\Controllers\StudentController::class, 'store'])->name('student.store');
$(document).ready(function() {
$(".btn-submit").click(function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var email = $("#email").val();
var pswd = $("#pwd").val();
var address = $("#address").val();
$.ajax({
url: "url",
type:'POST',
data: {_token:_token, email:email, pswd:pswd,address:address},
success: function(data) {
printMsg(data);
}
});
});
function printMsg (msg) {
if($.isEmptyObject(msg.error)){
console.log(msg.success);
$('.alert-block').css('display','block').append('<strong>'+msg.success+'</strong>');
}else{
$.each( msg.error, function( key, value ) {
$('.'+key+'_err').text(value);
});
}
}
});
Please use csrf token
I have modified my question. How can I get the result from second form? because I have create two form with similar code, however I can only get the result from the first form and when I press the second one, it still get the result from first form. Can someone help me out?
Code
<div>
<form id="fupForm" name="form1" method="post">
<div class="form-group">
<input type="hidden" class="form-control" id="gp_name" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control" id="date" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control" id="type" name="type"
value="Hotel">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Hotel" id="butsave">
</form></div>
<div>
<form id="fupForm2" name="form2" method="post">
<div class="form-group">
<input type="hidden" class="form-control" id="gp_name" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control" id="date" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control" id="type" name="type"
value="Coach">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Coach" id="butsave2">
</form></div>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
$("#butsave").attr("disabled", "disabled");
var gp_name = $('#gp_name').val();
var date = $('#date').val();
var type = $('#type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
<script>
$(document).ready(function() {
$('#butsave2').on('click', function() {
$("#butsave2").attr("disabled", "disabled");
var gp_name = $('#gp_name').val();
var date = $('#date').val();
var type = $('#type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave2").removeAttr("disabled");
$('#fupForm2').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
I have try to find on the Google, but can't find the solution for my case.
Add form id before the input element.
Remember ids are always unique and can not be duplicate. So here I change id to class. Please check below code.
<div>
<form id="fupForm" name="form1" method="post">
<div class="form-group">
<input type="hidden" class="form-control gp_name" id="" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control date" id="" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control type" id="" name="type"
value="Hotel">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Hotel" id="butsave">
</form></div>
<div>
<form id="fupForm2" name="form2" method="post">
<div class="form-group">
<input type="hidden" class="form-control gp_name" id="" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control date" id="" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control type" id="" name="type"
value="Coach">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Coach" id="butsave2">
</form></div>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
$("#butsave").attr("disabled", "disabled");
var gp_name = $('#fupForm .gp_name').val();
var date = $('#fupForm .date').val();
var type = $('#fupForm .type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
<script>
$(document).ready(function() {
$('#butsave2').on('click', function() {
$("#butsave2").attr("disabled", "disabled");
var gp_name = $('#fupForm2 .gp_name').val();
var date = $('#fupForm2 .date').val();
var type = $('#fupForm2 .type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave2").removeAttr("disabled");
$('#fupForm2').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
An id must be unique in a document. Use a validator.
You get the same data each time, because you are searching using an id selector and error recovery means that you will always get the first one.
Don't use IDs
Do use selectors relative to the form you are dealing with
For example:
$("form").on("submit", function(event) {
event.preventDefault();
const $form = $(this);
const $input = $form.find("[name=type]");
console.log($input.val());
});
form {
padding: 1em
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type=hidden name=type value=foo>
<button>Submit</button>
</form>
<form>
<input type=hidden name=type value=bar>
<button>Submit</button>
</form>
The function $( document ).ready( function() {} ) and $( function() {} ) are equal. This will overwrite the previous variant. If you merge the code, it should work.
my ajax call worked at first time but on second time its not work and it return something like ..The action you have requested is not allowed.
in header of console the Status Code is 403 Forbidden
Controller method as below..
public function authenticate() {
echo json_encode('sachin');
}
jQuery function
$("#adminFrmSubmitBtn").on('click',function(){
if($("#admin_login_frm").valid()){
var frmData=$(this).closest('form').serialize();
frmData+='&'+$.param({'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'});
$.ajax({
url:'<?php echo base_url('login/authenticate12'); ?>',//$(this).closest('form').attr('action'),
method:$(this).closest('form').attr('method'),
data:frmData,
success:function(response){
console.log(response);
}
});
}else{
return false;
}
});
Html Code
<form action="<?php echo base_url('login/authenticate'); ?>" method="post" name="admin_login_frm" id="admin_login_frm">
<input type="text" name="user_name" class="form-control" placeholder="Email">
<input type="password" name="user_password" class="form-control" placeholder="Password">
<button type="button" class="btn btn-primary btn-block btn-flat" >
</form>
To get fresh CSRF token. we have to get cookie using Javascript because Codeigniter is storing CSRF token in the cookie.
Put below code in your view(.php) file.
<script type="text/javascript">
function get_cookie(cname) { //using this function we can get cookie
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
$.ajax({
type: "POST",
url: "YOUR-URL",
data: {"<?php echo $this->security->get_csrf_token_name(); ?>":csrf_token}, //Add your data which you want to post
dataType: "json",
success: function(resp){
},
error: function(jqXHR, textStatus, errorThrown){
alert('Something is wrong');
window.location.reload();
}
});
</script>
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