Tips for handling Syntax Errors caused by invalid tokens in the JSON data from geocoding services

When querying geocoding with state/country, I sometimes encounter issues where the JSON responses are not parsed properly. How can I handle these errors and continue to the next response?

Below is the AJAX call:

$.ajax({

    url: "/abc/points",
    context: document.body,
    data: {
        latitude: places[0].geometry.location
            .lat(),
        longitude: places[0].geometry.location
            .lng(),
        distance: $(
                'input[name="distance"]:checked')
            .val(),
        city: city1,
        state: state1,
        country: country1,

    },
    success: function(responseText) {
        $("#response-div").html(
            responseText);
        $("#response-div")
            .find("script")
            .each(
                function(i) {
                    eval($(
                            this)
                        .text());
                });
        $("html").removeClass(
            "wait");
    }

});

There may be numerous results returned, and I simply want to skip over those that cause syntax errors and proceed with the next one. If needed, I can provide a sample of the JSON text returned.

Thank you

COMMENT I am unsure if it's possible to ignore syntax errors, so I'm exploring an alternative approach. Essentially, I need to replace both '\n' characters and commas in a JSON response being parsed into JSTL. Any guidance on how to achieve this would be greatly appreciated. While there are solutions for ignoring one or the other, combining both replacements seems to be a challenge.

