0

I'm really new in Ajax with PHP and JavaScript. I have to do some simple project as a workshop for my training and I created js script:

$(function() {
   $('#bookAdd').submit(function (e) {
       e.preventDefault();

       var title = $('#title').val();
       var description = $('#description').val();

       // console.log(title + '\n');
       // console.log(description);
       $.ajax({
           url: "../rest/rest.php/book",
           data: {
               'title': title,
               'description': description
           },
           type: 'POST',
           dataType: 'json',
           success: function (response) {
               console.log(response);
               //console.log(response['success']);
           },

           error: function (xhr, status, error) {
               console.log('error');
           }

       });
   });
});

Where #bookAdd is form to add new book and rest.php is php script where proper class is added and book is saving to DB. It looks like this:

<?php
//load DB config
require_once __DIR__.'/config/db.php';


$response = [];
//connect to DB
try {
    $conn = new PDO(
        "mysql:host=".DB_HOST.";dbname=".DB_DB.";charset=utf8"
        , DB_LOGIN, DB_PASSWORD,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (PDOException $e) {
    $response = ['error' => 'DB Connection error: '.$e->getMessage()];
}

######### Dynamic load php class file depend on request #########
//parsing url
//if request URI is rest.php/book/1
//we will parse part book/1 and explode it
//to get name of class (book) and optional id from db (1)
$uriPathInfo = $_SERVER['PATH_INFO'];
//explode path info
$path = explode('/', $uriPathInfo);
$requestClass = $path[1];

//load class file
$requestClass = preg_replace('#[^0-9a-zA-Z]#', '', $requestClass);//remove all non alfanum chars from request
$className = ucfirst(strtolower($requestClass));

$classFile = __DIR__.'/class/'.$className.'.php';
require_once $classFile;

######### END DYNAMIC LOAD #########

$pathId = isset($path[2]) ? $path[2] : null;

if (!isset($response['error'])) {//process request if no db error
    include_once __DIR__.'/restEndpoints/'.$className.'.php';
}

header('Content-Type: application/json');//return json header

if (isset($response['error'])) {
    header("HTTP/1.0 400 Bad Request");//return proper http code if error
}

echo json_encode($response);

The thing I can't find out is success function in my js file - why console log doesn't display anything?

Paweł Nowak
  • 75
  • 1
  • 3
  • 10
  • Have you checked the Network tab to see if you're sending / receiving proper request / responses? Have you checked your server script is actually being hit – Patrick Evans Jun 11 '17 at 23:39
  • So you're not getting a response, nor an error? The URL `../rest/rest.php/book` seems rather strange ? – adeneo Jun 11 '17 at 23:42
  • Hmm...there is no any php script visible in Network tab. What does it mean? – Paweł Nowak Jun 11 '17 at 23:50
  • if there is no network log of your php script being hit, then your ajax function is not being called – Patrick Evans Jun 11 '17 at 23:52
  • The thing is I got backend files from my training materials, so it is like it is and I'm confused.. I'm doing somethig wrong or those scripts are wrong... – Paweł Nowak Jun 11 '17 at 23:58
  • It looks like php file works, because book is added to database. There is annother file wit class Book which is responsible for that. – Paweł Nowak Jun 12 '17 at 00:08
  • Well, what happens if you do `echo '{"test" : "working"}';` or something similar, actually returning something ? – adeneo Jun 12 '17 at 00:12
  • Nothing...console.log is empty but php adds book to database. – Paweł Nowak Jun 12 '17 at 00:15
  • Ok, I changed a bit my success function. I looks like this now: `code success: function (response) { if (!response) { alert ('No respomse'); } else { alert (response); }` And When I add book alert says [object Object] – Paweł Nowak Jun 12 '17 at 11:55

2 Answers2

0

Try to run the .php file in browser and see if it outputs the desired results. Also try to replace your relative path with absolute path of the php file.

Azaz Khan
  • 106
  • 1
  • 6
0

Ok i fix this :) found solution here: jQuery AJAX call returns [object Object]. Just had to call function stringify at my response. Soo...conclusion is I can't display response just like that as json object? Am I right?

Paweł Nowak
  • 75
  • 1
  • 3
  • 10