简体   繁体   中英

Ajax PHP Call not working

I tried to run the code below but it doesn't work, and I tried everything I remember and couldn't get to work.

AJAX Call

var status = $(this).prop("checked");
var room_id = id;
$.post('maintenanceControl.php', {action: status, id: room_id});

PHP Script

<?php

if (isset($_POST['action']) && !empty($_POST['action']) && isset($_POST['id']) && !empty($_POST['id'])) {
    $action = $_POST['action'];
    $id = $_POST['id'];
    if ($action) {
        return manageMaintenance($id, true);
    } else {
        return manageMaintenance($id, false);
    }
}

function manageMaintenance($room_id, $status)
{
    $jsonString = file_get_contents('status.json');
    $data = json_decode($jsonString, true);

    foreach ($data['rooms'] as $key => $entry) {
        if ($key == $room_id) {
            $data[$key]['maintenance'] = $status;
        }
    }

    $newJsonString = json_encode($data);
    file_put_contents('status.json', $newJsonString);

    return true;
}

At first I thought it was a malfunction but the example below worked just fine

$.post( "test.php", function( data ) {
    alert(data);
});

PHP

<?php
echo "test";

In order to get data back into the Javascript ajax call, you need the php script to echo something.

Return values in php do not find their way back into the Ajax call.

Often, php scripts echo a value, either a single value or if you want the get more complex data from php back into the Ajax call, you can json encode several values and echo that.

You have to echo/print something in php script to send response to ajax request. You have to do something like below.

$response=false;
if (isset($_POST['action']) && !empty($_POST['action']) && isset($_POST['id']) && !empty($_POST['id'])) {
    $action = $_POST['action'];
    $id = $_POST['id'];
    if ($action) {
        $response=manageMaintenance($id, true);
    } else {
        $response=manageMaintenance($id, false);
    }
}

function manageMaintenance($room_id, $status)
{
    $jsonString = file_get_contents('status.json');
    $data = json_decode($jsonString, true);

    foreach ($data['rooms'] as $key => $entry) {
        if ($key == $room_id) {
            $data[$key]['maintenance'] = $status;
        }
    }

    $newJsonString = json_encode($data);
    file_put_contents('status.json', $newJsonString);

    return true;
}

echo $response==true? "OK" : "FAILED";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM