CORS problem using ajax

I’ve started with the Wikipedia Viewer project, and trying to get the json files from the Wikipedia API. I’m doing this using $.ajax, but I get a CORS error. So I saw in MediaWiki CORS manual that I can use it properly to get the permission, just if $wgCrossSiteAJAXdomains is enabled, like:

$wgCrossSiteAJAXdomains = array( some url );

and after that specifying the same origin the request is sent from in the $.ajax code. The problem is that when I write the code exactly as it is in my javascript code (inside a general function the code works by) (or just putting a ‘*’ as a value), I get this console error : “Uncaught ReferenceError: array is not defined”. This is the code :

function textBox(){

   $wgCrossSiteAJAXdomains = array( some url ); //This line got the error
  
  var string = document.getElementById("string").value;
  var content = "";
  
   $.ajax ({
        url: "https://en.wikipedia.org/w/api.php?action=query&list=search&srprop=snippet&format=json&srsearch=" + string,
     
        datatype: "json",
        origin : 'https://s.codepen.io',
        success: function (json) {
          
          
          for (var key in json["query"]["search"]){
      content += "<h1 style = \"color : white ; font-size : 30px ; font-family : Monospace\">" + json["query"]["search"][key]["title"] + "</h1>" + "<h1 style = \"color : gray ; font-size : 17px ; font-family : Monospace\">" + json["query"]["search"][key]["snippet"] + "<i>" + "... see more" + "</i>" + "</h1>" + "<br> <br>";
    }
          $("#general").html(content);
          
        }})
}

Am I putting the $wgCrossSiteAJAXdomains line in the wrong place? I’ve tried declaring ‘array’ as an array variable, but it doesn’t work either. Please help me :frowning:

You had time to edit my post, but you couldn’t had time to help me sorting this out? :expressionless:

In fairness, a mod’s job is not to answer every question, but we do have a canned response that allows us to let you know how we formatted your code so that other people can read it.

If others have the time to help you, having formatted code will help them help you.

1 Like

Could you share the link to your Codepen for this?

It’s hard to figure what some of your variables mean without the larger context.

In your problematic line, the correct syntax for initialising an array is new Array('item 1', 'item 2'), unless you’ve made your own function called array() that we cant see?

Also, the parameter/s you passed to it won’t work either. If the array is being passed in from a variable, the space in some url makes it invalid. You’d need the array to be called something acceptable, like some_url. That said, I’m not sure why a single url would be passed in as an array object either.

Please clarify your thinking for us so I can try to figure out what you want to do, and why it’s not working.