Ahmad Azizov
Ahmad Azizov

Reputation: 166

Get value of php file from the server using AJAX

I made a php page that gets all the files(file names) from a particular directory. I want to use ajax to get the value from the php file. I have never used ajax. Can anyone suggest me a way to achieve this?

My php code is pretty simple i guess. It will be used in a dropdown, thats why there is "option".

    <?php

foreach(glob('../files/videos/*.*') as $filename){
     $name1 = str_replace('../files/videos/', '', $filename);
     $ext = pathinfo($name1, PATHINFO_EXTENSION);
     $notneeded=".".$ext;
     $name = str_replace($notneeded, '', $name1);

     echo "<option  value='".$name1."'>".$name."</option>"."<br/>";


 }

 ?>

Thanks!

Upvotes: 0

Views: 771

Answers (2)

Ahmad Azizov
Ahmad Azizov

Reputation: 166

      <div style="float:left;" id="success"></div>
<div id="error"></div>
<script>
$("#success").load("yourfile.php", function(response, status, xhr) {
  if (status == "error") {
    var msg = "Sorry but there was an error: ";
    $("#error").html(msg + xhr.status + " " + xhr.statusText);
  }
});
  </script>

Upvotes: 0

Leeish
Leeish

Reputation: 5213

You can simply use echo, but a more useful way would be to encode the results in a JSON string. However you can do what you want like so.

$.get('url/to/php/file.php',function(data){
    $('select').html(data);
});

This is a jQuery solution of course just to demonstrate the simplicity of what you are trying to achieve. You can write all of this in vanilla javascript. Basically a XHR request, and then inject the returned data into the select element in your page.

Upvotes: 1

Related Questions