-6

This is the code which inserts data into the database. and the result is sent back to the ajax code.

<?php

if (isset($_FILES['files']['name'])) {
    $files = $_FILES['files']['name'];
    $desc = $_POST['description'];
    $subject = $_POST['subject'];
    $path = 'Lectures/' . $files;
    move_uploaded_file($_FILES["files"]["tmp_name"], $path);
    $date = date('d-M-y');

    $query = "INSERT INTO content(file_name,course_code,description,file_path,upload_date) VALUES ('$files','$subject','$desc','$path','$date')";

    $cm = sqlsrv_query($conn, $query);
    if ($cm) {
        $result['status'] = "Succsess";
    } else {
        $result['status'] = "failed";
    }
    echo json_encode($result);
}

And this is the Ajax Success: function.it executes only the else portion even if the condition is true.

success: function(output) {
    alert(output);
    if(output.status == "Succsess")
    { 
        alertify.success('Success message');
    }else{
        alertify.set('notifier','delay', 2);
        alertify.set('notifier','position', 'top-right');
        alertify.error('Error message');
    }
    readRecords();
    $('#form1').trigger("reset");
}
Rotimi
  • 4,783
  • 4
  • 18
  • 27

1 Answers1

1

alert(output); shows the success message if the data is inserted.

It should show [object Object].

You are looking at a string, and not an object parsed from JSON.

Since it is a string, it doesn't have a status property.

const output = '{ "status": "Succsess" }';
alert(output);
alert(output.status);

You need to tell jQuery that the response is JSON so it will parse it into an object.

header("Content-Type: application/json");
echo json_encode($result);

Note that you must set the headers before sending any other output.

Without setting the Content-Type header explicitly, PHP will default to claiming that the JSON is HTML … which it isn't.

Note that the below is for the sake of example. You should not add JSON.parse to your client-side code. jQuery will do that behind the scenes.

const output = JSON.parse('{ "status": "Succsess" }');
alert(output);
alert(output.status);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335