1

I'm trying to send data from option selector

<select id="city">
    <option value="{'city':'melbourne','lat':'-37.8602828','long':'144.9631'}">Melbourne</option>

Through an AJAX POST

$.ajax({
    method: "POST",
    url: "action.php",
    dataType: "json",
    data: {
        city: $('#city option:selected').val()
    },
})

However I got an empty $_POST in action.php. What is the correct way to send the value of the selected option through an AJAX request?

3
  • 2
    is value{'city':'melbourne','lat':'-37.8602828','long':'144.9631'}" is valid for value tag? Commented Oct 18, 2016 at 8:45
  • First of all you are missing equals and double quote on options value. Second: can your print the $('#city option:selected').val() and let to know whats the console print for this? Commented Oct 18, 2016 at 8:46
  • i read in another stackoverflow page that its a valid value tag. (page missing) Commented Oct 18, 2016 at 8:50

2 Answers 2

1

You have a missing =" at the option value attribute

<select id="city">
    <option value="{'city':'melbourne','lat':'-37.8602828','long':'144.9631'}">Melbourne</option>

Plus, you can directly access the select value:

$.ajax({
    method: "POST",
    url: "action.php",
    dataType: "json",
    data: {
        city: $('#city').val()
    },
})

At the level of PHP, you have to decode the value of $_POST['city'] to get a mapped PHP array:

$city = json_decode($_POST['city']);
Sign up to request clarification or add additional context in comments.

Comments

0

Could you please try modifying your HTML a bit as:

<option value='{"city":"melbourne","lat":"-37.8602828","long":"144.9631"}'>Melbourne</option>

value attributes value is within single quote and JSON data's key-value pair is in double quotes.

Also once you grab the selected value by .val() we are actually getting data of type string so before sending it; you need to parse it via $.parseJSON(str_value)

$(document).ready(function() {
  var str_value = $('#city option:selected').val();
  alert(str_value);
  alert("typeof str_value: " + typeof str_value);
  var jsonData = $.parseJSON(str_value);
  console.log(jsonData);
  alert("city " + jsonData["city"]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select id="city">
  <option value='{"city":"melbourne","lat":"-37.8602828","long":"144.9631"}'>Melbourne</option>
  <option value='{"city":"melbourne1","lat":"-37.8602828","long":"144.9631"}'>Melbourne1</option>
</select>

Comments

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.