Laravel Controller/Ajax not saving in my database - ajax

It seems like my save(); in my categories does not function as intended below. I will show the necessary codes first:
my table name is hms_bbr_category which is also connectec to my .env locally:
DB_CONNECTION=pgsql
DB_HOST=localhost
DB_PORT=5432
DB_DATABASE=jhs
DB_USERNAME=postgres
DB_PASSWORD=pa55wor0
my model: HmsBbrCategory
class HmsBbrCategory extends Model
{
protected $table = 'hms_bbr_category';
protected $fillable = [
"category_name", "category_description"
];
}
my controller: BBRCategoryConfigurationController
class BBRCategoryConfigurationController extends Controller
{
public function index(){
return view('frontend.bbr-settings.bbr-category-configuration');
}
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'category_name'=>'required|max:191',
'category_description'=>'required|max:191',
]);
if($validator->fails())
{
return response()->json([
'status'=>400,
'errors'=>$validator->messages(),
]);
}
else {
$category = new HmsBbrCategory;
$category->category_name = $request->input('category_name');
$category->category_description = $request->input('category_description');
$category->save();
return response()->json([
'status'=>200,
'message'=>'Category Added!',
]);
}
}
The ajax and modal fields
<div class="form-group">
<input type="text" class="form-control form-group w-100 category_name" placeholder="Category Name">
</div>
<div class="form-group">
<textarea class="form-control w-100 category_description" placeholder="Category Description" cols="50" rows="10"></textarea>
</div>
<script>
$(document).ready(function (){
$(document).on('click', '.add_category', function(e){
e.preventDefault();
var category_data = {
'category_name': $('.category_name').val(),
'category_description': $('.category_description').val(),
}
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(category_data);
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: "category_data",
dataType: "json",
success: function (response){
// console.log(response);
if(response.status == 400)
{
$('#saveform_errList').html("");
$('#saveform_errList').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#saveform_errList').append('<li>'+err_values+'</li>');
});
}
else
{
$('#saveform_errList').html("");
$('#success_message').addClass('alert alert-success');
$('#success_message').text(response.message);
$.('#createCategory').modal('hide');
$.('#createCategory').find('input').val("");
console.log(category_data);
}
}
});
});
});
</script>
my routes at web.php
Route::get('/bbr-category-configuration', [BBRCategoryConfigurationController::class,'index']);
Route::post('/bbr-category-configuration', [BBRCategoryConfigurationController::class,'store']);
Things to note:
my hunch is that my store function does not connect properly at $category = new HmsBbrCategory; However I have checked that my table name and the fields taken are the same, as seen at $category->category_name = $request->input('category_name');
I have also tested in ajax with the values by simply adding console.log(response) as seen in the screenshot, I cannot get past my validator to get to the save(). I am not sure how but There should not be an error since my text fields are filled.
I can elaborate more if needed, I am asking what can I change to fix my validation/save. thanks for any help.

