1

I'm trying to use an ajax request on a php file hosted on an URL. And i can't retrive datas from it.

My code :

Ajax request :

  $.ajax({
  type: "GET",
  url: "http://urltomysite.com/api/discogs/search.php",
  datatype: "html",
  data: dataString,
  success: function(data) {
    console.log(data);
    }
  });

Php file :

<?php
echo 'i am a string';
?>

the console log just returns nothing.

Is someone have an idea to solve my problem?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • 1
    Where does `dataString` come from? Is it actually running your PHP or not? – droopsnoot Jun 05 '20 at 12:20
  • `data:datastring` is of no use here for just this test. Click the `F12` key to [reveal the browser's developer tools](http://jayblanchard.net/basics_of_jquery_ajax.html). Look for the Network tab, then try the AJAX request. You should see what is sent and what is returned. – Jay Blanchard Jun 05 '20 at 12:21
  • OK so i remove the parameter "data: dataString" and i see the ajax request in network from developer tool. But the request status is fail ... – jcalcada-atoswap Jun 05 '20 at 12:27
  • 1
    What do you mean by "fail"? What's the error message assigned to that failing request? – Nico Haase Jun 05 '20 at 12:31
  • it's apparently a problem with CORS. – jcalcada-atoswap Jun 05 '20 at 12:35
  • If it's CORS here's what you need then https://stackoverflow.com/questions/8719276/cross-origin-request-headerscors-with-php-headers – Machavity Jun 05 '20 at 12:42

1 Answers1

-1

This should work as detailed in this question.

<?php echo 'apple'; ?> is pretty much literally all you need on the
server.

and

$.ajax({
  type: "GET",
  url: "http://urltomysite.com/api/discogs/search.php",
  data: queryParams,
  success: function(data) {
   alert(data); // apple
  }
});

You can also simplify with jQuery.get. There might be other things like Same-Origin policy at play here if you're requesting a page from another domain. This will usually mean that you need to add Access-Control-Allow-Origin header to your API. That would depend on the server specifics. And there is no info about it here. So I would assume nginx. This would mean adding add_header 'Access-Control-Allow-Origin' 'requesting origin domain'; to your config. More about CORS here. Another solution is to add the header within PHP script for example:

header('Access-Control-Allow-Origin: client.com');
header('Access-Control-Allow-Methods: GET');
header("Access-Control-Allow-Headers: X-Requested-With");
fsacer
  • 1,382
  • 1
  • 15
  • 23