0

I am using react js for web front end and php for back end, on button click on web page i am trying to send data to server but getting this Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:84)

I have tried two different ways for sending data to server but with each i got the same error. can anyone help me out?

React Code:

axios({
      method: "post",
      url: "https://asuiot12.000webhostapp.com/addCourse.php",
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS",
      },
      data: {
        Course_Code: inputTagCourseCode,
        Course_Name: inputTagCourseName,
        Credit_Hours: inputTagCreditHours,
      },
    })
      .then(function (response) {
        console.log(response);
        alert(response);
      })
      .catch(function (error) {
        console.log(error);
      });

    //attempt 2
    // axios
    //   .post("https://asuiot12.000webhostapp.com/addCourse.php", {
    //     Course_Code: inputTagCourseCode,
    //     Course_Name: inputTagCourseName,
    //     Credit_Hours: inputTagCreditHours,
    //   })
    //   .then(function (response) {
    //     console.log(response);
    //     alert(response);
    //   })
    //   .catch(function (error) {
    //     console.log(error);
    //   });
  };

Button Used:

<button
 style={{ float: "right" }}
 type="button"
 class="btn btn-success button_style mb-4"
 onClick={() => newCourse()}
>
Save Course
</button>

Php Code:

<?php
    include_once 'connection.php';
    class course{
        public $success;
        public $message;
    }
   // header("Access-Control-Allow-Origin: *");
   header("Access-Control-Allow-Origin: *");
   header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
   header('Access-Control-Allow-Headers: *'); 
   header('Access-Control-Max-Age: 1728000');
   header("Content-Length: 0");
   header("Content-Type: text/plain");
    $Course_Code = $_POST['Course_Code'];
    $Course_Name = $_POST['Course_Name'];
    $Credit_Hours = $_POST['Credit_Hours'];
    $query = "INSERT INTO Courses(Course_Code, Course_Name, Credit_Hours)
     VALUES ('$Course_Code','$Course_Name','$Credit_Hours')";
    if(mysqli_query($con,$query)){
        echo "Records added successfully.";    } else{
        echo "ERROR: Could not able to execute $query. " . mysqli_error($con);
    }
    mysqli_close($con);
?>
  • Can you have a look into your browsers DevTools console? There might be some helpful error messages. – Ogod May 29 '21 at 19:14
  • i have found this, POST https://asuiot12.000webhostapp.com/addCourse.php net::ERR_HTTP2_PROTOCOL_ERROR, but i don't know what does this mean, can you plz tell me about this error – Waqas Nazir May 30 '21 at 07:02
  • In firefox browser i found this, Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://asuiot12.000webhostapp.com/addCourse.php. (Reason: CORS request did not succeed). – Waqas Nazir May 30 '21 at 07:37
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Jun 12 '21 at 18:54

1 Answers1

-1

If you are using hostinger(000webhost) and you are making a website using react and PHP, you can use axios to retrieve data from server, you can't use axios to make a post request. If you will, you will he an http protocol error. So instead to axios use fetch(I repeat in case of 000webhost server). I have done the same thing with fetch like this

const addCourse = () => {
    fetch("https://asuiot12.000webhostapp.com/addCourse.php", {
      method: "POST",
      body: JSON.stringify({
        Course_Code: inputTagCourseCode,
        Course_Name: inputTagCourseName,
        Credit_Hours: inputTagCreditHours,
      }),
    })
      .then(function (response) {
        return response.json();
      })
      .then(function (data) {
        console.log(data);
        alert(data);
      })
      .catch((error) => {
        // Do something for an error here
        if (error.response) {
          console.log("Error with response", error.response.status);
        } else if (error.request) {
          console.log("Problem with request");
        }
      });
  };

In PHP file read data like this

<?php
   // write down you db connection code her/import connection file
   header("Access-Control-Allow-Origin: *");
   header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
   header('Access-Control-Allow-Credentials: true');
   header('Access-Control-Max-Age: 86400');    // cache for 1 day

   $data = json_decode(file_get_contents("php://input"), true);

   if($data['Course_Code'] != null && $data['Course_Name'] != null && 
   $data['Credit_Hours'] != null ){
        //echo json_encode($data);
        $Course_Code = $data['Course_Code'];
        $Course_Name = $data['Course_Name'];
        $Credit_Hours = $data['Credit_Hours'];
    

        $query = "INSERT INTO Courses(Course_Code, Course_Name, Credit_Hours)
        VALUES ('$Course_Code','$Course_Name','$Credit_Hours')";
        //$data = array();

        if(mysqli_query($conn,$query)){
        //$temp = array();
        //$temp['message'] = "Successfully Registered";
        $response = "Successfully Registered";
        echo json_encode($response);
        //array_push($data, $temp);
        } else{
        //  $temp = array();
        // $temp['message'] = "Error Occured ". mysqli_error($conn);
        $response  = "Error Occured ". mysqli_error($conn);
        echo json_encode($response);
        // array_push($data, $temp);
        }
        //echo json_encode($data);
   }else{
        $response = "Something went wrong...";
        echo json_encode($response);
   }
   mysqli_close($conn);
?>