Crazy Horse
asked on
Form validation with ajax/php mvc and json
This validation is working but I just wanted to check if it is actually acceptable practice to do what I am doing.
I have a Ajax.php file which is a controller within my controllers folder.
In there I have an Ajax class with an addAccom method which looks like:
I then have some jQuery in my scripts.js file being called in the footer. The jQuery appends the data to divs I have in the view. It is working fine but I just wanted to check that this is okay using PHP and MVC or if I am breaking some rules?
I do plan on sending data to the model and performing a database insert as well.
I have a Ajax.php file which is a controller within my controllers folder.
In there I have an Ajax class with an addAccom method which looks like:
public function addAccom()
{
$response = array();
$message = '';
if($_POST['category'] == '') {
$message .= "Category required <br />";
}
if(empty($_POST['name'])) {
$message .= "Name required <br />";
}
if(empty($_POST['description'])) {
$message .= "Description required";
}
if($message) {
$response['success'] = false;
$response['message'] = $message;
} else {
$response['success'] = true;
$response['message'] = "All good";
}
echo json_encode($response);
}
I then have some jQuery in my scripts.js file being called in the footer. The jQuery appends the data to divs I have in the view. It is working fine but I just wanted to check that this is okay using PHP and MVC or if I am breaking some rules?
I do plan on sending data to the model and performing a database insert as well.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You could tuck these validation rules inside your model class. That would leave the Controller to make the call to the method / function in the class, so it's not performing any "business logic"
HOWEVER
this is client side validation (i.e. called via AJAX), so "MVC" isn't really in the picture... you're in the VIEW / client side.
I generally keep my server side validation in the model.
HOWEVER
this is client side validation (i.e. called via AJAX), so "MVC" isn't really in the picture... you're in the VIEW / client side.
I generally keep my server side validation in the model.
ASKER
Interesting. I am new to MVC so my opinions or 2 cents don't really matter, but I thought the model was meant to be just for the database interaction? Without ajax, I do my validation in the controller and if the validation passes I then send the data to the model. But like I said, I am new to this so I probably don't know what I am talking about.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
I was more asking if doing it like how I did was okay using php MVC and OOP, because it doesn't look very OOPy.