Anonymous
Anonymous

Reputation: 1094

How to get updated score without page refresh in PHP using API

I have PHP code that updates score using API accompanied with a key by file_get_content PHP function.

I am getting the score, but every time I have to reload the page to get the updated score.

Can anyone tell me how to refresh the score without page reload? I know PHP server-side script language so definitely I have to refresh my own.

Is there any way to implement node.js here?

PHP code:

<?php
$var='xyzxyzxyz'; //My api key

    $cricketMatchesTxt = file_get_contents('http://cricapi.com/api/cricket/?apikey='.$var.' '); // change with your API key
    $cricketMatches = json_decode($cricketMatchesTxt);

    foreach($cricketMatches->data as $item) {
?>
    <h4><?php echo($item->title); ?></h4>
<?php } ?>

Upvotes: 0

Views: 561

Answers (2)

Quentin
Quentin

Reputation: 944301

To change the page in the browser, without loading a new one, you must use client-side JavaScript. There is no way for server-side code to change data it sent in the past.

If you want to get new data from the server (which could be provided with Node.JS but since you are already using PHP, I see no reason to change that), then you need to use Ajax (i.e. a JavaScript triggered HTTP request that does not result in the browser navigating to a new page) followed by DOM Manipulation to insert the data.

Typically you would use the XMLHttpRequest or fetch APIs (native to browsers) for, or libraries like Axios or jQuery (which wrap those APIs), for Ajax.

Then you can use Native DOM or a library like jQuery to change the content of the page the user is looking at without loading a whole new one.

Upvotes: 1

Igor Ilic
Igor Ilic

Reputation: 1368

You could use jQuery with ajax to make a call to your php file that will return the json response from the cricapi server to you and then replace the old data with the new one.

As this question is too broad and with little code to help you in more detail I can only point you to: https://api.jquery.com/jQuery.ajax/ so you can do your own research and see how to implement it.

This example might help you to understand how ajax works: https://www.tutorialscollection.com/jquery-load-how-to-use-jquery-ajax-load-method-with-examples/

Upvotes: 1

Related Questions