0

I was trying to send String data using Ajax and then send back the JSON data from the server using the Java code. But every time when I try to run the javascript it alerts "Path Finder : error".

And when I try to put a breakpoint in the "return" row in java, it just doesn't work, so I guess it is has a problem on the request stuff.

But when I use POSTMAN to test the data, it works! (shown as the picture). Can anyone help me with this problem? Thousand Thanks !! Testing using POSTMAN

JavaScript:targetpaths.js

var serviceURL = "http://localhost:8080/TransportationNetwork/rest/paths";

$('#findPaths').click(function() {
                getPaths();
});

function getPaths() {
        console.log('display paths');
        $.ajax({
                type:'POST',
                contentType:'application/json', //data type sent to server
                url: serviceURL,
                dataType:"json", // data type get back from server
                data: dataToServer(), //data sent to server 
                success: function(data, textStatus, jqXHR){
                        alert('Path created successfully');
                },
                error: function(jqXHR, textStatus, errorThrown){
                        alert('Path Finder : ' + textStatus);
                }
        });
}

function dataToServer() {
        var array = "";
        var        str1 = $('#source').val();
        var        str2 = $('#target').val();

        array = str1 + "," + str2;

        return array;
}

<!DOCTYPE html>

The HTML:

<head>
    <title>Path Finder</title>
</head>

<body>
    <div style="padding-left:100px;font-family: monospace;">
        <h2>Path Finder</h2>

        <div style="width: 200px; text-align: left;">

            <div style="padding:10px;">
                Source Node: <input id="source" name="source" />
            </div>

            <div style="padding:10px;">
                Target Node: <input id="target" name="target" />
            </div>

            <div style="padding:10px;text-align:center">
                <button id="findPaths">Find Paths</button>
            </div>

        </div>

        <ul id="paths"></ul>


</div>

<p id="demo"></p>

<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/targetpaths.js"></script>

Java Code:

@Path("/paths")
public class PathsResource {
        PathDao pathDao;

    public PathsResource() {
            pathDao = new PathDao();
    }

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes("text/plain")
    public List<DirectedEdge> pathsInfo(@QueryParam("st") String st) {
            System.out.println("Searching paths : " + st);
            return pathDao.getEdgeList(st);

    }  

UPDATA:

I changed above code to things below, It did invoke the
"System.out.println("Searching paths : " + st);"
correctly.
However, the browser still send me the error alert, I do not know how to solve this problem, is that because it didn't return a correct JSON format? but why I can see the returned data is correct in POSTMAN??? HELP!!!!

JAVA:

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<DirectedEdge> pathsInfo(@QueryParam("st") String st) {
        System.out.println("Searching paths : " + st);
        return pathDao.getEdgeList(st);
    }  

JAVASCRIPT:

var serviceURL = "http://localhost:8080/TransportationNetwork/rest/paths";

function dataToServer() {
    var array = "";
        str1 = $('#source').val();
        str2 = $('#target').val();

array = str1 + "," + str2;

return array;
}

$('#findPaths').click(function() {
        getPaths();
});

function getPaths() {
    console.log('display paths');
    $.ajax({
        type:'GET',
        url: serviceURL,
        dataType:"json", // data type get back from server
        data:"st=" + dataToServer(), //data sent to server 
        success: function(data){
            alert('Path created successfully');
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('Path Finder : ' + textStatus);
        }
    });
}
4
  • What is the string dataToServer() returns? It looks like invalid JSON. Commented Nov 5, 2015 at 19:41
  • Please post a return of dataToServer(). Commented Nov 5, 2015 at 19:43
  • the dataToServer just return a String value like "2,8" , which denotes the target id, and source id.@taggon , @AlvaroJoao Commented Nov 5, 2015 at 19:53
  • Even if I change the @consume("text/plain"), it won't work. @taggon Commented Nov 5, 2015 at 19:58

4 Answers 4

1

Modify your code as

   var serviceURL = "http://localhost:8080/TransportationNetwork/rest/paths?";

    $('#findPaths').click(function() {
                    getPaths();
    });

