jeff
jeff

Reputation: 387

php get variable from ajax

I am using ajax to send parameters and consult them, everything is functional only when obtaining the array with the records does not allow me to display the values independently

this is index.php

<script>
    $(document).ready(function(){
        $("#Montox").change(function(){
            var varmonto = $("#Montox").val();
            $.ajax({
                method: "post",
                url: "ajax/calc.php",
                data: {monto:varmonto}
            })
            .done(function(data){

                    $('#chattext').html(data['username1']);
                    $('#chattext2').html(data['username2']);/*I NEED TO SHOW THE DATA 'username2'*/

            });
        });
    });
</script>

this is my calc.php

<?php
echo json_encode(array('username1' => "luis", 'username2' => "jose"));

?>

Upvotes: 1

Views: 101

Answers (4)

JuJoGuAl
JuJoGuAl

Reputation: 119

You need add Json TYPE in your ajax header dataType: "json" it will allow you to get json text and parse it.

And for the next time, post the RESULT of (data) if you wanna a real help

Upvotes: 1

Jos&#233; A. Zapata
Jos&#233; A. Zapata

Reputation: 1297

Since you're expecting a JSON result from your server, you need to set the dataType property on your ajax call to return a Javascript object that you can manipulate. Like this:

<script>
    $(document).ready(function(){
        $("#Montox").change(function(){
            var varmonto = $("#Montox").val();
            $.ajax({
                method: "post",
                url: "ajax/calc.php",
                data: {monto:varmonto},
                dataType: 'json'
            })
            .done(function(data){
                    // 'data' is a javascript object, not an array!

                    $('#chattext').html(data.username1);
                    $('#chattext2').html(data.username2);/*I NEED TO SHOW THE DATA 'username2'*/

            });
        });
    });
</script>

That should work.

Upvotes: 2

user11897373
user11897373

Reputation:

Force JSON object inside the ajax with:

$.ajax({
     method: "post",
     url: "ajax/calc.php",
     data: {monto:varmonto},
     dataType: "json" //<--- HERE
})

Upvotes: 1

Barmar
Barmar

Reputation: 781004

You're not parsing the response as JSON. You can:

  1. Use the dataType: 'json' option to $.ajax() to make it parse it as JSON automatically.
  2. Call header("Content-type: text/json"); in PHP to tell jQuery that the response is JSON.
  3. Use data = JSON.parse(data) in the .done() function to parse it explicitly.

Upvotes: 3

Related Questions