简体   繁体   中英

Request to api using jquery ajax with php

hi guys i'm getting stuck in my code i'm requesting to a php api to get data with using jquery ajax. please help me with a solution

Ajax code

     $.ajax({
      url: request_url+"courses.php",
      type: 'POST',
      dataType: 'jsonp',
      cors: true ,
      contentType:'application/json',
      data: { request_courses: courses },
      secure: true,
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
      beforeSend: function (xhr) {
        xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
      },
      success: function (data){
        console.log("helo "+data);
      }
   });

Php Api code

   if(isset($_POST['request_courses'])){
        $courses = mysqli_query($conn, "SELECT * FROM `courses`");
        while ($rows = mysqli_fetch_assoc($courses)) {
            $data[] = $rows;
        }
        echo json_encode(array('status' => 1,'message'=>'responce_courses','data'=>$data));
    }

Error While runing this code

courses.html:1 A cookie associated with a cross-site resource at http://localhost/ was set 
without the `SameSite` attribute. A future release of Chrome will only deliver cookies with 
cross-site requests if they are set with `SameSite=None` and `Secure`. You can review 
cookies in developer tools under Application>Storage>Cookies and see more details at 
https://www.chromestatus.com/feature/5088147346030592 and 
https://www.chromestatus.com/feature/5633521622188032.



Access to XMLHttpRequest at 'file:///home/punkaj/Music/Cordova/ithub/www/index.html' from 
origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for 
protocol schemes: http, data, chrome, chrome-extension, https.
jquery.js:2 GET file:///home/punkaj/Music/Cordova/ithub/www/index.html net::ERR_FAILED
send @ jquery.js:2
ajax @ jquery.js:2
h @ plugins.js:45
i @ plugins.js:45
dispatch @ jquery.js:2
y.handle @ jquery.js:2

First off, are you sure of the file URLs? 'file:///home/punkaj/Music/Cordova/ithub/www/index.html' seems a bit sketchy IMO. Make sure that it's correct.

And secondly, looks like the AJAX referenced file (courses.php) is trying to set a new cookie on the browser, which is a bad practice in REST APIs. It's better to just return/output whatever value you want, and when you have that value in your 'success' AJAX function, you can save it there as a cookie back in the original script.

Lastly, it looks like you're getting the file directly by using an FTP protocol (file:///) rather than an HTTP protocol (http://) to get the content of the HTML file. Can't provide any further assistance on that without seeing the source code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM