0

I am trying to send the values of 7 jquery checkboxes to php via ajax. I am attempting to put the values in an array and serialize the array in ajax. Ultimately, I would like to use the values of the checked checkboxes as conditions is a MySQL WHERE clause. My code fails when I try to use the result in php and the table in that page will not display. However, if I comment out the $_POST line in that php page, my table displays. When inspecting the code in a browser, I get a 500 (internal Server Error) where the table should display. I also had the ajax display the error result which was as follows:

[object Object]

CODE:

My HTML code:

   <label for="prestage_select">Prestage</label>
   <input type="checkbox" name="revenue_checkboxes[]" id="prestage_select" value="Prestage">


   <label for="validation_select">Validation</label>
   <input type="checkbox" name="revenue_checkboxes[]" id="validation_select" value="Validation"> 


   <label for="scheduling_select">Scheduling</label>
   <input type="checkbox" name="revenue_checkboxes[]" id="scheduling_select" value="Scheduling">


    <label for="production_select">Production</label>
    <input type="checkbox" name="revenue_checkboxes[]" id="production_select" value="Production">


    <label for="needsBOL_select">Needs BOL</label>
    <input type="checkbox" name="revenue_checkboxes[]" id="needsBOL_select" value="Needs BOL">


    <label for="shpAcct2Close_select">Shipped: Account to Close</label>
    <input type="checkbox" name="revenue_checkboxes[]" id="shpAcct2Close_select" value="Shipped: Acctg. To Close Out">


    <label for="movedToComplete_select">Moved to Complete for Selected Period</label>
    <input type="checkbox" name="revenue_checkboxes[]" id="movedToComplete_select" value="Complete">

My Ajax Code:

    j("#create_submit").click(function(){

          //Send Revenue Status Values to php using ajax.     
              j.ajax({
                  method: 'POST',
                  url: 'revenue_report.php',
                  data: j('[name="revenue_checkboxes[]"]').serialize(),
                  success: function( response ) {
                          j('#fieldset_ReportDiv').html(response);
                          }
                   });


        //send Revenue Date values to php using ajax.
                  var revenuefrom = j('#revenuefrom').val();
                  var revenueto = j('#revenueto').val();
                  j.ajax ({
                      method: 'POST',
                      url: "revenue_report.php",
                      data: { revenuefromtext: revenuefrom, revenuetotext: revenueto },
                      success: function( response ) {
                          j('#fieldset_ReportDiv').html(response);
                          }
                  });

My PHP Code:

    <?php

    include('inc.php');


    //Get date range.

    $revenuefromajax=$_POST['revenuefromtext'];
    $revenuetoajax=$_POST['revenuetotext'];

    $revenuefromstring = strtotime($revenuefromajax);
    $revenuetostring = strtotime($revenuetoajax);

    $revenuefrom=date("Y-m-d", $revenuefromstring);
    $revenueto=date("Y-m-d", $revenuetostring);


    //Get selected Status Values.

    $revenuecheckboxes=$_POST('revenue_checkboxes'); //the page loads properly when this line is commented out. As soon as I remove the comment, it breaks.





    //connect  to the database 
    $conn = new mysqli($servername, $username, $password, $dbname);

    // Check connection
    if(mysqli_connect_errno() ) {
      printf('Could not connect: ' . mysqli_connect_error());
      exit();
    }

   //echo 'MySQL Connected successfully.'."<BR>";


   $conn->select_db("some database name");  /////Database name has been changed for security reasons/////////

   if(! $conn->select_db('some database name') ) {

        echo 'Could not select database. '."<BR>";
    }

    // echo 'Successfully selected database. '."<BR>";

    //Select Data and Display it in a table.


    $sql = "SELECT invoices.id, invoices.orderdate, invoices.stagestatus, FORMAT(TRIM(LEADING '$' FROM invoices.totalprice), 2) AS totalprice, clients.company, lineitems.invoiceid, FORMAT((lineitems.width * lineitems.height) /144, 2 ) AS sqft, lineitems.quantity AS qty, FORMAT((invoices.totalprice / ((lineitems.width * lineitems.height) /144)), 2) as avgsqftrevenue, FORMAT((TRIM(LEADING '$' FROM invoices.totalprice) / lineitems.quantity), 2) AS avgunitrevenue
    FROM clients
    INNER JOIN invoices ON clients.id = invoices.clientid
    INNER JOIN lineitems ON invoices.id = lineitems.invoiceid
    WHERE invoices.orderdate BETWEEN '".$revenuefrom."' AND '".$revenueto."'
    ORDER BY invoices.id DESC";


    $result = $conn->query($sql);


    echo "<table id='revenueReportA' align='center' class='report_DT'>
    <tr>

    <th>Customer</th>
    <th>SG</th>
    <th>Revenue</th>
    <th>SQ FT</th>
    <th>AVG Revenue Per SQ FT</th>
    <th>Number of Units</th>
    <th>AVG Revenue Per Unit</th>
    </tr>";


     if ($result = $conn->query($sql)) {

        // fetch associative array 
      while ($row = $result->fetch_assoc()) {


         echo "<tr>";
         echo "<td>" . $row['company'] . "</td>";
         echo "<td>" . $row['id'] . "</td>";
         echo "<td>" ."$". $row['totalprice'] . "</td>";
         echo "<td>" . $row['sqft'] ."&nbsp;&nbsp;". "ft<sup>2</sup>". "</td>";
         echo "<td>" ."$". $row['avgsqftrevenue'] . "</td>";
         echo "<td>" . $row['qty'] . "</td>";
         echo "<td>" ."$". $row['avgunitrevenue'] . "</td>";
         echo "</tr>";
         } 

          echo "</table>";

      ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



     //Free the result variable. 
     $result->free();

     }


     //Close the Database connection.
     $conn->close(); 


     ?>

I have tried several different suggestions for sending the values to php but the ajax keeps failing.

Note: I included the other ajax call for revenueto and revenuefrom date. This call is successful and my table displays correctly based off those dates so long as the data for the checkboxes ajax is commented out.

Note 2: apologies as I am new to ajax.

Thank you!

2 Answers 2

1

That $_POST is incorrect. What gets serialized is the name/value of the inputs. The [] in the input name will automatically get picked up by $_POST as an array for the key revenue_checkboxes

try

$revenuecheckboxes = $_POST['revenue_checkboxes'];// should be an array of the checked checkboxes
Sign up to request clarification or add additional context in comments.

4 Comments

Does anybody have any other suggestions for the ajax code?
suggestions for what specifically?
To see if there's a better way to send the information or to see if the issue lies in trying to create the initial array?
What is the specific issue now? If the code isn't working you will need to step into it and do some basic debugging. Check your error logs if you have 500 errors, or learn how to display errors. Learn how to inspect the data in javascript using the built in browser developer tools also
0

your way of getting array $revenuecheckboxes=$_POST('[name="revenue_checkboxes[]"]'); is invalid (dont go with javascript way here ;D) it should be as $revenuecheckboxes=$_POST['revenue_checkboxes'];

php will automatically find that its an array and will initialize 'revenuecheckboxes' to array with its values

2 Comments

I tried changing that section of code, but I'm still experiencing the same issue. When I try to preview the response in the browser, it says it can't preview the response and when I test the URL, the page is broken. I think there's either an issue with the ajax call itself or its an issue try to get the checkboxes arrayed properly. However, I don't know enough about it.
what are you returning in your response is not clear here...may be something later in your code causing the problem..go ahead and edit your question with you php code as well...

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.