4

I have a host server at a web-hosting and my PHP file is lodated in a folder at server. From my HTML form, I send some data using Jquery AJAX and I like to view all those variables in my PHP code at server side. My Jquery AJAX code is as follow.

function sendtoServer() {

     $.ajax({
        url: "advertisementdatavalidationatserver.php",
        type: "POST",
        data: $("#landedForm").serialize(), 
        success:  function(ret){

});
}

My PHP code at server is

<?php
$data = array();
$data['error'] = false;

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if(!isset($_POST['purpose'])){ 
        $data['error'] = true;
        $data['message'][] = "Purposeerror";
    }

    if(!isset($_POST['type'])){ 
        $data['error'] = true;
        $data['message'][] = "Typeerror";
    }

    if ($_POST['type'] == "With_RC" || $_POST['type'] == "With_BrickNorcal") { 

        if ($_POST['stories'] == "Stories"){
            $data['error'] = true;
            $data['message'][] = "Storieserror";        
        }


        if ($_POST['bedrooms'] == "Bedrooms") {        
            $data['error'] = true;
            $data['message'][] = "Bedroomserror";        
        }

        if ($_POST['bathrooms'] == "Bathrooms") {        
            $data['error'] = true;
            $data['message'][] = "Bathroomserror";        
        }

    }

    if ($_POST['divs_states'] == "Division") {        
            $data['error'] = true;
            $data['message'][] = "Divisionerror";        
    }

    if ($_POST['township'] == "Township") {        
            $data['error'] = true;
            $data['message'][] = "Townshiperror";        
    }

    if ($_POST['price']=="") {        
            $data['error'] = true;
            $data['message'][] = "Priceerror";        
    }else if (!preg_match('/^\d+$/', $_POST['price']) ) {        
            $data['error'] = true;
            $data['message'][] = "Priceinvalid";        
    } 

    if ($_POST['length']=="") {        
            $data['error'] = true;
            $data['message'][] = "Lengtherror";        
    }else if (!preg_match('/^\d+$/', $_POST['length']) ) {        
            $data['error'] = true;
            $data['message'][] = "Lengthinvalid";        
    } 

    if ($_POST['width']=="") {        
            $data['error'] = true;
            $data['message'][] = "Widtherror";        
    }else if (!preg_match('/^\d+$/', $_POST['width']) ) {        
            $data['error'] = true;
            $data['message'][] = "Widthinvalid";        
    }    

    if(!isset($_POST['haveaircon'])){ 
        $data['error'] = true;
        $data['message'][] = "Airconerror";
    }

    if ($_POST['possession'] == "Possession") {        
            $data['error'] = true;
            $data['message'][] = "Possessionerror";        
    }

    if($_POST['date']==""){ 
        $data['error'] = true;
        $data['message'][] = "Dateerror";
    }

    if($_POST['textarea'] == "Please enter additional information here..." || $_POST['textarea'] ==""){ 
        $data['error'] = true;
        $data['message'][] = "Textareaerror";
    }

    if(!isset($_POST['agentowner'])){ 
        $data['error'] = true;
        $data['message'][] = "Agentownererror";
    }

    if($_POST['name'] == ""){ 
        $data['error'] = true;
        $data['message'][] = "Nameerror";
    }

    if($_POST['phone'] == ""){ 
        $data['error'] = true;
        $data['message'][] = "Phoneerror";
    }else if((strlen($_POST['phone']) < 6) || !preg_match('/^\d+$/', $_POST['phone'])){
        $data['error'] = true;
        $data['message'][] = "Phoneinvalid";
    }

    if(!isset($_POST['email']) || empty($_POST['email'])){ 
        $data['error'] = true;
        $data['message'][] = "Emailrequired";
    }else if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
        $data['error'] = true;
        $data['message'][] = "Emailinvalid";
    }

    if(!$data['error']){
        // No errors, save into database

        $con = mysql_connect("localhost","thitsun_admin","z4iufn8n##");

        if (!$con)
        {
           $data['error'] = true;
           $data['message'][] = "Connectionerror";
           die('Could not connect: ' . mysql_error());
        }else{

           mysql_select_db("thitsun_properties_database", $con);

           $purpose = mysql_real_escape_string($_POST['purpose']);           
           $type = mysql_real_escape_string($_POST['type']);
           $stories = NULL;
           $bedrooms = NULL;
           $bathrooms = NULL;
           if ($_POST['type'] == "With_RC" || $_POST['type'] == "With_BrickNorcal") { 
                $stories = intval($_POST['stories']);
                $bedrooms = intval($_POST['bedrooms']);
                $bathrooms = intval($_POST['bathrooms']);
           }
           $divs_states = mysql_real_escape_string($_POST['divs_states']);
           $township = mysql_real_escape_string($_POST['township']);
           $price = intval($_POST['price']);
           $length = intval($_POST['length']);
           $width = intval($_POST['width']);

           if($_POST['haveaircon'] == "yes")
               $haveaircon = "yes";
           else
               $haveaircon = "no";
           if($_POST['havetelephone'] == "yes")
               $havetelephone = "yes";
           else
               $havetelephone = "no";

           $possession = mysql_real_escape_string($_POST['possession']);
           $date = mysql_real_escape_string($_POST['date']);
           $textarea = null;
           if($_POST['textarea'] != "Please enter additional information here..." || $_POST['textarea'] != ""){ 
              $textarea = mysql_real_escape_string($_POST['textarea']);
           }

           $agentowner = mysql_real_escape_string($_POST['agentowner']);
           $name = mysql_real_escape_string($_POST['name']);
           $phone = mysql_real_escape_string($_POST['phone']);
           $email = mysql_real_escape_string($_POST['email']);

           $address = NULL;
           if($_POST['address'] != "Please key in full address if you are ok..." || $_POST['address'] != ""){ 
              $address = mysql_real_escape_string($_POST['address']);
           }          

           $query = "INSERT INTO `thitsun_properties_database`.`registered_properties`(`id`, `purpose`, `type`, `num_stories`, `bedrooms`, `bathrooms`, `div_state`, `township`, `price`, `length`, `width`, `have_phone`, `have_aircon`, `possession`, `available_date`, `description`, `agentowner`, `name`, `phone`, `email`, `address`, `submitteddate`) VALUES (NULL,'$purpose', '$type','$stories', '$bedrooms', '$bathrooms', '$divs_states', '$township', '$price', '$length', '$width', '$havetelephone', '$haveaircon', '$possession', '$date', '$textarea', '$agentowner', '$name', '$phone', '$email', '$address',CURRENT_TIMESTAMP);";
   // `id`, `purpose`, `type`, `num_stories`, `bedrooms`, `bathrooms`, `div_state`, `township`, `price`, `length`, `width`, `have_phone`, `have_aircon`, `possession`, `available_date`, `description`, `agentowner`, `name`, `phone`, `email`, `address`, //`submitteddate`


    //'$purpose', '$type','$stories', '$bedrooms', '$bathrooms', '$divs_states', '$township', '$price', '$length', '$width', '$havetelephone', '$haveaircon', '$possession', '$date', '$textarea', '$agentowner', '$name', '$phone', '$email', //'$address',CURRENT_TIMESTAMP
           if(mysql_query($query,$con) or die("Insertion Failed:".mysql_error()))
           {
              if(mysql_affected_rows($con)!=1){
                 $data['error'] = true;
                 $data['message'][] = "Connectionerror";
              }
           }

            mysql_close($con);
        }

    }
}

