1

I use jQuery Ajax with php,I get value in json encode in php file but I cant decode in result

<script>
    jQuery(document).ready(function() {
        jQuery(".upload").click(function(e) {
            e.preventDefault();
            var data = {};
            jQuery(".ajax_elements").each(function(_, elem) {
                data[this.id] = this.value;
            });
            jQuery.ajax({
                type: "POST",
                url: "map.php",
                data: data,
                cache: false
            }).done(function(result) {
                alert(result);
            });
        });
    });
</script>

PHP code

 echo json_encode(array('URL'=>'http://test.com'));

here I get {URL:http://test.com} in alert but how to get value of this URL?

I tried jQuery.parseJSON(result); but it shows error in console

1
  • 1
    Your code missing dataType: "json" Commented Jan 6, 2014 at 15:37

4 Answers 4

2

Try this,

jQuery(document).ready(function() {
    jQuery(".upload").click(function(e) {
        e.preventDefault();
        var data = {};
        jQuery(".ajax_elements").each(function(_, elem) {
            data[this.id] = this.value;
        });
        jQuery.ajax({
            type: "POST",
            url: "map.php",
            data: data,
            cache: false,
            dataType: "json" // add this line in your code
        }).done(function(result) {
            alert(result.URL);
        });
    });
});

Set dataType:"json" for URL alert result.URL in your Ajax success function .

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

Comments

0

You parse it like this:

alert(result.URL);

Comments

0

TO build on what @Leonardo answered above. When you pass to jquery the json_encoded variable it is already interpreted as an OBJECT on your javascript code. So you just reference it as such.

Comments

0

You have to parse with parseJSON, use this:

}).done(function(result) {
     var res = $.parseJSON(result);
     alert(res.URL);
});

now in res you have what you're sending in JSON format from php, if you alert "res.URL" you'll get "http://test.com". You can pass other parameters and call them using res.parameterNameFromPhp

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.