Click here to Skip to main content
15,116,815 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I try to consume a Geocoding Service. The URL looks like
https://myURL/GeocodeServer/geocodeAddresses

After launching the Geocoding page, and then pasting the data values into the textbox,
{
  "records": [
{"attributes": {"SingleLine": "CAPH", "OBJECTID" : 1 }} ,
{"attributes": {"SingleLine": "WOPK", "OBJECTID" : 2 }} ]
}

clicking on either [Get] or [Post] button results in the results displayed (either JSON or HTML format).

My next step is to write a JavaScript script that uses an AJAX function to retrieve the results dynamically.
My code is below:
var formData = '{"records": [ {"attributes": {"SingleLine": "CAPH", "OBJECTID" : 1 }}, {"attributes": {"SingleLine": "WOPK", "OBJECTID" : 2 }} ] }';
var url = "https://myURL/GeocodeServer/geocodeAddresses";
$("#searchForm").submit(function (event) {
    $.ajax({
        type: 'POST',
        url: url, 
        data: JSON.stringify(formData),  // formatData since it is formatted in JSON already
        contentType: "application/json; charset=utf-8",
        traditional: true,
        success: function (data, textStatus, jQxhr) {
            var result = data;
        },
        error: function (jqXhr, textStatus, errorThrown) {
            console.log(errorThrown);
        }
    });
}             

However, I still get error. How to format well for an AJAX Get or Post? What's wrong in my AJAX code? Thanks if you can help.

What I have tried:

How to format well for an AJAX Get or Post
Posted
Updated 21-Oct-21 0:40am
Comments
SeeSharp2 18-Jun-21 8:49am
   
1. What is the error?
2. You do not need to call JSON.stringify. That is meant to stringify an object but formData is already a string.
s yu 18-Jun-21 9:29am
   
If JSON.stringfy() is removed, still get the same error. The errorThrown = ''.

1 solution

When the form is submitted, you initiate an AJAX request. But you don't cancel the form submission, so your page unloads and navigates to the form's action instead.

Use event.preventDefault() to stop the form from being submitted so that your AJAX request has a chance to run.
JavaScript
$("#searchForm").submit(function (event) {
    event.preventDefault();
    
    $.ajax({
        type: 'POST',
        url: url, 
        data: formData,
        contentType: "application/json; charset=utf-8",
        traditional: true,
        success: function (data, textStatus, jQxhr) {
            var result = data;
            // Do something with the data here...
        },
        error: function (jqXhr, textStatus, errorThrown) {
            console.error(errorThrown);
        }
    });
}             
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900