0

I need some help creating Ajax, which I am not familiar with.

This is my actual PHP code that works:

$channels = array("channel1","channel2");
$arrlength = count($channels);
for($x = 0; $x < $arrlength; $x++) {


$ch = curl_init("somemyapiurl".$channels[$x]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$kanal = curl_exec($ch);  
$kanal_decode= json_decode($kanal); 
$ch_name= $kanal_decode ? 'true' : 'false';
echo "<button type='button' id= '".$channels[$x]."' class='btn btn-success'>"$channels[$x]."</button>&nbsp";

echo "<script>
if($ch_name == false) {
document.getElementById('$channels[$x]').className='btn btn-danger';
}  </script>";}}

So what I do here is actually for every value in $channels, I am checking api and create button on page, with default class success. If API returns value false , then with script I am changing button class.

Until now, I was doing refresh of page for some interval, but now I want to my page do this dynamically without refreshing it and I know I need ajax. Thank you in advance for the help.

cdomination
  • 605
  • 1
  • 7
  • 25
savke24
  • 19
  • 2
  • 4
    So write the code that does just that. But please don't us ask to do your work for you. – John Conde Jul 06 '16 at 12:02
  • i was trying but i am new with coding ,and as i say i dint "catch" Ajax that well.. – savke24 Jul 06 '16 at 12:03
  • 1
    @savke24 You should do some ajax tutorials first. Get to know jquery and it's pjax is a good start. – BRO_THOM Jul 06 '16 at 12:08
  • Welcome to SO. Please read [What topics can I ask about](http://stackoverflow.com/help/on-topic) and [How to ask a good question](http://stackoverflow.com/help/how-to-ask) And [the perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) And [How to create a Minimal, Complete and Verifiable example](http://stackoverflow.com/help/mcve) SO is **not a free coding or code conversion or tutorial or library finding service** You also have to show that you have made some effort to solve your own problem. – RiggsFolly Jul 06 '16 at 12:13

1 Answers1

1

The way AJAX works is you call out to a PHP file, it does some work, it uses PHP echo command to return data to the AJAX code block where it is received in the success function (or the .done() function) - and from there you now have the data returned by PHP in a variable. You can parse it (if a json object) and iterate through its elements to build HTML, or you can just directly inject the returned data (whether PHP returned HTML or just a couple of words or numbers).

This post has some very simple AJAX examples to review / experiment with.

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111