no display fail message from controller - json

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);
}
});

Related

Ajax function (Unexpected token) in AJAX Call

so I have been testing a bunch of new different JS code to see if I can get the POST request to send information to a SharePoint list. When I run my newest block, it tells me "Error: Line 20: Unexpected token" when I call $.ajax saying the period is what is unexpected? I truly don't understand.
Here is my JS code:
$(document).ready(function(){
$("#btnSubmit").click(function(){
saveDelivDetails();
});
});
function saveDelivDetails(){
var itemType = GetListItemTpye(listname);
var item = {
"__metadata":{"type":itemType},
"Program":$("#dProgram").val(),
"Deliverable":$("#dDeliverable").val(),
"To":$("#dTo").val(),
"Date":$("#dDate").val(),
"Approved":$("#dApproved").val(),
"Notes":$("#dNotes").val()
};
var requestUrl = _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('"+listname+"')/items",
$.ajax({
url: requestUrl,
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers:{
"Accept":"application/json;odata=verbose",
"X-RequestDigest":$("#__REQUESTDIGEST").val()
},
success: onSuccess,
error: onError,
});
function onSuccess(data){
alert("New Item Created");
$("#txtSubmitName").val();
}
function onError(error){
alert('error' + error);
console.log(error);
}
function GetListItemType(name){
return "SP.Data."+CharacterData(0).toUpperCase().name.slice(1)+"ListItem";
}
You have a , after line 19.
var requestUrl = _spPageContextInfo.webAbsoluteUrl+"/_api/web/lists/getbytitle('"+listname+"')/items",

Codes are displayed instead of html elements

I have called ajax request in some interval of time. Now, if I pressed the back button after success ajax then, the browser displayed all of my HTML code instead of displaying HTML elements.
<script>
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('devices.index')}}',
dataType: 'json',
success: function (data) {
}
});
}, 1000);
</script>
if($request->ajax()){
foreach ($devices as $device){
$latestUpdate = Carbon::parse($device->updated_at);
$diff = Carbon::now()->diffInMinutes($latestUpdate);
if($diff > 2){
Device::where('id',$device->id)->update(['status'=>'3']);
}
}
return response()->json(['msg' => "successfully checked"]);
}
I had expected to render the HTML elements, but it displayed.
{
"msg": "successfully checked"
}
Same things happened when I send HTML in json.
if($request->ajax()){
$returnHtml = view('alerts.index', compact('threshold'))
->with('alerts', $alerts)->render();
return response()->json(['html' => $returnHtml, 'data' => $alerts]);
}
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('alerts.index')}}',
dataType: 'json',
success: function (data) {
var formatedhtml = $('<div>').html(data.html).find('table');
$('table').html(formatedhtml);
}
});
}, 5000);
In this case it display
Instead of returning as json return data as array:
Try something like this
return ['html' => $returnHtml, 'data' => $alerts];
There's nothing wrong with how you are receiving the data when you use return response()->json(['html' => $returnHtml, 'data' => $alerts]);
If you want to actually put the html that you received from your server into an element in your page, you will need to use Element.innerHTML (https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) so that the html will not be escaped by the browser.
window.setInterval(function () {
$.ajax({
method: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '{{route('devices.index')}}',
dataType: 'json',
success: function (data) {
// this is the table where you want to place the received table contents
var my_table=$('#my-table')
// we turn the data we received from the server into a jQuery object, then find the table we want data from
var received_table=$(data.html).find('table')
// switch out the table contents
my_table.html(received_table.html())
}
});
}, 1000);
EDIT: Since you are using jQuery, I changed the answer to fit.

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);
}
});
});
});

“Invalid JSON primitive” in Ajax processing MVC

I have some problems with an ajax call.
Here is the function:
function jsFunction(value) {
var selectedCompany = document.getElementById("CompanyId");
var selectedCompanyId = selectedCompany.options[selectedCompany.selectedIndex].value;
$.ajax({
type: "POST",
data: { companyId: selectedCompanyId, supplierId: value },
url: "#Url.Action("CheckContract", "PaidWork")",
dataType: 'json',
traditional: true,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response) {
if (response != null && response.success) {
document.getElementById("errorMessage").style.display = 'hidden';
alert(response.responseText);
} else {
// DoSomethingElse()
document.getElementById("errorMessage").style.display = 'visible';
alert(response.responseText);
}
},
error: function (response) {
alert("error!"); //
}
});
}
This is the div for the message
<div id="errorMessage" style="display:none"><strong class="alert-danger">#ViewBag.MessageContractNotExist</strong></div>
In my view I have a message which I want to display or not, depends on what response Json send me from controller.
This is the method in controller:
public ActionResult CheckContract(int companyId, int supplierId)
{
bool result = true;
if (!spService.ContractExists(companyId, supplierId, ContractType.SupplierSilviPrio))
{
result = false;
}
if(!result)
{
ViewBag.MessageContractNotExist = "Not exist!!!";
return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
}
The problem is that I keep getting this error: invalid json primitive object
Can you please help me what I miss here? Thanks