Phil Hudson
Phil Hudson

Reputation: 3901

jQuery returning null - selected option not being posted correctly?

This jQuery script is returning null. I've tried using other syntax for selected options but here's what I've got below:

The script works and runs correctly, allowing me to download the Excel file. However the ID is not being set correctly (via the option selected) and thus is parsing as "0".

<script>
//When Page Loads....
$(document).ready(function(){

  $('#dropdown').change(function(){
    // Call the function to handle the AJAX.
    // Pass the value of the text box to the function.
    sendValue($(this).val());   
  }); 
});

// Function to handle ajax.
function sendValue(str){
  // post(file, data, callback, type); (only "file" is required)
  $.post(
    "scripts/export_to_excel/index.php", //Ajax file
    { sendValue: str },  // create an object will all values
    //function that is called when server returns a value.
    function(data){
      $('#linkDiv').html(data.returnValue);
    }, 
    //How you want the data formatted when it is returned from the server.
    "json"
  );
}
</script>

Select HTML

<p>Select event for export to Excel:</p>
<p>
  <select name="eventIDExport" id="dropdown"> 
    <option value=0> 
    <?=$options?> 
  </select>
</p>
<?php var_dump($_POST['eventIDExport']); ?>
<div id="linkDiv"></div>

Rendered mark-up

<p>Select event for export to Excel:</p>
<p>
  <select name="eventIDExport" id="dropdown"> 
    <option value=0> 
    <option value="1">BIG event</option>
    <option value="54">2013 Network Conference</option>
  </select>
</p>
NULL
<div id="linkDiv"></div>

Some of the code in index.php to process Ajax request - I think this is triggering the null value?

if (isset($_POST['eventIDExport']))
{
$eventIDExport = $_POST['eventIDExport'];
}else{
$eventIDExport = "";    
}

Upvotes: 0

Views: 717

Answers (1)

Gabriel Santos
Gabriel Santos

Reputation: 4974

Why you POST sendValue and check if eventIDExport is set?

$.post("scripts/export_to_excel/index.php", {
    sendValue: str
    ^^^^^^^^^

and

if (isset($_POST['eventIDExport']))
                  ^^^^^^^^^^^^^

Your code should be:

if(isset($_POST['sendValue']))
{
    $eventIDExport = $_POST['sendValue'];
} else {
    $eventIDExport = "";
}

or

$.post("scripts/export_to_excel/index.php", {
    eventIDExport: str

Upvotes: 1

Related Questions