3

I am sending a value through a jquery ajax call to my spring controller. I want it to send an object back to populate a form in an iziModal. Currently, it sends the value from the browser back to my controller, and runs through my method in my controller, but then I get stuck. For some reason I'm having issues sending the response back to my ajax success function. I am getting this parse error: SyntaxError: Unexpected token t in JSON at position 1556482

Here is my controller method:

 @RequestMapping(value="/editCarrierAjax", method= RequestMethod.POST)
 public @ResponseBody CarrierAppointment getCarrierDets (@RequestParam("data") String data, MasterCarrier masterCarrier,  Model model) throws Exception{
       CarrierAppointment carrierToEdit = carrierAppointmentRepository.findById(Long.parseLong(data));
        model.addAttribute("carrierToEdit", carrierToEdit);
        return carrierToEdit;
    }

Ajax Call:

            $('.trigger-edit-carrier').on('click', function(event){
                var selectId = $(this).attr('value');
                console.log(selectId);
                var token = $("meta[name='_csrf']").attr("content");
                console.log(token);
                var header = "X-CSRF-TOKEN";
                  console.log(header);
                 $.ajax({
                    type: "POST",
                    url: "/editCarrierAjax",
                    data: {data:selectId},
                    dataType:"json",
                    cache: false,
                    timeout: 600000,
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader(header, token);
                        console.log(header +", "+ token);
                    },
                    success: function(data, jqXHR){
                          console.log("success fn");
                          console.log(data);
                      
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("Status: " + textStatus); alert("Error: " + errorThrown);
                    }
                });
            });

I've tried adding the Jackson library mentioned here Convert a object into JSON in REST service by Spring MVC

but it still throws an error. Any idea how to fix this error?

Stacie
  • 306
  • 7
  • 26
  • Your ajax code doesn't have `dataType: "json"` ? Are you returning json response ? – Swati Jun 25 '20 at 03:59
  • @Swati if i add contentType and dataType as json, I get a 400 bad request error. I am just trying for return of an object. I've used similar ajax/code before in a different project and it worked there so not sure whats bad here. – Stacie Jun 25 '20 at 16:20
  • Currently in your code you have not converted your `carrierToEdit` to json as your ajax is accepting json ? can you update your code with that ? Also then check what does `console.log(data);` showing ? – Swati Jul 02 '20 at 04:11

2 Answers2

1

It seems like your data returned by method is having issue in parsing JSON. sometimes it happens due to some special characters in data. Could you just try to log carrierToEdit( System.out.println(carrierToEdit); ) on server side and see its value? probably it will be very BIG string content and id you put it in any text editor and go to position 1556482 you will see t which is causing this...

SyntaxError: Unexpected token t in JSON at position 1556482

also if your data in not sensitive you can try to validate it online using some JSON validator tools like https://jsonlint.com/

You can find the issue there and some minor changes in data/code would fix your parsing issue...

     @RequestMapping(value="/editCarrierAjax", method= RequestMethod.POST)
     public @ResponseBody CarrierAppointment getCarrierDets (@RequestParam("data") String data, MasterCarrier masterCarrier,  Model model) throws Exception{
           CarrierAppointment carrierToEdit = carrierAppointmentRepository.findById(Long.parseLong(data));
System.out.println(carrierToEdit);

            model.addAttribute("carrierToEdit", carrierToEdit);
            return carrierToEdit;
        }

Hope this Helps... All the Best :)

0

The fact that you get a 400 bad request status code returned if you set contentType and dataType to json (maybe try out application/json!) in your jQuery code could relate to controller misconfiguration. If all of your controller methods process JSON (receive JSON payload in requestbody, respond with JSON payload in responsebody) then you could try to set the @RestController annotation at your controllers class-level - this annotation also implicitly adds a @ResponseBody annotation and configures all controller methods to consume and produce content of type application/json. E.g. like this:

@RestController
public class YourControllerClass {

  @PostMapping("/editCarrierAjax")
  public CarrierAppointment getCarrierDets(@RequestParam("data") String data, MasterCarrier masterCarrier,  Model model) throws Exception {
     CarrierAppointment carrierToEdit = carrierAppointmentRepository.findById(Long.parseLong(data));
     model.addAttribute("carrierToEdit", carrierToEdit);
     return carrierToEdit;
  }
}

The other option would be to explictly configure this single controller method, to consume/produce JSON, e.g. like this:

@Controller
public class YourControllerClass {

  @ResponseBody 
  @RequestMapping(value="/editCarrierAjax", method= RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
  public CarrierAppointment getCarrierDets(@RequestParam("data") String data, MasterCarrier masterCarrier,  Model model) throws Exception{
    CarrierAppointment carrierToEdit = carrierAppointmentRepository.findById(Long.parseLong(data));
    model.addAttribute("carrierToEdit", carrierToEdit);
    return carrierToEdit;
  }
}

Please share your whole controller and CarrierAppointment class if any of those approaches don't fix your issue. You should also validate the generated JSON that is sent back to your client as @Programmer suggested. Good luck!