3

Here I have sme .ajax function that work well:

 $( document ).ready(function() {
$('a#kom').click(function (e) {
    var tabela = 'parcele';
      $.ajax({
            url: "getComments.php",
            type: "POST",
            async: true, 
            data: { ajdi:ajdi,tabela:tabela}, //your form data to post goes here as a json object
            dataType: "html",

            success: function(data) {
            console.log(data);  
            },
            error:function(data) {
            console.log(data); 
            }
        });

        });
        }); 

and this function produce this JSON:

[{"datum":"2014-05-22","komentar":"Testiranje za komentare da vidimo kako moze da sluzi, dali radidobro, bla bla bla bla bla bla bla bla bla bla bla bla ... ..."}] 

Iknow its a basic question but I cant find any good resource... How I can into .ajax function when function is success to create this html:

'<div class="notes">
        <h4>Tekst zaglavlje</h4>
        <h5>'+datum+'</h5>
        <p>'+komentar+'</p>
    </div>'

for every object I get from JSON... so like that:

            success: function(data) {
            // CREATE A HTML FROM JSON DATA FOR EACH JSON OBJECT. HOW?
            console.log(data);  
            },

UPDATE WITH PHP

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { 

    try {


     $result = $db->prepare("SELECT * FROM komentari WHERE id_utabeli=:ajdi AND tabela=:tabela");
     $result->execute(array(':ajdi' => $_POST['ajdi'], ':tabela' => $_POST['tabela']));
    $result = $result->fetchAll(); 

     $temp = array();
foreach($result as $r) {

          $temp[] = array('datum' => (string) $r['datum'], 'komentar' => (string) $r['komentar']); 

        }
    $table = $temp;
    $jsonTable = json_encode($table);
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    echo $jsonTable;
}
    else { 
echo 'ERROR 404';
  }  
1

4 Answers 4

3

You have a wrong dataType that should be:

dataType: "json", 

because response is json not a html.

In your success function do this:

success: function(data) {
    var htm = '';  
    $.each(data, function(i, resp){
        htm +='<div class="notes">' + 
                 '<h4>Tekst zaglavlje</h4>' +
                 '<h5>'+resp.datum+'</h5>' +
                 '<p>'+resp.komentar+'</p>' +
             '</div>';
    }); 
    $('yourContainer').html(htm);
},

As your response seems to be an array [{},{}....] or multiple javascript objects so to produce such html markup you have to loop in that array with $.each() method and declare one blank var htm=''; before $.each() iteration and concatenate the resulting html out of your json, then place at the position of your container which can hold the produced html.


Find a Demo @ Fiddle

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

9 Comments

I get; Uncaught TypeError: Cannot use 'in' operator to search for '162' in [{"datum":"2014-05-22","komentar":"Testiranje za komentare da vidimo kako moze da sluzi, dali radidobro, bla bla bla bla bla bla bla bla bla bla bla bla ... ..."}]
why this is not a safe way, open XSS?
Then you have posted a wrong json object. Then it might be {},{}... instead of [{}, {} ...].
@gmaestro why do you have a dataType: "html"? Wouldn't it be "json".
Is this now a safe way to create HTML from JSON?
|
2

Since you're using jquery, you can do this like follows:

$( document ).ready(function() {
    $('a#kom').click(function (e) {
        var tabela = 'parcele';
        $.ajax({
            url: "getComments.php",
            type: "POST",
            async: true, 
            data: { ajdi: ajdi, tabela: tabela },
            dataType: 'json',
            success: function(data) {
                console.log(data);  

                $.each(data, function(i, item) {
                    // create html
                    var elem = '<div class="notes">
                                    <h4>Tekst zaglavlje</h4>
                                    <h5>' + item.datum + '</h5>
                                    <p>' + item.komentar + '</p>
                                </div>'

                    $('body').append(elem); // append the item
                });
            },
            error: function(data) {
                console.log(data); 
            }
        });
    });
});

9 Comments

say: Uncaught SyntaxError: Unexpected token ILLEGAL
I change only this: $('#komenatri').append(elem);
extended it a little bit. please try again.
what that means: Uncaught TypeError: Cannot use 'in' operator to search for '162' in [{"datum":"2014-05-22","komentar":"Testiranje za komentare da vidimo kako moze da sluzi, dali radidobro, bla bla bla bla bla bla bla bla bla bla bla bla ... ..."}]
changed the code. it was not expecting json thus data was not an object. now it should work.
|
1

Your success function should look like this:

success: function(data) {
    notes_div = $("<div/>");
    hfour = $("<h4/>").text("Tekst zaglavlje");
    hfive = $("<h5/>").text(data.datum);
    para = $("<p/>").text(data.komentar);
    notes_div.append(hfour).append(hfive).append(para);
    $('#komenatri').append();
},

Other answers provided that just build your HTML as a string are not safe. They open you up to XSS (google it ;) ) but we fix that by making elements as JQuery objects and setting their .text() which makes the resultant content HTML safe.

You should also run your data through htmlspecialchars() in PHP before outputing it.

change:

$temp[] = array('datum' => (string) $r['datum'], 'komentar' => (string) $r['komentar']);

To

$temp[] = array('datum' => htmlspecialchars( (string) $r['datum'] ), 'komentar' => htmlspecialchars( (string) $r['komentar']) );

This will prevent users from injecting their own HTML into your pages with their comments.

4 Comments

yes but this is incomplete answer, becuse I need to make html for every JSON object also I need to add it into ID=komentari
hm, dont ork, just nothing happend... is there some sintaks error?
@gmaestro I've changed my answer so that the resultant HTML goes into '#komentri' can you clarify. What do you mean by every object returned? in the success function does data contain info for one form or all forms??
@gmaestro you tell me. If you open your web developer console do you get an error? Does an element with the id 'komenatri' exist?
0
success: function(data) {
    for(var i = 0, ceiling = data.length; i < ceiling; i++) {
        document.getElementById("komenatri").innerHTML += 
            "<div class=\"notes\"><h4>Tekst zaglavje</hr><h5>" + 
            data[i].datum + 
            "</h5><p>" + 
            data[i].komentar + 
            "</p></div>";
    }
}

1 Comment

I'm not the downvoter but I'd imagine it's because you've provided a pure JavaScript onlclick answer when what's needed is clearly a JQuery one with an AJAX success function. Bit nasty not leave a comment first though...

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.