+ 19

How the AJAX workes

Hay freinds I had writen a code to fetch data using API. But the data is not shown here. When I had writen same code in anWriter app the code gave me proper output. Before 1 week I tried to fetch data when I was learning then it was working properly too. But now 😬 Is this a sololearn problem ? Or I am doing something wrong. If I am doing wrong please help me. And tell me too what is it showing for you. https://code.sololearn.com/W4NEkMdBahDL/?ref=app

13th Sep 2020, 12:20 AM
Ayush Kumar
Ayush Kumar - avatar
23 Respuestas
+ 5
ok so your origin wasn't https://solocode.azurewebsites.net but it was null. https://solocode.azurewebsites.net is the origin every time I tested in a web browser. I updated my proxy to be much more flexible on origin of the request. EDIT: 8 days after answering this question, I removed my code at: https://code.sololearn.com/W1QjjZdKeidc/ because it was mostly for this question. I'll keep the proxy up for another week or so and hopefully you find another host.
14th Sep 2020, 9:12 AM
Josh Greig
Josh Greig - avatar
+ 5
This is the message I get: VM6:19 Mixed Content: The page at 'https://code.sololearn.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://newsapi.org/v2/top-headlines?country=in&category=science&apiKey=35f1d301d058490aa16fbb70da3378b7'. This request has been blocked; the content must be served over HTTPS. The problem is related to something called CORS. The API needs to set a special HTTP response header to let JavaScript make use of results from it. Did anWriter relay the API request for you so that AJAX hit a server with the same domain name/origin?
13th Sep 2020, 1:08 AM
Josh Greig
Josh Greig - avatar
+ 5
Yes Josh Greig it worked well in the anWriter. see the data coming property in anWriter 234{"status":"ok","totalResults":70,"articles":[{"source":{"id":null,"name":"SciTechDaily"},"author":null,"title":"What Makes Memories So Detailed and Enduring? Newly Discovered Mechanism of Learning - SciTechDaily","description":"In years to come, personal memories of the COVID-19 pandemic are likely to be etched in our minds with precision and clarity, distinct from other memories of 2020. The process which makes this possible has eluded scientists for many decades, but research led …","url":"https://scitechdaily.com/what-makes-memories-so-detailed-and-enduring-newly-discovered-mechanism-of-learning/","urlToImage":"https://scitechdaily.com/images/Brain-Hippocampus-Inhibitory-Nerve-Cells.jpg","publishedAt":"2020-09-13T00:08:47Z","content":"The tiny red dots are inhibitory nerve cells within the brain’s hippocampus. The optogenetic tool, shown in green, allows researchers to measure the strength of messages to other...
13th Sep 2020, 1:17 AM
Ayush Kumar
Ayush Kumar - avatar
+ 4
O wow it worked Josh Greig. But how. Can you came to message section for my doubts regarding this ?
14th Sep 2020, 9:16 AM
Ayush Kumar
Ayush Kumar - avatar
+ 3
I tried that fetch API too Mirielle[ InAcTiVe ]
13th Sep 2020, 8:52 AM
Ayush Kumar
Ayush Kumar - avatar
+ 3
You can use the cors-anywhere proxy server, "https://cors-anywhere.herokuapp.com/", you will need to add to the front of the URL you're trying to reach. https://code.sololearn.com/Wz5hWw0rED9Y/#
13th Sep 2020, 8:59 AM
ODLNT
ODLNT - avatar
+ 3
You can use the cors-anywhere proxy server, "https://cors-anywhere.herokuapp.com/", you will need to add to the front of the URL you're trying to reach. https://code.sololearn.com/Wz5hWw0rED9Y/# #####################@ Yes ODLNT but it's still throwing error and some unexpected output. I am still confused why everything is all right in anWrite editor but not on sololearn
13th Sep 2020, 9:12 AM
Ayush Kumar
Ayush Kumar - avatar
+ 3
That is what I too facing ODLNT. But how these things actually work do you know ?
13th Sep 2020, 10:47 AM
Ayush Kumar
Ayush Kumar - avatar
+ 3
What do you mean that it isn't working? Are you seeing an error message that I'm not? The output from the API comes through in it: {"status":"ok","totalResults":70,"articles":[{"source":{"id":null,"name":"HeraldScotland"},"author":"Elle Duffy","title":"Coronavirus outbreak linked to Police Scotland training college as seven test positive - HeraldScotland","description":"An outbreak of coronavirus linked to a police training college in Scotland has been identified.","url":"https://www.heraldscotland.com/news/18718383.coronavirus-scotland-outbreak-linked-police-scotland-training-college/","urlToImage":"https://www.heraldscotland.com/resources/images/11756655/","publishedAt":"2020-09-14T06:37:33Z","content":"An outbreak of coronavirus linked to a police training college in Scotland has been identified.\r\nSeven people linked to the driving school at the college in Tulliallan have tested positive for the vi… [+2271 chars]"},{"source":{"id":null,"name":"Haveeru.com.mv"},"author":"Max Grant","title":"Japan Space Agency will send 8K cameras to Mars exploration - haveeruonline","description":"The Japan Aerospace Exploration Bureau and broadcaster NHK are working together to develop a space camera capable of shooting at 4K and 8K resolutions to","url":"https://www.haveeru.com.mv/japan-space-agency-will-send-8k-cameras-to-mars-exploration/","urlToImage":null,"publishedAt":"2020-09-14T06:29:34Z","content":"The Japan Aerospace Exploration Bureau and broadcaster NHK are working together to develop a space camera capable of shooting at 4K and 8K resolutions to capture Mars, which was previously unseen. Me… [+1587 chars]"},{"source":{"id":null,"name":"Firstpost"},"author":null,"title":"DarkSats not dark enough: SpaceX Starlink satellites continue to ruin it for astronomers - Firstpost","description":"SpaceX's megaconstellation also sets a precedent for other companies to follow suit with their own, without considering the needs of the astronomy community, say experts.","url"
14th Sep 2020, 8:47 AM
Josh Greig
Josh Greig - avatar
+ 3
Ok thanks Josh Greig and ODLNT for your help.
15th Sep 2020, 2:09 AM
Ayush Kumar
Ayush Kumar - avatar
+ 2
Why it is showing multiple output in multiple devices Mirielle[ InAcTiVe ] 😬 Its output is varying from device to device. for example : in my devise it is only showing 4 as output
13th Sep 2020, 1:29 AM
Ayush Kumar
Ayush Kumar - avatar
+ 2
See ODLNT This is what it is throwing. It's not a error but this is not the expected output 234{"status":"error","code":"corsNotAllowed","message":"Requests from the browser are not allowed on the Developer plan, except from localhost."} devise : galaxy j7-nxt
13th Sep 2020, 9:20 AM
Ayush Kumar
Ayush Kumar - avatar
+ 2
乂۝丹ⓨㄩک廾۝乂〖թг๏〗 I ran your code via sololearn playground on several devices iOS phone, Ipad, android phone, tablet and a new laptop. iOS devices displayed "status":"ok" and the data in a json format. Got the same result with the android tablet But the laptop and android phone displayed "status":"error" 🤷‍♂️ Maybe another more experienced community member can explain what is going on.
13th Sep 2020, 10:37 AM
ODLNT
ODLNT - avatar
+ 2
Did you understand my last answer? It works if you just copy my code. I published it below so you can just click "Run": https://code.sololearn.com/W1QjjZdKeidc/#html It shouldn't matter what device you're using. As long as the requests are always coming from https://solocode.azurewebsites.net, the behaviour should be the same.
14th Sep 2020, 6:29 AM
Josh Greig
Josh Greig - avatar
+ 2
😥😥 it's still not working Josh Greig. First make this code to work then I will explore all about it. Without proper knowledge of API's and AJAX I was not able to understand your last answer. I have to learn AJAX from very beginning. So try explaining things in simple manner for me.
14th Sep 2020, 8:27 AM
Ayush Kumar
Ayush Kumar - avatar
+ 2
You can take a self look of your output for your code Josh Greig https://ibb.co/D1HGNhP
14th Sep 2020, 8:49 AM
Ayush Kumar
Ayush Kumar - avatar
+ 2
Here is the updated PHP script that worked for you: <?php function cors() { // Allow from any origin if (isset($_SERVER['HTTP_ORIGIN'])) { // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one // you want to allow, and if so: header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 86400'); // cache for 1 day } // Access-Control headers are received during OPTIONS requests if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) // may also be using PUT, PATCH, HEAD etc header("Access-Control-Allow-Methods: GET, POST, OPTIONS"); if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); } } if (!isset($_GET['apiKey'])) { header('Content-type: text/plain'); ?>You must specify your newsapi.org API Key as an apiKey parameter. For example, https://www.accesslocator.com/news_proxy?apiKey=123 <?php exit; } else { cors(); $key = $_GET['apiKey']; $content = file_get_contents('http://newsapi.org/v2/top-headlines?country=in&category=science&apiKey='.$key); header('Content-type: application/json'); echo $content; } If you have a host that can run that, point your JavaScript at that. It now is so accommodating that my server could get a lot of unwanted traffic. I was restricting to the origin used when I run the code on my laptop in Sololearn's Code Playground because I wanted it restricted for your use only. Similar reasons would be behind a lot of people who set CORS. Now, my script is written as if to say "you can use the information I send you no matter where you're come from."
14th Sep 2020, 9:39 AM
Josh Greig
Josh Greig - avatar
+ 2
Hay Josh Greig I dont have knowledge of PHP. So is their any alternative so that I can do all this in javascript only. I am thinking to start learning PHP so to became master in it I would require much time. So please come to DM and guide me or if you have any problem then let me know so I would get some other resource. Because I have 0% knowledge of PHP
14th Sep 2020, 1:24 PM
Ayush Kumar
Ayush Kumar - avatar
+ 2
Yes, that could be implemented with JavaScript but nothing that can run in the web browser. You could use NodeJS to rewrite that PHP script. PHP is easier to find free or very cheap hosting for, though. I don't feel like reimplementing and testing with NodeJS but this article can get that started: https://dzone.com/articles/cors-in-node ODLNT mentioned cors-anywhere before but it sounded like you had trouble with it. cors-anywhere was made with serverside JavaScript, though: https://www.npmjs.com/package/cors-anywhere Maybe https://cors-anywhere.herokuapp.com/ is just not configured properly for null origins and you can fix that with a nodejs script that is fully under your control.
14th Sep 2020, 5:32 PM
Josh Greig
Josh Greig - avatar