Andrew
Andrew

Reputation: 1575

Issue with sending data with ajax to php script

I have an issue when sending form data over Ajax to PHP script. When sending data i get this kind of error

Fatal Error: Class Libs\Controller not found

I have written my own MVC project structure and its working fine if i'm sending data just with POST request but when sending with AJAX getting this error

use Libs\Controller;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;


class Contact extends Controller {
  //rest code to send email with PHPMailer
}

And here is the js script

$("#contact-form").on('submit', function (e) {
    $(".validmessage").css("display", "block");
    e.preventDefault();

    $.ajax({
        url: "/../../app/controllers/Contact.php",
        type: "POST",
        data: $(this).serialize(),
        success: function (data) {
            $("#form_output").html(data);
        },
        error: function (jXHR, textStatus, errorThrown) {
            alert(errorThrown);
        }
            });
        });

My file structure:

controllers
 - Contact.php
-libraries
  - Controllers.php
  - Core.php
  - Database.php

Using PSR autoloader to load my classes inside index.php file

Upvotes: 0

Views: 43

Answers (1)

pr1nc3
pr1nc3

Reputation: 8358

   require '../libraries/Controllers.php'

    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;


    class Contact extends Controller {
      //rest code to send email with PHPMailer
    }

You need to move one step back to access the Controllers. At the moment you are in contact.php so you can not "see" the libraries folder. You need to move 1 step back using ../ and then access the folder and it's files.

Upvotes: 3

Related Questions