As the error shows, The validation is failing (empty value i guess) and returning the code you programmed (400).
i'm guessing it is because you are using a string instead of the variable at the attribute data: "category_data",
update the code to send the variable instead
$.ajax({
type: "POST",
url: "/clinical/bbr-category-configuration",
data: category_data, //change here
dataType: "json",
success: function (response){
//...

Related

Laravel: Ajax update to database

i just want to update my data via ajax i am getting error.
Error Console:
POST http://abc.local/teachers/users/1 404 (Not Found)
here is my controller:
public function policyupdate(Request $request, $id)
{
$user = DB::table('users')->find($id);
$user->update($request->all());
return response()->json([
'status' => 'success',
'msg' => 'has been updated'
]);
}
web.php:
Route::post('users/{user}','TeachersController#policyupdate') ;
js:
jQuery(document).ready(function(e) {
alert(1);
$('#update-policy').on('click', function(e) {
console.log('Update policy clicked!')
e.preventDefault(e);
$.ajax({
type: "POST",
url: "users/" + $('#update-policy').attr("value"),
data: $(this).serialize(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
alert(updated);
},
});
});
});
I only notice a couple of issues.
url: "users/" + $('#update-policy').attr("value"),
In the url of the ajax call you don't have a slash at the beginning, so the url will be relative to the url of the page where the function is located, instead of the base url. to solve it just add that slash at the beginning
url: "/users/" + $('#update-policy').attr("value"),
The other one is that you have an input with the put method,
<input type="hidden" name="_method" value="put" />
so the Laravel route should be put (it makes sense if it takes into account that it is a route to update)
Route::put('users/{user}','TeachersController#policyupdate') ;
Well, and as you yourself discovered, with query builder, the update() method works if you query with where() instead of find()
$user = DB::table('users')->where('id', $id)->update( $request->all() );

Post 403 forbidden on Yii2 Ajax Call

I know there's other topic on this in stackoverflow but it still didn't work for me. I try to make a simple dynamic menu that generate dynamic content based on the chosen <li> id.
This is the code to generate the menu :
foreach($cabang as $index=>$model){
echo '<li id='.$model->idDpd->id_dpd.'>
<a class="nav-link" href="#" role="tab" data-toggle="tab">'.$model->idDpd->dpd.'</a>
</li>';
}
The menu is created successfully. But I have the problem with the content generated with Ajax
This is what I have in my view file :
$script = <<< JS
$(document).ready(function(){
function load_page_details(id)
{
$.ajax({
url: "<?=Url::to(['/site/fetch']) ?>",
method:"POST",
data:{id:id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success:function(data)
{
$('#page_details').html(data);
}
});
}
//load page-details where the id in the database table equals 1. Set the default to 1 while page is loading for the first time.
/* load_page_details(1);*/
$('.nav li').click(function(){
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script)
?>
This is my SiteController and the action :
public function actionFetch(){
if (Yii::$app->request->isAjax) {
// fetch the $_POST["id"]
$data = Yii::$app->request->post('id');
if(isset($data))
{
$query= Cabang::find()->where(['id_dpd'=> $data])
->joinWith('idDpd')
->all();
$output = '';
foreach($query as $model)
{
$output .= '
<div role="tabpanel" class="col-lg-4 tab-pane fade show active" >
<div class="col-md-12">
<h4>'.$model->kota.'</h4>
<p>'.$model->alamat.'</p>
<p>'.$model->telp.'</p>
<p>'.$model->email.'</p>
<p>'.$model->jadwal.'</p>
</div>
</div>
';
}
/* echo $output;*/
// return Json
return \yii\helpers\Json::encode($output);
}
}
}
The error caught in my console in chorome dev tool : jquery.js:9175 POST http://localhost/%3C?=Url::to([%27/site/fetch%27])%20?%3E 403 (Forbidden)
I tried to make the fetch function to a new php file and link the URL in my Ajax to that file (not to a controller or SiteController in my case) like : url: url:"site/fetch.php",but it returned jquery.js:9175 POST http://localhost/site/fetch.php 404 (Not Found)
What am I doing wrong? I have spent two days without solution. Thanks for the help!
Your PHP is not correct - you cannot use <?= /* ... */ ?> inside of heredoc. You need to use temporary variable:
$url = Url::to(['/site/fetch']);
$script = <<<JS
$(document).ready(function () {
function load_page_details(id) {
$.ajax({
url: "$url",
method: "POST",
data: {id: id}, //pass the 'id' of Load_page_details function parameter to the targeted URL
success: function (data) {
$('#page_details').html(data);
}
});
}
$('.nav li').click(function () {
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
JS;
$this->registerJs($script);

How to get a value from ajax call in laravel

I want to get a value from the ajax call in controller function. How can i do it?
My code is here:
<i class="fa fa-pencil-square-o"></i>
My script:
<script>
function amount_pay(id)
{
$.ajax({
type: 'POST',
url: 'amount_popup/'+ id,// calling the file with id
success: function (data) {
alert(1);
}
});
}
</script>
My route:
Route::post('amount_popup/{id}', 'AdminController\AmountController#amount_to_pay');
my controller function:
public function amount_to_pay($id)
{
echo $id;
}
easly return the value:
public function amount_to_pay($id)
{
return $id;
}
Use
var url = '{{ route('amount_popup', ['id' => #id]) }}';
url = url.replace('#id', id);
instead of
'amount_popup/'+ id
You are trying to get the value from a GET request, but you are sending the form as a POST request.
You should change your script code to:
<script>
function amount_pay(id)
{
$.ajax({
type: 'GET', //THIS NEEDS TO BE GET
url: 'amount_popup/'+ id,// calling the file with id
success: function (data) {
alert(1);
}
});
}
</script>
THEN CHANGE YOUR ROUTE TO:
Route::get('amount_popup/{id}', 'AdminController\AmountController#amount_to_pay');
OR IF YOU WANT TO USE POST... DO THIS...
<script>
function amount_pay(id)
{
$.ajax({
type: 'POST',
url: 'amount_popup',
data: "id=" + id + "&_token={{ csrf_token() }}", //laravel checks for the CSRF token in post requests
success: function (data) {
alert(1);
}
});
}
</script>
THEN YOUR ROUTE:
Route::post('/amount_popup', 'AdminController\AmountController#amount_to_pay');
THEN YOUR CONTROLLER:
public function amount_to_pay(Request $request)
{
return $request->input('id');
}
For more info:
Laravel 5 Routing

Symfony ajax form need reload page to show results

I have a product page where users can write comments, this works fine but i would like to implement ajax form with no page refresh.
The code call ajax and persist, but need press f5 to show new comment.
what am I doing wrong?
Thanks, and sorry for my english.
In product view, render a controller that call the form:
<div class="comments">
{{ render(controller('AppBundle:Comment:newComment',{'media': selected.id})) }}
</div>
Controller:
class CommentController extends Controller
{
/**
* #Route("/media/{media}/", name="create_comment", options={"expose"=true})
* #Method("POST")
* #ParamConverter("media", class="AppBundle:Media")
*/
public function newCommentAction(Request $request, $media)
{
$comment = new Comment();
$form = $this->createForm(CommentType::class, $comment);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$data = $form->getData();
$data->setUser($this->getUser());
$data->setMedia($media);
$em = $this->getDoctrine()->getManager();
$em->persist($data);
$em->flush();
return new JsonResponse('Success!');
}
return $this->render('comment/newComment.html.twig', array(
'media' => $media,
'form' => $form->createView()
));
}
}
newComment.html.twig
<form method="POST" id="commentForm" action="{{path('create_comment', {'media': media.id})}}">
{{ form_row(form.comment) }}
<button type="submit" id="submitButton" class="btn btn-xs btn-danger">{{ 'btn.send' |trans }}</button>
app.js
$('body').on('click','#submitButton', function(e){
e.preventDefault();
var $form = $('#commentForm');
$.ajax({
type: "POST",
dataType: "json",
url: 'http://demo/app_dev.php/media/16/',
data: $form.serialize(),
cache: false,
success: function(response){
$(".ajaxResponse").html(response);
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
This should work for you to reload the element with class="comments" after your POST:
$('#submitButton').on('click', function (e) {
e.preventDefault();
var $form = $('#commentForm');
$.ajax({
type: "POST",
dataType: "json",
url: 'http://demo/app_dev.php/media/16/',
data: $form.serialize(),
cache: false,
success: function (response) {
$('.comments').load(window.location + ' .comments > *');
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
Edit:
As far as your second question regarding $request->isXmlHttpRequest() -- this method just looks for the X-Requested-With header with value of XMLHttpRequest. Are you testing for it on the first request or on the second request or on both requests? Can you take a look in Firebug or Chrome Tools and see if the header is on both requests?

Refresh page in symfony2 at the end of Ajax call

How can I refresh a page after an ajax call is executed.
My Ajax call is
$.ajax({
type: "POST",
data: data,
url:"{{ path('v2_pm_patents_trashpatents') }}",
cache: false
});
The method that is executed by this ajax is
public function trashpatentAction(Request $request){
if ($request->isXmlHttpRequest()) {
$patent_id = $request->get("pid");
$em = $this->getDoctrine()->getEntityManager();
$patent = $em->getRepository('MunichInnovationGroupPatentBundle:SvPatents')->find($patent_id);
if (!$patent) {
throw $this->createNotFoundException('No patent found for id '.$patent_id);
}
$patent->setIs_deleted(1);
$em->flush();
}
}
Edit
Portfolio Controller Index Action
public function indexAction(Request $request) {
$switch_form = $this->createForm(new SwitchPortfolioType($portfolios));
////rest of action code
return $this->render('MunichInnovationGroupPatentBundle:Portfolio:index.html.twig', array('new_patentgroup_form' => $new_patentgroup_form->createView(),'switch_form' => $switch_form->createView(), 'new_form' => $new_form->createView(), "portfolios" => $portfolios ,"selected_portfolio" => $selected_portfolio,"portfolio_groups" => $portfolio_groups,"patents" => $patents));
}
Index.html.twig
<form name="portfolios" action="{{ path('v2_pm_portfolio') }}" method="post" >
{{ form_widget(switch_form) }}
<input type="submit"class="portfolio_input button2 tooltip" value="Switch">
</form>
SwitchPortfolioType
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class SwitchPortfolioType extends AbstractType
{
public function __construct($portfolios)
{
$this->portfolios = $portfolios;
}
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('', 'choice', array(
'choices' => array(
'test' => 'Test'
),
'empty_value' => 'Switch your Portfolio',
));
}
public function getName()
{
return 'switch_portfolio';
}
}
At the end of this action I want to refresh the page
How can I do this?
The refresh will have to be done in javascript. I am not sure why you would POST via ajax only to reload the page anyway, why not just POST normally?
Anyway, to do what you ask I would return some simple JSON response in the controller to signify a success and then in the ajax callback do this:
$.ajax({
type: "POST",
data: data,
url:"{{ path('v2_pm_patents_trashpatents') }}",
cache: false,
success: function(data) {
// optionally check if the response is what you wanted
//if (data.response == 'deleted') {
document.location.reload(true);
//}
}
});
Using jQUery:
$('your_form').disable=true;
Pure JS:
your_form.disabled = true;

Resources