Joanmi
Joanmi

Reputation: 442

Ajax Sending data (JSON) throught POST

Someone can see why it shows the error Maximum call stack size exceeded? And why is not working the script? UPDATE: I added the php code that don't put the value "domain" and I updated the JS code.

    function addentrys() {
    var nwentry =  {};
    el = document.getElementById('addname').value;
    eldmn = document.getElementById('adddomain').value;
    nwentry.name = el;
    nwentry.domain = eldmn;
    $.ajax({
        type: 'POST',
        url: 'api/domain',
        dataType: 'json',
        data: nwentry,
        succes: function(data) {
            alert('Ok')
        }
    })
}

php:

//ADD
$app->post('/domain', function () {
    $jsonContents = file_get_contents('data/data.json');
    $name = $_POST['name'];
    $domain = $_POST['domain'];
    $data = json_decode($jsonContents, true);
    $last_item = end($data);
    $last_item_id = $last_item['id'];
    $data[] = array(
        'name' => $name,
        'domain' => $domain,
        'id' => $last_item_id+1
    );
    $json = json_encode($data);
    file_put_contents('data/data.json', $json);
    return $this->response->withRedirect('../index.html');
});

Upvotes: 1

Views: 60

Answers (3)

Rajesh Kumar
Rajesh Kumar

Reputation: 2503

You are passing control object not the value to ajax. try below code

    function addentrys() {
    var nwentry =  {};
    el = document.getElementById('addname')
    nwentry.name = el.value;
    var data = JSON.stringify(nwentry)
    $.ajax({
        type: 'POST',
        url: 'api/domain',
        dataType: 'json',
        data: (nwentry),
        succes: function(result) {
            console.log(result)
         }
     })
  }

Upvotes: 1

Maleen Abewardana
Maleen Abewardana

Reputation: 14572

Try following code. Check success function typo and sending data varaible, not nwentry object

function addentrys() {
var nwentry =  {};
el = document.getElementById('addname')
nwentry.name = el;
var data = JSON.stringify(nwentry)
$.ajax({
    type: 'POST',
    url: 'api/domain',
    dataType: 'json',
    data: data,
    success: function(result) {
        console.log(result)
    }
  })
}

Upvotes: 0

Rehman
Rehman

Reputation: 11

function addentrys() {
    var nwentry =  {};
    el = document.getElementById('addname').value;
    nwentry.name = el;
    var data = JSON.stringify(nwentry)
    $.ajax({
        type: 'POST',
        url: 'api/domain',
        dataType: 'json',
        data: (nwentry),
        succes: function(result) {
            console.log(result)
    }
    })
}

Upvotes: 1

Related Questions