2

I am writing some kind a rest API for the first time, so I need a little help. I found few solutions for my problems here on stackoverflow and I managed to solve them. But now I came to another one and could not find a solution.

First of all, js file code.

$.getJSON('test.php', function(data) {
    console.log(data);
    articles = data;
    return articles;            
});

This is js file, from which I send request to php file and then get data back. The thing is, data I get back from php looks fine in browser console when I log it, all data is there. But when I try to use that data on page (with my return statement), it does not work. If I replace return articles row with

return [{"name":'Name goes here',"description":'Description goes here'}];

it works fine on a page. This is bothering me, because in browser console I can see all the objects that have been returned from php file, but they do not work on page. I hope any of you can help me. I am pasting my php file below.

$json = array(
        array(
            "name" => 'Name goes here',
            "description" => 'Test description.',
            "link" => 'articles/articleName',
            "img" => '../images/article1.jpg'
        ),
        array(
            "name" => 'Name goes here 2',
            "description" => 'Not ready yet',
            "link" => '#',
            "img" => ''
        ),
        array(
            "name" => 'Name goes here 3',
            "description" => 'Not ready yet',
            "link" => '#',
            "img" => ''
        )
    );

    $jsonstring = json_encode($json, JSON_PRETTY_PRINT);
    echo $jsonstring;

1 Answer 1

2

The problem is you're returning in the async part of your $.getJson call.

What you have:

function myFunction()
{
    $.getJSON('test.php', function(data) {
        console.log(data);
        articles = data;
        return articles;            
    });
}
var articles = myFunction();

myFunction runs, and returns nothing, then later the $.getJSON gets its response and doesn't have anything to do with it.. Return doesn't mean much there since the code has 'moved on'

What you need to do is handle the data inside the async part of getJSON (or pass in a function to do stuff in there)

What you need:

function myFunction()
{
  $.getJSON('test.php', function(data) {
    console.log(data);
    articles = data;          

    //do something with articles
    //maybe set a div equal to them
    $("#myArticles").innerHTML = articles;

    //or call a function with articles as a param
    doSomethingCool(articles);
  });
}

function doSomethingCool(arts)
{
  alert("You have articles: " + arts);
}

You can even pass in the thing you want to do as a param

function myFunction(callback)
{
  $.getJSON('test.php', function(data) {
    console.log(data);
    articles = data;          

    callback(articles);
  });
}


myfunction(alert);  //will alert with the articles

//define the callback function 'on the fly'
myfunction(function(articlesFromJson) {
  if(articlesFromJson.length > 2)
    alert("wow 2+ arcticles");
});

The above would grab the articles twice, and do something different with the each time.

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

5 Comments

Thank you for quick reply. I tried your option and it is the same as before. In both cases I get JSON from php file, but looks like there is a problem because I can't use that data on page. (in console log the objects are visible!) The thing is, I was asked by my friend to connect his page with database and since this is my first time doing it with api like this I do not know how these kind of pages work. It automatically reads return from this function and it generates articles on first page. But with my return there is only blank space. If I insert that JSON row I mentioned above, it works.
Hmm, that's definitely the way to do it. How are you trying to "get the data on the page"? Are you setting the content of a div with the data?
<a href="/{{lang}}/{{article.link}}" ng-repeat="article in articles" class="article"> <article class="aktualno-box"> <div class="aktualno-inner"> <div class="aktualno-bg" style="background-image:url({{article.img}})"></div> <div class="center ontop"> <p class="aktualno-title">{{article.name}}</p> </div> <div class="hidden-description"> <p class="hidden-text">{{article.description | articledesc : 120}}</p> Sorry for maddness with code.. So this is how he gets data, there must be some js back there to handle these calls.
Looks like you're using angular, you need to set $scope.articles in the async part of $.getJSON
Yep it is angular thing. Will check few tutorials and fix it.Thank you for your help!

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.