Pass json from ajax to laravel controller - json

would you like to help me? I have an ajax like this
var id = {{#$projectid}};
var datatab = JSON.stringify({data: change})
$.ajax({
url: 'save/'+id,
type: 'POST',
dataType: 'JSON',
data: {json:datatab},
success: function(response, textStatus, jqXHR) {
});
and then, I want to pass the datatab as json to database in json field
this is my save function in controller
public function save($project_id=0, Request $request)
{
$project_id = $request->project_id;
$weight = $request->weight;
TaskPlanning::create([
'project_id' => $project_id,
'weight' => $weight
]);
return response()->json([]);
}
In database, weight field is json. and I want to save my json file from ajax to weight
This is my model
class TaskPlanning extends Model
{
protected $table = 'p_task_planning';
protected $fillable = ['project_id','weight'];
public function project()
{
return $this->belongsTo(Project::class,'project_id','id');
}
public function milestone()
{
return $this->belongsTo(Milestone::class,'milestone_id','id');
}
protected $casts = [
'weight' => 'array'
];
}

Try this,
var id = {{#$projectid}};
var datatab = JSON.stringify({data: 'change'});
$.ajax({
url: 'save/'+id,
type: 'POST',
dataType: 'JSON',
data: {_token : '{!! csrf_token() !!}',
weight : datatab,
project_id : id
},
success: function(response, textStatus, jqXHR) {
});

use axios instead of $.ajax..
just make sure you add meta tag
<meta name="csrf-token" content="{{ csrf_token() }}" >
then
use axios like this..it will auto load csrf token
axios.post('save/'+id, data).then(function (response) {
//response
});

Related

How to fix Laravel AJAX request not working

I am trying to store the data from multiple ratio buttons to the database.
And the AJAX post request is below:
$.ajax({
url: '{{ route("checklist.store") }}',
method:'POST',
data:{
_token: CSRF_TOKEN,
data1 : value1,
data2 : value2
},
success:function(data){
console.log('success');
}
});
The message in the console is printed on the console but the item is not created in the database.
Store method in controller :
$hacInspectionsChecklistTable = HacInspectionsChecklistTable::create($request->all());
Check your Model first :
protected $fillable = [
'data1', 'data2'
];
If everything is ok you can try with something like that
Ajax code :
$.ajax({
url: '{{ route("route.store") }}',
method:'POST',
data:{
_token: CSRF_TOKEN,
data1 : value1,
data2 : value2
},
success:function(data){
if(data=="created"){
console.log('success');
}
}
});
Route
Route::post('/youroute', [YourController::class, 'store'])->name('route.store');
Controller
public function store(Request $request){
$data = new Model();
$data->data1 = $request->data1;
$data->data2 = $request->data2;
$data->save();
return response()->json('created');
}

Laravel: sending JSONArray from ajax to Controller error: Undefined variable myData

I am sending a JSONArray via Ajax to Controller. and it is returning
"500 Internal Server Error"
After checking response of URL in console I found that my Array is undefined:
message- Undefined variable: myData
exception- ErrorException
file- C:\xampp\htdocs\EDO_Roster\app\Http\Controllers\EventController.php
This is my Ajax Code:
var myJson = JSON.stringify(myData);
var button = document.getElementById("submit");
button.addEventListener("click", function(event){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: "{{route('postEvent' , 'myJson')}}",
data: {myData: myJson},
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done( function(data){
console.log('Ajax was Successful!');
console.log(data);
}).fail(function(){
console.log('Ajax Failed');
});
});
route of the function:
Route::post('randomPost', 'EventController#postEvent')->name('postEvent');
This is my Controller Code
public function postEvent(Request $request)
{
$events = DB::table('auto_events')
->insert(array(
'edo_id' => $myData->edo_id,
'strat' => $myData->start,
)
);
return response($events, 200);
}
I've tried several solutions provided at stack overflow like changing Ajax calls, checked my route several times.
You haven't defined the variable $myData inside your controller, that's why you got that error on your controller, you're supposed to get the input data from $request
just try as below
public function postEvent(Request $request)
{
$myData = $request->all();
$events = DB::table('auto_events')
->insert(array(
'edo_id' => $myData->edo_id,
'strat' => $myData->start,
)
);
return response($events, 200);
}

Populate text box with Json data

Please see my below code,
Controller -
public ActionResult AmountOwed()
{
int vehicleID = Convert.ToInt32(Request.Cookies["VehicleID"].Value);
var amountOwed = _PUSPERSContext.TblEOYPayments.Where(x => x.VehicleID == vehicleID).OrderByDescending(x => x.PaymentID).Take(1).Select(x => x.AmountOwed).ToList().FirstOrDefault();
return Json(amountOwed, JsonRequestBehavior.AllowGet);
}
This gives me the value I want but I now want to display it in a textbox in a partial view (_EOYPaymentsLayout.cshtml) -
<div class='form-group'>
#Html.LabelFor(m => m.TblEOYPayment.AmountOwed, new { title = "Amount Owed" })
#Html.TextBoxFor(m => m.TblEOYPayment.AmountOwed, new { title = "Amount Owed", #class = "form-control inputSizeMedium"})
</div>
I have have tried various things in my ajax code but I can never get the value into the view (this code is in the main view called Payments) -
$(document).ready(function () {
$('#addEOYPayment').click(function () {
$.ajax({
type: "GET",
url: "AmountOwed",
datatype: "Json",
success: function (data) {
$('#TblEOYPayment_AmountOwed').html(data.amountOwed);
}
});
});
});
Would be grateful for some advice. Thanks
Instead of return a json object, you can return a partial view
C#
public ActionResult AmountOwed()
{
int vehicleID =
Convert.ToInt32(Request.Cookies["VehicleID"].Value);
var amountOwed = _PUSPERSContext.TblEOYPayments.Where(x => x.VehicleID == vehicleID).OrderByDescending(x => x.PaymentID).Take(1).Select(x => x.AmountOwed).ToList().FirstOrDefault();
return PartialView("NameOfView.cshtml", amountOwed );
}
js
$(document).ready(function () {
$('#addEOYPayment').click(function () {
$.ajax({
type: "GET",
url: "AmountOwed",
datatype: "Json",
success: function (data) {
$('#TblEOYPayment_AmountOwed').html(data.responseText);
}
});
});
});
and your view may receive the type of thevariable amountOwed.
You must double check your url. Please do include the controller name. For an instance: URL: "\Home\AmountOwed\" + ID,
Thanks for the replies.
Finally got it working, it was just this:
$(document).ready(function () {
$('#addEOYPayment').click(function () {
$.ajax({
type: "GET",
url: "/Home/AmountOwed",
datatype: "Json",
success: function (data) {
$('#TblEOYPayment_AmountOwed').val(data);
}
});
});
});

no display fail message from controller

I need validate user's nickname when the gonna registre in my proyect:
My Controller
$inputData = Input::get('nickname');
parse_str($inputData);
$informacion = array('nickname' => $inputData);
$regla = array('nickname'=>'required|unique:usuarios|alpha_num|min:6|max:15');
if($request->ajax()){
$usuarios = Usuarios::Usuarios();
$validar = Validator::make($informacion,$regla);
if($validar->fails()){
return Response()->json(array(
'fail' => true,
'errors' => $validar->getMessageBag()->toArray()));
}
else{
return Response()->json(array('success' => true, "message" => "Nombre de Usuario Disponible"));
}
}
My Script
$( "#validar" ).click(function( event ) {
var dato = $('#nickname').val();
var route = $('#form-sign-up').attr('action');
var tipo = $('#form-sign-up').attr('method');
var token = $('#form-sign-up #token').val();
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{nickname: dato},})
.fail(function(data){
$('#nickname-msj').html(data.errors);
$('#nickname-msj').fadeIn();
})
.done(function(data) {
$('#nickname-msj').html(data.message);
$('#nickname-msj').fadeIn();
});
});
.done works, but .fails not, and i need display that information to my user, because so they can know what is the problem, if someone can help me will be great.
I am using Laravel 5.2
Thank you.
The fails function of Ajax is triggered with a code different from 200. So you can return
if($validar->fails()) {
return response()->json($arrayHere, 400); //HTTP 400 error for bad request
}
So, just basically add 400 after your array, inside of json() function. When you don't specify the code, it defaults to 200.
Maybe also change your ajax request ? Or not
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{
nickname: dato
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});

Redirect to diffrent action when reciving json results in my script

i'm getting a list view json results and I would like to redirect to a different view and display the results according to my json
( I hope i'm clear) this what i'm did
<script type="text/javascript">
$(document).ready(function () {
$("#term").autocomplete({
source: function (request, response) {
$.ajax({
url: "Home/GetSubjectsName",
data: "{'term': '" + request.term + "' }",
dataType: 'json',
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.value,
value: item.value,
id: item.id,
}
var url = '#Url.Action("bla", "blaaaa")';
}))
}
});
},
minLength: 2,
});
});
my jsonlook like this :
public JsonResult GetSubjectsName(string term)
{
var results = db.subjects.Where(s => term == null ||
s.SubjectName.ToLower().Contains(term.ToLower())).Select(x => new
{ id = x.SubjectId, value = x.SubjectName }).Distinct().ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
and the action I would like to display the results is this (instead of partial view)
public ActionResult bla(string term)
{
IEnumerable serach = from sub in db.subjects.Where(t => t.SubjectName.Contains(term)).Distinct()
select new SearchResultsViewModel
{
Created = sub.Created,
Gender = sub.Gender,
OccupationDecription = sub.OccupationDecription,
Image = sub.Image,
SubjectName = sub.SubjectName
};
ViewBag.term = term;
return RedirectToAction("bla", "home", serach.ToList());
}
my View :
#model IEnumerable<MyProJect.ViewModels.SearchResultsViewModel>
foreach ....
what I need is to go to a different action and display the data
Here's some code that might help. Your post is still a bit unclear, so I'm filling in the missing pieces according to what you have described. I've made no attempt at designing the form layout.
Home/Index.cshtml:
#using( Html.BeginForm("bla") ) {
#Html.LabelFor(model => model.term)
#Html.EditorFor(model => model.term)
<button type="submit">Submit</button>
}
<script type="text/javascript">
jQuery(function ($) {
$("#term").autocomplete({ source: '#Url.Action("GetSubjectsName")', autoFocus: true, minLength: 2 });
});
</script>
Your autocomplete should be changed to:
public JsonResult GetSubjectsName(string term)
{
return Json(db.subjects
.Where(s => term == null ||
s.SubjectName.ToLower()
.Contains(term.ToLower()))
.OrderBy(x => x.SubjectName)
.Select(x => x.SubjectName)
.Distinct(), JsonRequestBehavior.AllowGet);
}
As far as I can tell, everything else should work as intended.