// then echo the $data array you have built as JSON to use in jquery. 
//This will be what is returned in your AJAX request
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($data);
?>

I like to debug all these variables like $name, $email, $phone before they are put into database. Of course, I can check once they are successfully saved into database. But in some cases, if they can't be saved into database, I need to check what are the value inside these variables.

All discussions said to use print, print_r or echo. I used them, but I don't see any output or frankly is no idea where to see those outputs. I checked in the console (F12), but nothing is there.

My query is I have PHP code in a .php file located in host sever. How can I view the variables sent via AJAX at PHP code?

Thanks

15
  • You have to look at your generated html, they are printed there. Call the php url from your browser and you will see the output. Commented Jan 7, 2016 at 14:13
  • var_dump($_POST['type']); die(); Do not do this in a prod environment. Commented Jan 7, 2016 at 14:16
  • Possible duplicate of What's the difference between echo, print, and print_r in PHP? Commented Jan 7, 2016 at 14:19
  • Thats better, now people can see what you are trying to do Commented Jan 7, 2016 at 14:20
  • @Abdulla No its more complicated that that, he want to know how he can view the data provided on an AJAX call to a server script, so he can see what gets sent to the server on th server Commented Jan 7, 2016 at 14:21

5 Answers 5

3

The way I do this is to write the output of a print_r($_POST) to a file on the server because as you say there is no console or window that you can see the data coming into the server script that services your AJAX call

<?php
$data = array();
$data['error'] = false;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    file_put_contents('somefilename.txt', print_r($_POST,true), FILE_APPEND);

    // your other code

Using the FILE_APPEND option will add each call to the end of your file so you can check changes made in the javascript(AJAX) code with each change you make there

Sign up to request clarification or add additional context in comments.

Comments

1

print, echo, print_r, var_dump and other print functions output to the viewport - in most cases, this will be the browser.

If your file index.php contains:

<?php echo "Hello, world!" ?>

visiting //index.php will show

Hello, world!

Similarly, if executing via command line, such as > php index.php you'll see the output in the terminal directly.


To see the differences between print, print_r, echo and var_dump, please see this post.

Comments

1

Add this in the first few lines of advertisementdatavalidationatserver.php:

var_dump($_POST);
die();

Open web tools (chrome F12 for example) Click 'Network' tab. Make ajax request. Click reaponse. The response will contain a dump of $_POST

1 Comment

Thanks that makes sense. Let me test.
1

Here is a function that logs anything in the error log file of the current directory , if you like to log them in a certain directory just add it before the third argument of error_log

  <?php
    //example of usage
    _log("this is a string");
    _log(array("key",4));


    function _log($msg)
    {
        if(is_string($msg))
        {
            error_log("\n".$msg,3,"error_log");
        }
        else
        {
            error_log("\n".print_r($msg,true),3,"error_log");
        }
    }
    ?>

Comments

0

A print intitiated by PHP is interpreted by a webserver like Apache, Nginx, ... . For example you have the file index.php with the following content:

<html>
  <title>Hello World</title>
  <body>
    <?php
      print("Hello, World!");
    ?>
  </body>
</html>

and you add this file into the folder of your webserver, e.g. /var/www/index.php and you access your webserver with your browser, you can see the output of your PHP-prints.

2 Comments

Does it works, if solely PHP code in the server received data sent via AJAX?
You might want to look at this post, where AJAX posts to a PHP scripts are described: stackoverflow.com/questions/22179620/sending-data-via-ajax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.