user5778346
user5778346

Reputation:

Ajax always returns the length of JSON

Hello could someone explain why ajax always returns the length of JSON?

$(document).ready(function () {
   $("#addElem").click(function (e) {
       e.preventDefault();
       var val1 = $('#addname').val();
       var val2 = $ ('#addprice').val();
       $.ajax({
           type: 'POST',
           url: 'server.php',
           dataType:"json",
           data: {name: val1, action:'set', price: val2},
           success: function( data ){
                var ident = $('#text').append( data );

           }
       }).done(function(data) {
            alert(data)
       });

   });
});

EDITED: here is a server.php https://jsfiddle.net/nvy2cavz/

SOLVED It was not my mistake .It was a Server.php deal . THE SERVER.php always work only in that way. THANK YOU ALL

Upvotes: 0

Views: 64

Answers (2)

Vüsal
Vüsal

Reputation: 2706

$.append function receives (htmlString or Element or Text or Array or jQuery). How can you use json object $.append? Your data object in success function is javascript object. I think the problem is hidden here.

Upvotes: 1

Vivek Athalye
Vivek Athalye

Reputation: 2979

Your PHP code is returning the length of items array. That's what you are getting in data. It's not the length of JSON but length (number) returned by your server side code.

// rest of the code
if($_POST['action'] == 'set') {
    if(isset($_POST['name']) && isset($_POST['price'])){
        $item = [
            'name' => $_POST['name'],
            'price' => $_POST['price']
        ];
        $items[] = $item;
        file_put_contents('items.json', json_encode($items));
        $return = json_encode(count($items)-1); //<<<<<<<<<<<<< Change here if you want
    } else {
        $return = json_encode(['error' => 'Wrong item details']);
    }
}
// rest of the code

Upvotes: 1

Related Questions