Sory my english is not good, I have a problem with comment input form in my program. the comment field in the process will only succeed if the filled column is the top column. if the comment field other than the above will fail. please enlighten him
this is a successfull process in first column comment
but if I write in the comment field other than the above will fail
token and field with_id same as comment column above, whereas value from barengan_id if in inspect element differ its contents. and also comment field so empty value
and this is my code
my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Barengan;
use App\BarenganComment;
use App\User;
class CariBarenganCommentController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request,Barengan $id)
{
$data = [
'user_id' => auth()->id(),
'barengan_id' => $id->id,
'comment' => $request['comment'],
];
return BarenganComment::create($data);
}
public function destroy(Barengan $barengan_id,$id)
{
BarenganComment::destroy($id);
}
}
And this my form in view
<div id="form">
<form method="post" data-toogle="validator" class="form-horzontal">
{{ csrf_field() }}
{{method_field ('POST')}}
<input type="hidden" name="id" id="id">
<input type="hidden" name="barengan_id" value="{{$d->id}}" id="barengan_id">
<div class="styled-input">
<input class="input inputkoment" type="text" placeholder="Tulis Komentar ..." name="comment" id="comment">
<span></span>
<button type="submit" class="btn btn-default pull-right btn-custom-komen"><i class="fa fa-chevron-circle-right"></i></button>
</div>
</form>
</div>
<script src="{{asset('js/jquery-1-11-0.js')}}"></script>
<script>
function deleteComment(id) {
var popup = confirm("apakah anda yakin akan menghapus data?");
var csrf_token = $('meta[name="csrf-token"]').attr('content');
if(popup == true){
$.ajax({
url: "{{ url('caribarengancomment')}}/"+id,
type: "POST",
data: {'_method': 'DELETE','_token': csrf_token
},
success: function(data) {
$("#contact-table").load(" #contact-table");
$('#alert-success').html('show');
},
error: function () {
alert("Opppps gagal");
}
})
}
}
$(function () {
$(document).on('submit','#form form',function (e) {
if (!e.isDefaultPrevented()) {
var barenganId = $('#barengan_id').val();
console.log(barenganId);
url = "{{ url('caribarengan')}}/" + barenganId + "/comment";
// url= '{{route('caribarengancomment.store',$d)}}';
$.ajax({
url: url,
type: "POST",
data: $('#form form').serialize(),
success: function(data) {
$("#contact-table").load(" #contact-table");
$('#alert-success').html('show');
},
error: function () {
alert('Oops! error!');
}
});
return false;
}
});
});
</script>
and my model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BarenganComment extends Model
{
protected $fillable = ['user_id','barengan_id','comment'];
public function user()
{
return $this->belongsTo(User::class);
}
public function barengan()
{
return $this->belongsTo(Barengan::class);
}
}
I am very tired these days stack here :(
you use multiple forms on page? look like id`s of inputs conflict.
try this way
<form method="post" data-toogle="validator" class="form-horzontal" data-barengan="{{$d->id}}">
...
if (!e.isDefaultPrevented()) {
var barenganId = $(this).data('barengan');
Related
I want to list down the users according to the user_types while inserting so I created the two tables and each table has connections. Each model PHP file has a relationship function. and I created the jquery code and I created the controller function but it's not working I don't know where I making the mistake please help me to fix this problem. I attached all code I have written and the database also.
User Type Database
User Database Table
UserType Id and User Table usty_id has connections
UserType Model
<?php
namespace Asset_Management_System;
use Illuminate\Database\Eloquent\Model;
class UserType extends Model
{
public function userpermission()
{
return $this->hasMany('Asset_Management_System\UserPermission');
}
public function user()
{
return $this->hasMany('Asset_Management_System\User');
}
}
User Model
class User extends Authenticatable
{
public function usertype()
{
return $this->belongsTo('Asset_Management_System\UserType','usty_id');
}
}
Insert Form
<div class="form-group">
<label>User Type</label>
<select class="form-control select2" style="width: 100%;" id="ust_id" name="ust_id">
<option selected="selected">Select User Type</option>
#foreach($UserType as $ust)
<option value="{{$ust->id}}">{{$ust->usty_name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>User</label>
<select class="form-control select2" style="width: 100%;" id="user_id" name="user_id">
<option selected="selected">Select User</option>
#foreach($User as $us)
<option value="{{$us->id}}">{{$us->us_fname}} {{$us->us_lname}}</option>
#endforeach
</select>
</div>
Controller
public function show(Request $request)
{
//echo $id;
if (!$request->usty_id) {
$html = '<option value="">'.trans('global.pleaseSelect').'</option>';
} else {
$html = '';
$user = User::where('usty_id', $request->usty_id)->get();
foreach ($user as $us) {
$html .= '<option value="'.$us->id.'">'.$us->us_fname.' '.$us->us_lname.'</option>';
}
}
return response()->json(['html' => $html]);
}
And Jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$("#ust_id").change(function(){
$.ajax({
url: "{{ route('WorkRequest.show') }}?usty_id=" + $(this).val(),
method: 'GET',
success: function(data) {
$('#user_id').html(data.html);
}
});
});
</script>
Route
Route::get('WorkRequest/show', 'WorkRequestController#show')->name('WorkRequest/show');
And this is the error I'm getting when I go to the form
Missing required parameters for [Route: WorkRequest.show] [URI: WorkRequest/{WorkRequest}]. (View: C:\xampp\htdocs\Asset_Management_Laravel\resources\views\layouts\main.blade.php)
Please Help me to solve this issues
This Code is working perfectly
<script type="text/javascript">
$(document).ready(function(){
// Department Change
$('#ust_id').change(function(){
// Department id
var id = $(this).val();
// Empty the dropdown
$('#user_id').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: "{{ route('WorkRequest/show') }}?usty_id=" + id,
type: 'get',
dataType: 'json',
success: function(response){
//alert(response);
$('#user_id').html(response.html);
}
});
});
});
</script>
public function show(Request $request)
{
//echo $id;
$html = '';
$user = User::where('usty_id', $request->usty_id)->get();
foreach ($user as $us)
{
$html .= '<option value="'.$us->id.'">'.$us->us_fname.' '.$us->us_lname.'</option>';
}
return response()->json(['html' => $html]);
}
Replace above Route with this-Route::post('workRequest/get_options','WorkRequestController#getOptions')->name('workRequest.options'); and place above the route::resource() route
And ajax code as below
$("#ust_id").change(function(){
let parameter = {'usty_id': $(this).val()};
$.ajax({
url: "{{ route('workRequest.options') }}",
method: 'POST',
data: parameter,
success: function(data) {
$('#user_id').html(data.html);
}
});
});
Add this Controller method to get options
public function getOptions(Request $request)
{
if (!$request->usty_id) {
$html = '<option value="">'.trans('global.pleaseSelect').'</option>';
} else {
$html = '';
$user = User::where('usty_id', $request->usty_id)->get();
foreach ($user as $us) {
$html .= '<option value="'.$us->id.'">'.$us->us_fname.' '.$us->us_lname.'</option>';
}
}
return response()->json(['html' => $html]);
}
I am trying to favorite and unfavorite posts and insert it in favorites table if clicked and if clicked again it deletes it from favorites table i put my routes in web.php file
the functions in the controller which should be called in the route are not called i insert there dd() method to test it so i am guessing the problem is in the form action and not sending the data
<body>
...
#foreach ($posts as $post)
<div class="column">
#if ($post->showstar == true)
<form action="/favorites/delete" method="post">
<span class="foo fa fa-star checked"></span>
</form>
#endif
<h2>{{$post->title}}</h2>
<img src={{$post->url}} >
</div>
#endforeach
</body>
<script>
$(document).ready(function () {
$("form").on("click", ".foo", function () {
if ($(this).hasClass("checked")) {
$(this).removeClass("checked");
} else {
$(this).addClass("checked");
}
});
});
</script>
Controller:
class FavoritesController extends Controller
{
public function index()
{
return view('Favorites', ['favs' => Favorite::where('user_id', '1')->get()]);
}
public function view(Request $request)
{
dd("hello");
$fav = new Favorite();
$fav->user_id = $request->get('userid');
$fav->post_id = $request->get('postid');
$fav->save();
}
public function delete(Request $request)
{
dd("bye");
$fav = new Favorite();
$dfav = $fav->where('id', $request->id);
$dfav->delete();
return view('favorites');
}
public function fetch(Request $request)
{
$fav = new Favorite();
$favs = $fav->where('user_id', $request->user_id);
return view('favorites', compact('favs'));
}
}
Routes:
Route::post('/favorites', 'FavoritesController#view');
Route::post('/favorites/delete', 'FavoritesController#delete');
Route::post('/favorites/fetch', 'FavoritesController#fetch');
You could always try the plain and simple html form submit.
<form action="/favorites/delete" method="post">
#csrf
<input type="hidden" name="id" value="{{ $post->id }}">
<button>
<span class="foo fa fa-star checked"></span>
</button>
</form>
This way you can send the hidden input, post id in your case, to the controller and it will delete it.
You need a similar function ajax, to send data to a controller:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:'youUrl',
data:{'youData':"YourValueData"},
type:'post',
success: function (response) {
alert(response);
},
error: function(x,xs,xt){
alert(x);
}
});
How do I take value from one textarea to another with laravel and jquery ajax.
I have this files so far.
Route:
Route::post('/post', 'PostController#post');
Controller:
class PostController extends Controller
{
public function post(Request $request)
{
$request->json()->all();
}
}
JQuery file:
$(function(){
$('#insert').on('click', function(e){
e.preventDefault();
var intrare = $('textarea#firsttextarea').val();
$.ajax({
type:'POST',
url: '/post',
data: {intrare: intrare},
success: function(data){
$('textarea#secondtextarea').val(data);
}
});
});
});
and the html :
<textarea class="form-control" name="firsttextarea" rows="10" id="firsttextarea" ></textarea>
<button id="insert" class="btn btn-md btn-primary"><span class="glyphicon glyphicon-circle-arrow-right"></span>Insert</button>
<textarea class="form-control" name="secondtextarea" rows="10" id="secondtextarea" ></textarea>
When i push the button nothing happens.
First problem probably can be in CSRF Verify. You can disable it if it so or add {{ csrf_token() }}.
Then your post action should be looks like this:
public function post(Request $request)
{
return response()->json($request->all());
}
I checked it and it's work fine. but in textarea insert [Object object] because it JSON. You can add JSON.stringify in your Jquery script like this:
$(function(){
$('#insert').on('click', function(e){
e.preventDefault();
var intrare = $('textarea#firsttextarea').val();
$.ajax({
type:'POST',
url: '/post',
data: {intrare: intrare},
success: function(data){
$('textarea#secondtextarea').val(JSON.stringify(data));
}
});
});
});
Try this, you're not returning a response in your Controller method.
class PostController extends Controller
{
public function post(Request $request)
{
return response()->json([
'data' => $request->get('intrare'),
]);
}
}
then, add this to your head in your blade file
<meta name="csrf-token" content="{{ csrf_token() }}">
and replace your JS with the below:
$(function() {
// We need CSRF Token in our ajax request so we can
// validate the POST request
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
}
});
// Insert text from first textarea to the other textarea
$("#insert").on("click", function(e) {
e.preventDefault();
var intrare = $("textarea#firsttextarea").val();
$.ajax({
type: "POST",
url: "/post",
data: { intrare: intrare },
success: function(response) {
$("textarea#secondtextarea").val(response.data);
}
});
});
});
i want to use this code buy it stays in Procesando, espere por favor....
Jquery:
function realizaProceso(valorCaja1, valorCaja2){
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2
};
$.ajax({
data: parametros,
url: 'ajax/pregunta',
type: 'POST',
beforeSend: function () {
$("#resultado").html("Procesando, espere por favor...");
},
success: function (data) {
$("#resultado").html(data.resultado)
}
});
Html
Introduce valor 1
<input type="text" name="caja_texto" id="valor1" value="0"/>
Introduce valor 2
<input type="text" name="caja_texto" id="valor2" value="0"/>
Realiza suma
<input type="button" href="javascript:;" onclick="realizaProceso($('#valor1').val(), $('#valor2').val());return false;" value="Calcula"/>
<br/>
Resultado: <span id="resultado">0</span>
Route
Route::post('ajax/pregunta', [
'as' => 'ajax/pregunta', 'uses' => 'AjaxController#pregunta'
]);
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\Request;
use Illuminate\Support\Facades\Response;
class AjaxController extends Controller {
public function __construct()
{
$this->middleware('auth');
}
public function pregunta(){
$resultado = Request::input('valorCaja1') + Request::input('valorCaja2');
return response()->json(['resultado' => 'Roberto']);
}
}
When i clic in "Calcula" button " Procesando, espere por favor..." apears in the screen but it dont load the succes code, any solution??
Thanks!!
I think that you need provide a token , i'm not sure but i believe that is necesary
in your page blabla.blade.php add
<input type="hidden" name="_token" id="_token" value="{{{ csrf_token() }}}" />
and then in your ajax call
var tok = $('#_token').val();
var parametros = {
"valorCaja1" : valorCaja1,
"valorCaja2" : valorCaja2,
"_token" = tok
};
regards...
CodeIgniter Ajax is not working for me.
This is what I have tried so far.
v_login.php
<script type="application/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var form_data = {
username : $('#username').val(),
password : $('#password').val(),
ajax : '1'
};
$.ajax({
url: "<?php echo site_url('c_login/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
<div class="container">
<div class="jumbotron">
<?php
$attributes = array('class' => 'form-signin');
echo form_open('c_login', $attributes); ?>
<h2 class="form-signin-heading">VMS Login System</h2>
<input type="username" name="username" id="username" class="form-control" placeholder="Username" required autofocus>
<input type="password" name="password" class="form-control" placeholder="Password" required>
<input class="btn btn-primary" type="submit" id="submit" value="Login">
<input class="btn btn-primary" type="reset" value="Cancel">
<?php echo form_close(); ?>
<div id="message">
</div>
</div>
</div>
C_login.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_login extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('url');
}
function index() {
$this->load->view('include/header');
$this->load->view('v_login');
$this->load->view('include/footer');
}
function ajax_check() {
if($this->input->post('ajax') == '1') {
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'),$this->input->post('password'));
if($user == '1') {
echo 'login successful';
} else {
echo 'unknown user';
}
}
}
}
}
/* End of file c_login.php */
/* Location: ./application/controllers/c_login.php */
m_access.php
<?
class M_access extends CI_Model {
public function check_user($username,$password) {
$this->query = $this->db->select('COUNT(*)')->from('users')->where(array('username'=>$username,'password'=>$password))->limit(1)->get();
return $this->query->row_array();
}
}
I don't know what's wrong, I have already set up config.php and routes. But it's not working at all. Any ideas? Help is much appreciated. Thanks.
After a long chat with OP the solution is this
Your model
class M_access extends CI_Model {
public function check_user($username,$password) {
$args = array(
'username' => $username,
'password' => $password
);
$query = $this->db->select('*')->from('users')->where($args)->get();
if($query->num_rows()) {
return $query->row_array();
}
return false;
}
}
In your controller, use
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'), $this->input->post('password'));
if($user) {
// right user
}
else {
// wrong user
}
Don't need to send ajax:1 because jQuery sends a request header to server, like this
X-Requested-With': 'XMLHttpRequest'
and in CodeIgniter you may check for ajax request using
if($this->input->is_ajax_request()){
// it's an ajax request
}
Also, you asked for a gif loader to shw, so this could be used as
$('#submit').click(function() {
var form_data = { ...};
// show the gif loader
$.ajax({
...
data: form_data,
success: function(msg) {
// hide the gif loeader
$('#message').html(msg);
}
});
});
Update : For inserting an image you may check this fiddle example, like
$('#submit').click(function(e){
e.preventDefault();
var loader = $('<img/>', {
'src':'url_of_the_image',
'id':'ajax_loader'
});
loader.insertAfter($(this));
});
and to remove the image in your success callback, you may use
$('#ajax_loader').remove();
error 404 due to the calling path because file name with "C" and you calling it with "c", rather than that
in my opinion you need to have a deeper look at codeigniter form validation helper
before you try the ajax call
once you did it server side perfectly & if you still want to validate using ajax , make another function as a webservice only for this purpose along the orignal server side validation function , it'd be something like that
function ajax_check(){
$username_check=true;
//your code goes here to check if username unique or not and result assigned to $username_check
if(!$username_check){
echo json_encode('fail');
return;
}
echo json_encode('success');
}