J. Doe J. Doe - 1 month ago 8
Javascript Question

Having trouble sending AND receiving information from a php file using javascript

I am sending some information to a php file that runs a query but I want to also retrieve some information from that php file at the same time. The php file executes fine but I can't get the json_encoded object.

Javascript function that sends a string and a number to a php file:

function open_close(){
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status="+status+"&TicketNum="+ticketNum;
var http3 = createAjaxRequestObject();

if (http3.readyState == 4) {
if (http3.status == 200){
alert("Ticket Updated!"); //This never gets hit
getUpdatedTicket(JSON.parse(http3.responseText));
}
}

http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}


PHP File that takes the string and number and updates a table

<?php
include("config.php");
session_start();

$status = $_POST["Status"];
$num = $_POST["TicketNum"];
$newStatus = " ";
if(strcmp($status, "Open") == 0){
$newStatus = "Closed";
}
elseif(strcmp($status, "Closed") == 0){
$newStatus = "Open";
}

$sql = "UPDATE tickets SET Status = \"$newStatus\" where TicketNum = $num ";
$r = $conn ->query($sql) or trigger_error($conn->error."[$sql]");

$sql = "SELECT * FROM tickets where TicketNum = $num";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$data[] = $row;
}

echo json_encode($data);

?>


How can I retrieve the json_encoded object in the same javascript function?

Answer

You'd need a readyState listener to know when the request is done, and then get the data from the responseText

function open_close() {
    var status = encodeURIComponent(SelectedTicket["Status"]);
    var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
    var info = "Status=" + status + "&TicketNum=" + ticketNum;
    var http3 = createAjaxRequestObject();

    http3.onreadystatechange = function () {
        if (http3.readyState == 4) {
            if (http3.status == 200) {
                console.log(http3.responseText); // <- it's there
            }
        }    
    }

    http3.open("POST", "openClose.php", true);
    http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    http3.send(info);
}