LukasA
LukasA

Reputation: 109

AJAX response, getting undefined(in console normal JSON)

The first

<form id="tweetInsert"  action="<? echo URL ?>homescreen/ajaxInsertTweet/" method="post">
    <textarea name="tweetText" rows="3" cols="40"></textarea>
    <button type="submit" name="submitTweet">Tweet</button>
</form>
<div class="row">
    <div id="tweets">
    </div>
</div>

The second

function ajaxInsertTweet()
{
    $tweet = $_POST["tweetText"];
    $stmtInsertTweet = $this->db->prepare("INSERT INTO tweets (tweet) VALUES (:tweet)");
    $stmtInsertTweet->execute(array(':tweet' => $tweet));
    $data = array('tweet' => $tweet );
    //print_r($data);
    echo json_encode($data);
    exit;
    //header("Location:".URL."homescreen");
}

The third

$("#tweetInsert").submit(function(ev){

    ev.preventDefault();
    var url = $(this).attr("action");

    var data = $(this).serialize();

    console.log("Output: " + data);

    $.post(url, data, function (o){
        $("#tweets").append("<div>"+o.tweet+"</div>");
    });
});

I try to load a post instantly inside of a div without refreshing the page, so i load a function on my javascript that does the post and stops the form from submit. I got a json array-> in my console, there is a json array like: {"tweet","HERE IS THE POST OR SOMETHING ESLE"} but inside the div it gets called undefined. In my console.log("Output: "+data) I got something like this:

Output: tweetText=fgsdgfh

Question: Why do i get a undefined inside my div? it should display the tweet

Upvotes: 0

Views: 118

Answers (3)

Phil
Phil

Reputation: 60

$.post(url, data, function (o){
    $("#tweets").append("<div>"+o.tweet+"</div>");
});

The input parameter to the function is what is returned from the page. So o is your returned HTML. It is a string, not an object.

So the correct format would be

$.post(url, data, function (o){
    $("#tweets").append("<div>"+ o +"</div>");
});

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

Try adding dataType argument to $.post.

It doesn't appear you are setting a Content Type header at server so response may be being interpreted as text.

This will tell $.post to expect json and to parse it internally

$.post(url, data, function (o){
    $("#tweets").append("<div>"+o.tweet+"</div>");
},'json');

Upvotes: 1

Rick Burns
Rick Burns

Reputation: 1546

Change this:

$.post(url, data, function (o){
  $("#tweets").append("<div>"+o.tweet+"</div>");
});

to:

$.post(url, data, function (o){
  $("#tweets").append("<div>"+o.tweetText+"</div>");
});

Upvotes: 0

Related Questions