Matt Linland
Matt Linland

Reputation: 67

How to use the ajax() function in JQuery?

In my javascript file I have the following:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">

$.ajax({

    type: 'post',
    url: 'script.php',
    data: '',
    success: function(output) {
        alert(output[0])
    }

});

</script>

In my PHP file I have the following:

<?php

echo 'dog';
echo 'cat';

?>

Now I know I'm not passing any data through the ajax function, I just wrote the above to test one thing, that is:

When I alert output[0] I get the letter "d". Instead I want to be able to get "dog" and when I alert output[1] I want to be able to get "cat". How to achieve this?

Upvotes: 3

Views: 86

Answers (2)

rubayeet
rubayeet

Reputation: 9400

The PHP script is returning the string 'dogcat'. So when you're printing output[0], you'd obviously get the first character in the string.

You need to separate your words echoed from the PHP script with some kind of separator, such "|", and have the javascript split the output by that.

Upvotes: 1

Ken Franqueiro
Ken Franqueiro

Reputation: 10559

By default, given the response your call is receiving, jQuery is simply handing you the output as a string, in which case you'd have to do whatever string splitting/parsing as appropriate.

See http://api.jquery.com/jQuery.ajax/ and specifically the dataType property for more information. Depending on what you eventually intend to return from that service (JSON, XML, etc.), you'll want to set that property accordingly in the object you pass to the $.ajax call.

Upvotes: 3

Related Questions