function(marker, event, context) {
                             var contentString = '<div style="width:600px; height: 300px;">' +
                                                    '<div> <h4>' +  '${fn:replace(object.name, search, replace)}' + ' </h4> </div>' +
                                                    '<table class="table">' +
                                                      '<tbody>' +
                                                        '<tr class="active">' +
                                                          '<td>Address: </td>' +
                                                          <c:set var="address" value="${object.stAddress} ${object.city}, ${object.state} ${object.zipcode}" />
                                                          '<td colspan=5>' + "${fn:replace(address, ",", " ")}"+"${fn:replace(address, "\n", " ")}" + '</td>' +
                                                       ' </tr>' +

Edit I have attempted various methods to replace special characters but have encountered challenges specifically with '\n'

<c:set var="search" value="'" />
<c:set var="replace" value="" />
<c:set var="newLn" value="\n" />
${fn:replace(fn:replace(address, newLn, replace), search, replace)}

Answer №1

After some investigation, I managed to find a solution to this issue. Sharing my method here in case it can benefit others.

<c:set var="modifiedAddress" value="${fn:replace(originalAddress,newLine, "")}" />

In my script, I utilized the 'modifiedAddress' variable for executing double replacements.

${fn:replace(modifiedAddress, "'", "")} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Conditional radio button disabling in Material-ui

Currently, I am developing a React application using material-ui. My goal is to disable all radio buttons within a RadioGroup when a specific event occurs, and then re-enable them once the event is no longer active. For example, when a button is clicked, ...

Encountered an error in index.js while using JavaScript: ".babelrc error - please refrain from copying comments as the object could not be cloned."

Update: it appears that the issue is linked to my .babelrc file: { "presets": ["env", "react"], "plugins": ["transform-class-properties", "transform-object-rest-spread"] } Removing this f ...

The initial output of the object yields an undefined value

Issue Description (View Code on Fiddle): The issue with this code is that the first printed result returns 'undefined'. Why does this happen and how can it be fixed? Code Snippet: var animals = { dogs: 0, cats: 0, birds: 0, fis ...

Using arrow functions in React to streamline unit testing with Jest

Every time I encounter an error that checkIfBlank is undefined, I recognize that I need to export the function. However, I am unsure how to do so for an Arrow Function. This is the code snippet in register.js import React from "react"; import ax ...

Issue with $routeChangeStart and other similar events not being triggered during page initialization

Within my angular web application, $routeProvider .when('/topic/:keyword/heath-feed', { controller: 'hfController', }) .when('/topic/:keyword/heath-feed/:storyType', { controller: 'hfControll ...

Having trouble with accessing controls within an UpdatePanel?

I am attempting to access Page Controls at Page_Load, execute a database query, and modify the visibility of controls. Here is the Code: foreach (Control thiscontrol in ContentPlaceHolderBody.Controls) { try { if (thiscontrol.ID.Contains("Tex ...

Looking to enhance this JavaScript code for updating an object's description - any tips on optimization?

I have a list of group items, with 7 items per column. Each item has an id, such as #a1, #b2, etc. I am using the Simple Slider plugin to display two columns on each slide: one with the list and one with the description #descr. I am looking for a more effi ...

Mistakes with managing Ajax callbacks for success and failure

Encountered a strange issue... The DESIRED outcome is: Upon successful request, display a basic alert on the page to confirm functionality. In case of failure, show the error message within the designated div. $(function() { $('.error').hid ...

"Unlocking the Power of PayPal: A Guide to Seamless Integration with Context

Is there a way to integrate PayPal Express Checkout as a pop-up on my website instead of redirecting to PayPal? I need to make the payment using jQuery AJAX. Can anyone provide a tutorial or link that would help me accomplish this? Thank you in advance. ...

Dealing with the use of ?_escaped_fragment_= for AJAX crawlers

Struggling to ensure my AJAX-based website is SEO-friendly. Following online tutorials, I've added "pretty" href attributes to links such as: <a href="#!site=contact" data-id="contact" class="navlink">контакт</a>. In the div where c ...

What is the best way to create synchronous AJAX requests?

Can I convert this into a function? // Function to check if station is alive function checkStation(valueSelected) { let result = false; $.ajax({ url: "lib/grab.php", data: "check_live=1&stream_url="+valueSelected, ...

"Encountered a problem during the installation of pm2 for Node.js

I am in the process of installing pm2 (https://github.com/Unitech/pm2) Encountered the following error while doing so: D:\_Work>npm install pm2 -g --unsafe-perm npm WARN `git config --get remote.origin.url` returned wrong result (http://ikt.pm ...

Ways to stringify a JavaScript new date object using JSON

Extracting information from the form's JSON as users input data on the calendar const data = JSON.stringify(orderForm.informationDate)); At present, I am retrieving JSON data to generate a PDF document: {"year":2023,"month":12,&qu ...

What could be the reason for express-validator's inability to identify missing fields during the validation of XML input

My server, based on Express, is set up to parse XML instead of JSON using body-parser-xml. To validate the input body, I am using express-validator as shown in the following simplified example: router.post("/", body('session.credential[0].$.usern ...

What is the best way to utilize the "useRouter" function to extract parameters from the URL within the getServerSideProps() method in Next.js?

How can I access the URL parameters within the getServerSideProps() method? Below is the snippet of my code. The objective of my code is to extract parameters from the URL, fetch data from the API, and render it on the front end. import { useRouter } from ...

When dealing with Retrofit2, how should I structure a JSON class if the data received from the server is in this format?

If I receive JSON data like the example below, how should I define the Postitem class? { "author": "1122", "text": "ggg", "image": "https://www.landscape.com/irenepretty", "point": { "longitude": "-4.921875", "latitude": "13.9 ...

Iterating through a set of HTML elements and making updates using a forEach loop

I have encountered an issue while attempting to update a group of HTML elements within a forEach loop. Initially, everything appears to be functioning correctly up to section 3. However, upon adding a new section, the problem arises where the navigation ba ...

How can I attach an existing event to a dynamically loaded element using AJAX?

In the main page of my website, there is a button: <button class="test">test</button> Additionally, I have included the following script in my code: $('.test').on('click',function(){ alert("YOU CLICKED ME"); } ...

Exploring the behavior of control flow in Typescript

I am a beginner when it comes to JS, TS, and Angular, and I have encountered an issue with an Angular component that I am working on: export class AdminProductsMenuComponent implements OnInit{ constructor(private productService: ProductService, ...

What is the best way to trigger Ajax OnClick from a Provider Web Part to a Consumer Web Part?

I'm currently working on managing an ajax connection by triggering a button onclick method in a different web part to initiate a partial postback on the consumer side. The process involves Web Part A (Provider) calling a method on Web Part B (Consume ...