2

I have the following code on my PHP page which gets a message from the client and stores it into a log file on the server. This function is called by a jquery AJAX function(given below). The AJAX request sends the data properly and the PHP code works fine. However when the response to the AJAX request is sent back the page suddenly redirects to index.php(my main page):

PHP Code

function store_chat_msg_function()
{
    //Check if session is active
    if(isset($_SESSION['NAME']))
    {
        $data = $_POST;

        $text = $data["message"];
        $filepath = $data["filepath"];

        $fp = fopen($filepath, 'a');
        fwrite($fp, "<div class='msgln'>(".date("g:i A").") <b>".$_SESSION['NAME']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
        fclose($fp);

        //Push data array to be sent into array
        $json = array();
        $bus = array(
            'message' => "1"
        );
        array_push($json, $bus);

        //Encode to JSON format
        $jsonstring = json_encode($json);

        //Specify type of data being sent
        header("content-type:application/json");    //<-----(error:line 179)

        //Finally send the data
        echo $jsonstring;
    }
    else
    {

    }
}

And the AJAX function is:

//On submit message
$("#submitmsg").click(function(){

    var ptarget = $(this).html();

    //get some values from elements on the page:
    //Set parameters...
    var clientmsg = $("#usermsg").val();

    //Clear the text box
    $("#usermsg").val("");

    var data = {
        "action": "send_chat_msg",
        "message": clientmsg,
        "filepath": globalrefreshfile
    };
    data = $(this).serialize() + "&" + $.param(data);

    //Send the data using post and put the results in a div
    $.ajax({
        url: "post.php",
        type: "POST",
        data: data,
        datatype: "json",
        success: function(data) {
            if(data[0].message!="1"){
                alert("Message was not sent.");
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status);
            alert(errorThrown);
            $("#chatbox").html('There was an error updating chat window');
            $("#chatbox").fadeIn(1500);
        }
    });
});

I removed header("content-type:application/json"); and datatype: "json" in the AJAX function and found that the data is muddled by error data sent by the ZEND server i'm debugging on. The error is:

"
Warning: session_start(): Cannot send session cache limiter - headers already sent in C:\Program Files (x86)\Zend\Apache2\htdocs\ChatServer\post.php on line 2
Warning: Cannot modify header information - headers already sent in C:\Program Files (x86)\Zend\Apache2\htdocs\ChatServer\post.php on line 179
[{"message":"1"}]

So i understand that I think i may have messed up the headers based on the ZEND debugger error which is interfering with my JSON data(seen appended at the end of the error)? What gives? Thank you for your time and patience.

GKamath
  • 31
  • 3
  • Before you send anything to the client, including headers, that's when you need to call session_start(). When sending the headers, they must then be the next thing you send before any content is actually sent. – Zarathuztra Mar 05 '15 at 14:35

2 Answers2

2

Add ob_start(); as the first line in your script if you can't move the header("content-type:application/json"); to the top of the page for some reason.

Matt
  • 5,315
  • 1
  • 30
  • 57
1

You cannot modify headers, so move your code to top of page:

header("content-type:application/json");

Top means top of proccessed page, Not a top of function.

Regards

Kerem
  • 37
  • 7