0

If a user scrolls to nearly the bottom more content shall be loaded with the help of an ajax request. This ajax request gets some data back (as a string in form of a json object - so it´s not an json object but only has to be parsed into one). Further Iactually use a plugin (JSON2HTML) which generates html after a template iterating through a json object.

JSON (before ajax):

var template = {"tag":"div","class":"parent","children":[
{"tag":"div","class":"tablee","style":"cursor:/*pointer*/;","children":[
    {"tag":"table","class":"post","children":[
        {"tag":"tbody","children":[
            {"tag":"tr","children":[
                {"tag":"td","class":"postby","children":[
                    {"tag":"img","class":"postppic","src":"propic\/${profilepic}","html":""}
                  ]},
                {"tag":"td","class":"postcontent","children":[
                    {"tag":"p","class":"postusername","children":[
                        {"tag":"a","class":"poster","href":"${username}-profile.php","html":"${username}"},
                        {"tag":"br/"},
                        {"tag":"span","class":"caption","html":"${caption}"}
                    ]}
                ]},
                ...

var data = [

    {
        "username":"momo",

        "profilepic": "momo_1.jpg",

        "caption":"", 

        "likes": "0",
    },

    {
        "username":"momo",

        "profilepic": "momo_1.jpg",

        "caption":"", 

        "likes": "0",
    },

    ...

];

var str = json2html.transform(data,template);

$("#rein").append(str);

Now if the user scrolls down more shall be loaded, the string formed like a json object is now echoed by the php the number of posts we already have in the docment is sent to (so we don´t get the same posts again...).

jQuery (ajax request when nearly bottom reached):

$(document).ready(function () {
    function loadMore()
    {
        var accountpar = $(".parent").length;
        $("h1").text(accountpar);
        $.ajax({
            url: 'homemore.php',
            type: 'post',
            data: {
                'account':accountpar
            },
            success: function(json) {
                var str = json2html.transform(json,template);
                $(str).insertAfter($('[class="parent"]').last());
                $("#rein").append();
                homejs();
            }
        });
        $(window).bind('scroll', bindScroll);
    }

    function bindScroll(){
        if($(window).scrollTop() + $(window).height() > $(document).height() - 75) {
            $(window).unbind('scroll');
            loadMore();
        }
    }

    $(window).scroll(bindScroll);
});

And that works fine to until the success is reached and data should be received. (homejs() is the jquery function that is loaded after document.ready so the first jquery written in the document.) This data looks like that (according to my google chrome browser):

var data = [

{
    "username":"momo",

    "profilepic": "momo_1.jpg",

    "caption":"",

    "likes": "0",
},

{
    "username":"momo",

    "profilepic": "momo_1.jpg",

    "caption":"",

    "likes": "0",
},

...

];

So something was received but it couldn´t be parsed? Cause that´s what console log says (is it called so? like where you can see all the errors...):

VM5454:2 Uncaught SyntaxError: Unexpected token v

json2html.transform @ json2html.js:33

//Normalize strings to JSON objects if necessary
var obj = typeof json === 'string' ? JSON.parse(json) : json; //line 33

$.ajax.success @ home.php:423

var str = json2html.transform(datanew,template); //line 423

j @ jquery-1.11.3.min.js:2

k.fireWith @ jquery-1.11.3.min.js:2

x @ jquery-1.11.3.min.js:5

b @ jquery-1.11.3.min.js:5

So can anyone of you figure out why it isn´t working? I hope I provided enough of information... Please help :']

Moritz
  • 745
  • 1
  • 10
  • 32
  • see dev console if there is any error or add error call back to catch the error . – Matin Kajabadi Apr 01 '16 at 16:37
  • could you write an answer on how to do that. I´m pretty new to jQuery and tried to provide as much information as I could... sorry if that´s a stupid question... @Matt.k – Moritz Apr 01 '16 at 16:47
  • You can use .fail() in the Ajax call. At this jQuery page, search for the phrase "deprecation notice" and the code example is right below that yellow box. Make sure that you use a parameter, like: `.fail(function(error) { console.log(error); })` See: http://api.jquery.com/jQuery.ajax/ – Clomp Apr 01 '16 at 17:09

2 Answers2

1

You can replace your ajax with this to see what you get back

var accountpar = $(".parent").length;          
var data = {account:accountpar} ; 
  console.log('data',data);
 $.ajax({ 
        url: 'homemore.php',
        data: data ,
        type: 'post',
        dataType: "json",
        success: function(response) {
                  console.log(response);
         },
        error: function(jqXHR, exception) {
               if (jqXHR.status === 0) {
                   alert('Not connect.\n Verify Network.');
                } else if (jqXHR.status == 404) {
                    alert('Requested page not found. [404]');
                } else if (jqXHR.status == 500) {
                    alert('Internal Server Error [500].');
                } else if (exception === 'parsererror') {
                    alert('Requested JSON parse failed.');
                } else if (exception === 'timeout') {
                    alert('Time out error.');
                } else if (exception === 'abort') {
                    alert('Ajax request aborted.');
                } else {
                   alert('Uncaught Error.\n' + jqXHR.responseText);
                }
         }
  });
Matin Kajabadi
  • 3,414
  • 1
  • 17
  • 21
  • Ok, I think due to this excerpt of code we´re a step further. It now says: Requested JSON parse failed. – Moritz Apr 01 '16 at 17:18
  • The reason is because you return back your data as a string or another format , it is not really Json, so the parser fails when parsing it. you can take off `dataType: "json` property to see if you get any data – Matin Kajabadi Apr 01 '16 at 17:28
1

Have you tried running all of the JSON through http://www.jslint.com to see if it's valid JSON?

The Unexpected token error in the json2html.transform @ json2html.js:33 file suggests that something is broken in the JSON objects. (There isn't any way for us to check them, as all 3 examples above have ellipsis in them.)

Or what about passing the json in the success function through the JSON.parse() method? See the answer at this page: I keep getting "Uncaught SyntaxError: Unexpected token o"

Update: Here is a jsfiddle for you to try out. (Scroll to the very bottom of the JS in the fiddle.)

HTML:

<div id="output1"></div>
<div id="output2"></div>

JavaScript Example 1 - Using Stringified JSON:

If your PHP file outputs this as a string, then you have to run JSON.parse on it.

var json = '[{"username": "momo", "profilepic": "momo_1.jpg", "caption": "", "likes": "0"}]';

var HTML = json2html.transform(JSON.parse(json),template);
$('#output1').html(HTML);

JavaScript Example 2 - Using JSON:

If your PHP file outputs this JSON format, then you don't need the JSON.parse method.

var json = [{"username": "momo", "profilepic": "momo_1.jpg", "caption": "", "likes": "0"}];

var HTML = json2html.transform(json,template);
$('#output2').html(HTML);

You have to see what your web server is outputting.

If you see these errors...

Unexpected token ] ... then the code is using a string (not JSON like example 1) & it has a comma before the closing bracket and it should be removed. Then run JSON.parse() on the string, to convert it to an object.

Unexpected token o ... then the code is trying to run JSON.parse() on a valid JSON object. To fix it, remove the JSON.parse() method.

Community
  • 1
  • 1
Clomp
  • 3,168
  • 2
  • 23
  • 36
  • After using Matt k. approach I found out that the "requested JSON parse failed" if that woudl help you. – Moritz Apr 01 '16 at 17:21
  • But I can see an x with a red background (google chrome´s symbol for error) at the end of the data that was received being displayed right behind the sqaure bracket and the semicolon: "]; **x**" – Moritz Apr 01 '16 at 17:26
  • Can you make a http://jsfiddle.net code example, so that we can see what the 3 full JSON objects look like? – Clomp Apr 01 '16 at 17:29
  • We'd need to check that to see if it contains any munged JSON formatting. I've seen large complex nested JSON objects, which came out of a No SQL DB & weren't properly formatted when they were inserted into the DB. So they couldn't be eval()'d using JSON.parse(); They were strings which looked like JSON, but were simply improperly formatted strings. This issue seems similar to that one. – Clomp Apr 01 '16 at 17:38
  • I just echoed everything out with php, so that it looked like a json string. That worked at least in the original file, where there´s a limit of posts that should be shown which is the reason why I need the ajax now. – Moritz Apr 01 '16 at 17:43
  • Take the commas out of each section after the `"likes": 0,`. You can run the code through http://jsbeautifier.org to clean it up & http://jslint.com to verify when it's good. Typically browsers like IE don't like that trailing comma, but other modern browsers are more forgiving. However, json2html.js doesn't like the trailing commas. So you'll need to remove them. Also remove it at the end of the string, before the bracket. – Clomp Apr 01 '16 at 17:56
  • Removed those after likes but nothing happened and I can't remove the last one after the curly bracket cause it's a while loop :/ – Moritz Apr 01 '16 at 18:06
  • The php echo function returns a string, not JSON. So run JSON.parse() on it. Use example 1 in my updated answer. http://php.net/manual/en/function.echo.php – Clomp Apr 01 '16 at 20:56
  • you were right, i tried it out with many strings now and found out that the comma before the square bracket is triggering the error cause json2html automatically provides json parsing... But then there´s another problem how do I remove the last comma before the sqaure? – Moritz Apr 02 '16 at 04:19
  • Try a string replace on it, before it runs through the JSON.parse() code in json2html. Like `json = json.replace(/,\s*]/,']');` The \s in the regEx is a space character. The * is zero or more times. So it should replace both ",]" and ", ]" with a single bracket "]" character. – Clomp Apr 02 '16 at 06:39