Laravel with Jquery - Ajax Throwing 500 Error - Prob with Server Side - javascript

. Hello y'all. I am trying to gather a few variables and send it to my controller. I keep getting a 500 error and can't figure out where exactly I'm going wrong other than I'm pretty sure its server side. Any pointers about where I went wrong or better practices would be greatly appreciated! Thank yall so much!
Route:
/*Ajax Edit Price on Price Page*/
Route::post('edit_price', array(
'as' => 'edit_price',
'uses' => 'PriceController#edit_price'
));
Controller:
public function price_edit(){
console.log($id_and_db);
}
JS:
/*Ajax edit prices*/
$(document).ready(function(){
$('.edit_button').click(function(e){
e.preventDefault();
var id_and_db = $(this).prop('name').replace('edit', 'newprice'),
new_price = $('[name=' + id_and_db + ']').val();
$('#test').val(id_and_db);
$.ajax({
url: 'edit_price',
type: "POST",
data: {
"id_and_db": id_and_db,
"new_price": new_price,
},
success: function(data){
$("#edit_results").html(data);
$("#edit_results").addClass('panel callout radius');
console.log(data);
},
error: function(xhr, status, error){
console.log(xhr);
console.log(status);
console.log(error);
},
});
});
});
Error Message:
POST http://localhost/local/example/public/edit_price 500 (Internal Server Error) jquery.min.js:4
XHR finished loading: POST "http://localhost/local/example/public/edit_price". jquery.min.js:4
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
price_index_admin.js:40
error price_index_admin.js:41
Internal Server Error

You did
'uses' => 'PriceController#edit_price'
but your controller method is price_edit().
Try change your controller method to
public function edit_price() {

This is not valid for a controller - it looks like you are trying to run java inside php:
public function price_edit(){
console.log($id_and_db);
}
it should be something like this
public function price_edit(){
return Response::json(['your response here']);
}

Related

JSON Parse error when submitting AJAX post to Spring Boot Controller using Thymeleaf

I have a form that I am submitting using AJAX:
var formData = JSON.stringify($('#supportrequest').serializeArray());
$.ajax({
type: "POST",
url: "/updatesupportrequest?bugid=" + $('#requestnum').val(),
data: formData,
success: function(){
console.log("success");
},
error: function(xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
},
complete: function(){
console.log("complete");
},
dataType: "json",
contentType : "application/json"
});
This is picked up by my Spring Boot controller:
#PostMapping("/updatesupportrequest") // Called by the form
public String createSupportRequest(#RequestParam(name = "bugid") int bugid, #RequestBody String requestBody,
Model model) {
System.out.println(bugid);
DatabaseWriteResponse response = writeToDatabaseService
.writeToDatabase(WriteToDatabaseService.PROCEDURE_UPDATESUPPORTREQUEST, requestBody);
System.out.println(response.getResponse());
if (response.getResponse().equals(DatabaseWriteResponse.SUCCESS)) {
return "supportrequest";
}
else {
model.addAttribute("response", response.getResponse());
model.addAttribute("errorMsg", response.getMsg());
return "error";
}
}
The actual saving of the data works just fine. The problem is that the controller returns the "supportrequest.html" page. AJAX then throws a parse error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Looking at the xhr.responseText, we get the page back:
responseText: "<!--\r\n TODO\r\n - Dev page has some different fields \r\n\r\n\r\n -->\r\n\r\n<!DOCTYPE HTML>\r\n<html>\r\n<head>\r\n<title>Support Center</title>\r\n<meta http-equiv=\"Content-Type\" content=\"text/html;
I either need the page to redirect properly (which works fine on Get, just not Post) or to be able to return an empty JSON string and trigger the AJAX success function. I don't particular care which - I can handle the result either way. I just can't get either option to work. What am I doing wrong?
If you want to return JSON in a #Controller class, then annotate the return type of the method with #ResponseBody.

Access JSON Ajax Response data

I have added a property to a JSON data but I cannot access the data on JS it does not show. I am not new to Ajax and JSON but it is a apparent that I still have gaps in my knowledge when it comes to Ajax. Please help me understand how i can append data to my Ajax response.
I have this in a PHP controller class:
$x = '5';
if($request->ajax()){
return response()->json([
'total_questions' => $x,
'responseText' => $e->getMessage(),
], 500);
}
I want to access the total_questions property with JS/JQuery..
My JS AJAX callback is here:
console.log('errors -> ', data.total_questions); - returns undefined
$.ajax({
type:"POST",
url: APP_URL+"selfEvaluation/save",
data:$(this).serialize(),
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(data){
var errors = data.responseJSON;
console.log('data -> ', data);
console.log('errors -> ', data.total_questions);
if(data.status == 422){
// alert('422');
}
}
});
This is my console result
error: function(data){
is an incorrect method signature. See the definition at http://api.jquery.com/jquery.ajax/.
It should be
error: function(jqXHR, errorThrown, textStatus){.
You'll need to access the jqXHR.responseJSON property. So:
console.log('errors -> ', jqXHR.responseJSON.total_questions);
But I would question why you're returning a "500" status code for this request, when it appears to be a valid response. "500" means "Internal Server Error", which implies the server crashed, when it appears that it did not. If you return a "200" ("OK") status, your ajax code will go into the "success" callback and you can directly reference the "data" object in the callback to read your data.
try this if you will get a json response from your browser.
if($request->ajax()){
$result = array(
'total_questions' => $x,
'responseText' => $e->getMessage(),
], 500);
}
echo json_encode($result);

No response in console to jquery ajax request

I am making the following jquery ajax call to a codeigniter php function:
$.ajax({
type:"POST",
url: "AjaxUpdate/getHtml",
data:{ u : 'http://stackoverflow.com/' },
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(jqXHR,textStatus, errorThrown);
}
});
The requested php function is :
public function getHtml() {
$url = $_POST['u'];
$result = file_get_contents($url);
return json_encode($result);
}
How can I fix this?
edit: the error in the console shows:
error
reply_detail:4667 Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…} "parsererror" SyntaxError: Unexpected end of input {stack: (...), message: "Unexpected end of input"}message: "Unexpected end of input"stack: (...)get stack: function () { [native code] }set stack: function () { [native code] }__proto__: Error
Some things may be happening.
I don't know PHP, but is getHtml REALLY returning a JSON?
Maybe it is failing to parse the returning content. There are other options in the JQuery $.ajax dataType property.
It isn't executing the success function, because it might be failing at some point. Try adding an error function and log the data. The JQuery documentation is very helpful and rich.
Also, try to change to data: JSON.stringify({ u : 'http://stackoverflow.com/' }), at least in ASP.NET I have to do it every time.
Are you sure you are calling the function inside the file?
You need to invoke the function by calling it.
getHtml();

