2

Hello I have a problem with my ajax request in jquery.

When I use my get request without sending any data the response is as expected, I receive my array and can access the values:

$.get(
    loadUrl,
    function(data) {
        useReturnData(data);
    },
    "json"
);

function useReturnData(data){
    leftPlayer = data;
    alert(leftPlayer[4]);
};

This works as expected and I recieve my value of "528" being my leftPlayer[4] value.

But when I change my request to send a piece of data to php in the request like so:

$.get(
    loadUrl,
    { type: "left" })
    .done(function(data) {
        useReturnData(data);
    },
    "json"
);

function useReturnData(data){
    leftPlayer = data;
    alert(leftPlayer[4]);
};

My data received seems to be in string format to javascript. My alert prints "5" (the 4th character if the array was a string)

When alerting leftPlayer. I find that in the first request in which I send no data the variable is printed as: 355,355,355,355,528,etc...

Whereas in the second request in which I DO send data it prints as:

[355,355,355,355,528,etc...]

Notice the []. It isn't recognised as an array.

The php file it accesses has absolutely no changes in each request, as I am testing at the moment. The data sent isn't even used in the php file at the moment.

Any ideas where I'm going wrong?

3
  • 1
    You should be passing the "json" parameter to the $.get() function, but you're passing it to the .done() function. Commented Sep 1, 2013 at 11:35
  • Ah I see.. I tried using: Commented Sep 1, 2013 at 11:54
  • $.get( loadUrl, { type: "left" }, "json") .done(function(data) { useReturnData(data); } ); - but no change Commented Sep 1, 2013 at 11:54

1 Answer 1

1

I've fixed my problem.

Like what "nnnnnn" said in his comment I'm passing my "json" parameter to the .done() function instead of the $.get() function.

I couldn't seem to get it to correctly view it as JSON though so I used the easiest method:

$.getJSON(
    loadUrl,
    { type: "left" },
    function(data) {
        useReturnData(data);
    }
);

function useReturnData(data){
    leftPlayer = data;
    alert(leftPlayer[4]);
};

Using $.getJSON instead does like what it says and expects JSON to be returned as default.

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

Comments

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.