    function getPaths() {
            console.log('display paths');
        var  str1 = $('#source').val();
        var  str2 = $('#target').val();

serviceURL=serviceURL+str1 + "," + str2;
            $.ajax({
                    type:'POST',
                    contentType:'application/json', //data type sent to server
                    url: serviceURL,
                    dataType:"json", // data type get back from server
                   // data: dataToServer(), //data sent to server 
                    success: function(data, textStatus, jqXHR){
                            alert('Path created successfully');
                    },
                    error: function(jqXHR, textStatus, errorThrown){
                            alert('Path Finder : ' + textStatus);
                    }
            });
    }

or update you dataToServer() method as

function dataToServer() {
var array = "";
    var str1 = $('#source').val();
    var str2 = $('#target').val();
        array = str1 + "," + str2;
return JSON.stringify({
        "st" : array

    });
}
Sign up to request clarification or add additional context in comments.

8 Comments

Do I need to specify the "st" parameter in the javascript? @ahmed
yes definitely and i have updated by answer and added an other way just modify you dataToServer method as i mentioned above
can you show me how to specify the "st" value in the url ? is it url + "st=" + dataToServer()? @ahmed
also chage @Consumes("text/plain") to @Consumes("application/json")
just append ?st=1,2 to the url as you submit the url through POSTMAN
|
0

If you really want to JSON data to the server, just make dataToServer() return valid JSON. Here the modified function:

function dataToServer() {
    var array = [];
    var str1 = $('#source').val();
    var str2 = $('#target').val();

    array = [str1 , str2];

    return JSON.stringify(array);
}

Remember to restore @Consumes("application/json").

7 Comments

Thanks, but what about the st parameter in the java code ? do I need to make any change? @taggon
st parameter should be appended to serviceURL. When you call $.ajax, change url: serviceURL to url: serviceURL + '?st=' + YOUR_ST_DATA.
I tried your code there, but same error popped up. I think I need to send the String like "2,8".
I just realized you want to send the data as st. Am I correct? Then, you don't need JSON. remove contentType, restore previous dataToServer, change the type of Ajax to "GET". Use "st="+dataToServer() as data to send. That's it. Forget all my previous answer.
Thank you,I did what you told me, and now I can see "System.out.println("Searching paths : " + st); " works in eclipse. but The same error popped up in the browser, why it cannot invoke the success method instead? @taggon
|
0

You are build wrongly the String read this

Solution:

    function dataToServer() {
        var array = "";
        var        str1 = '"source":'+ $('#source').val();
        var        str2 = '"target":'+ $('#target').val();

        array = "{"+str1 + "," + str2+"}";

        return array;
}

please see the example below:

var string = '1,2';
var string2 = '{"source":1,"target":2}';
try {

  var json = JSON.parse(string);
  document.write('ok : ' + string);
  document.write('<br/>');
  document.write(JSON.stringify(json, null, 2));
  document.write('<br/>');

} catch (err) {
  document.write('err: 1,2');
  document.write('<br/>');
}

try {

  var json2 = JSON.parse(string2);
  document.write('ok :' + string2);
  document.write('<br/>');
  document.write(JSON.stringify(json2, null, 2));

} catch (err) {
  document.write('err : {"method":1,"target":2}');
  document.write('<br/>');
}

5 Comments

Thanks man, but it just popped up the same error, I just wonder do I need to change the "st" parameter in java code ? @alvaro
Hi, I changed my code as shown in UPDATE above, however, the browser still send me the error alert, I do not know how to solve this problem, is that because it didn't return a correct json format? but why I can see the returned data is correct in POSTMAN? @alvaro
after change the code shown as UPDATE above, the System.out.println() works correctly in java. but why the browser still send me an error method? is it because the return value in java is not in json format? but why I can see the data in json format in POSTMAN? @alvaro
thank you, do you think I really have No 'Access-Control-Allow-Origin' header probem? , please take a look at stackoverflow.com/questions/33572801/… @alvaro
@user3765602 I will take few min to see it.
0

I am not familiar in this area but just a guess, should your 'dataToServer()' function return something like 'st=2,8' rather than just '2,8' ?

1 Comment

yes! correct! but I still have some problems receiving the json data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.