A
A
Alexander2015-11-16 12:12:03
PHP
Alexander, 2015-11-16 12:12:03

Ajax on mvc (php)?

Comrades, hello! In this question, a beginner, so do not kick)
How can I screw AJAX if I use the MVC template in php?
The project structure is below in the photo:
2fe83264ec5d4a66b94897f2bf3ddce7.jpg
in the controller I have a view variable that checks the get parameter, for example, like this:
localhost/project/?view=profile
In general, I have one entry point. There is such a structure in index.php In this project I already use ajax, but the whole page is sent and I cut out the piece I need from it, but now I need the "correct response" from the server, not the whole page... Many thanks in advance to everyone!
include $view."php";

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evgeny Komarov, 2015-11-16
@alex_p95

Project Structure
app\
____Controller\
________Main.php
public\
____js\
________ scriptr.js
vendor\
index.php
composer.json
.htaccess
In script.js file

$('#confirmForm').on('click', function (event) {
    $.ajax({
        url: '/confirm',
        method: 'post',
        dataType: 'json',
        success: function (data) {
            console.log(data);
        }
    });
});

In the front controller (index.php), we redirected the request to, for example, the Main::index() controller
<?php
    session_start();
    require_once '/vendor/autoload.php';
    $router = new AltoRouter();
    $router->map('GET|POST', '/confirm', 'Main::index');

    if ($match = $router->match()) {
        $path = explode('::', $match['target']);
        $controllerName = 'Controller\\' . $path[0];
        $controller = new $controllerName;
        call_user_func_array([$controller, $path[1]], $match['params']);
    } else {
        header('Location: /404');
    }

In the Main.php controller
<?php
class Main()
{
    public function index()
    {
        $service = new MainService();
        $service->saveForm();
        json_encode([
            'success' => true,
            'message' => 'Форма успешно сохранена'
        ], JSON_UNESCAPED_UNICODE);
    }
}

S
Sergey Zelensky, 2015-11-16
@SergeyZelensky-Rostov

read about json_encode/decode functions in php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question