backbone.js error handling with laravel issues

I have a model.save, it works fine.
this.model.save({
success: function (model, response) {
alert('hello');
},
error: function (model, xhr, options) {
alert('hello');
},
});
The controller is sending back 500, which i want it to right now for testing.
$response = [
'status' => 'error',
'message' => 'Cannot delete! Image is in use.'
];
return Response::json($response, 500);
console.log shows: POST /mysite/public/api/test 500 (Internal Server Error)
It is not alerting me 'hello', so for some reason my error callback function is not working. I can't find any problems with the syntax. Anyone else spot my problem? If so thank you!
The first argument of the save method is a set of attributes to save, and the second argument is the the options hash which should contain your callbacks. Modify your call to look like this:
this.model.save(null, {
success: function (model, response) {
console.log("success");
},
error: function (model, response) {
console.log("error");
}
});

ASP.NET MVC HttpException message not shown on client

I'm building a RESTful web api with asp.net mvc, which returns pure json data. On my client, I'm using backbone.js to communicate to it.
My question is, how do I capture the message in javascript? For eg. What if a user has no permission to delete or there was no item matching the id? I've been told to throw http errors instead of custom json.
So my code would be:
[HttpDelete]
public ActionResult Index(int id)
{
if (id == 1)
{
throw new HttpException(404, "No user with that ID");
}
else if (id == 2)
{
throw new HttpException(401, "You have no authorization to delete this user");
}
return Json(true);
}
How do I access the message in my javascript callback? The callback would look like:
function (model, response) {
alert("failed");
//response.responseText would contain the html you would see for asp.net
}
I do not see message i threw in the exception anywhere at all in the data that was returned from the server.
You should use the error callback on the client. The success callback is triggered only when the request succeeds:
$.ajax({
url: '/home/index',
type: 'DELETE',
data: { id: 1 },
success: function (result) {
alert('success'); // result will always be true here
},
error: function (jqXHR, textStatus, errorThrown) {
var statusCode = jqXHR.status; // will equal to 404
alert(statusCode);
}
});
Now there is a caveat with 401 status code. When you throw 401 HTTP exception from the server, the forms authentication module intercepts it and automatically renders the LogIn page and replaces the 401 status code with 200. So the error handler will not be executed for this particular status code.
I just answered this in my question What is the point of HttpException in ASP.NET MVC, but you can actually get that string if you use the HttpStatusCodeResult like this:
In your controller:
return new HttpStatusCodeResult(500,"Something bad happened")
And you can access "Something bad happened" using, say, jQuery $.ajax() like this:
$.ajax: {
url: "#Url.Action("RequestsAdminAjax", "Admin")",
type: "POST",
data: function(data) { return JSON.stringify(data); },
contentType: "application/json; charset=utf-8",
error: function (xhr, textStatus,errorThrown) {
debugger;
toggleAlert('<strong>Error: </strong>Unable to load data.', 'alert alert-danger');
}
},
and errorThrown will contain "Something bad happened".
HTH.

Categories

Resources