简体   繁体   中英

How to send SELECT element to server using AJAX

I have an issue in checking form element SELECT at server PHP code .

I found a similar link here, but it is slightly different in discussion. My HTML code is

<body>
<div id="header">
<h1>Please add your landed property to advertise</h1>
</div>

<div id="background">
<form name="advertiseForm"  id="advertiseForm" method="post" >


<br /><br /><br />
<select name="stories"  id="stories"  required="required"/>  
     <option value="Stories" >Number of stories</option>  
     <option value="1">1</option> 
     <option value="2">2</option> 
     <option value="3">3</option>
     <option value="4">4</option> 
     <option value="morethan4">More than 4</option>
<select/>  
<label for="stories">Please select for number of stories</label>
<div  id="stories-error" class="error-box" style="color:#FF0000"></div>

<br /><br /><br />
<select name="bedrooms" id="bedrooms" required="required"/>  
     <option value="Bedrooms" >Number of bedrooms</option>  
     <option value="1">1</option> 
     <option value="2">2</option> 
     <option value="3">3</option>
     <option value="4">4</option> 
     <option value="5">5</option>
<select/>  
<label for="numbedrooms">Please select for number of bedrooms</label>
<div  id="bedrooms-error" class="error-box" style="color:#FF0000"></div>
</form>
</body>

I have two SELECT elements at my form and form elements are sent to server using AJAX using data: $("form").serialize(), .

</body>
<script>
function sendtoServer() {
     $.ajax({
        url: "advertisementdatavalidationatserver.php",
        type: "POST",
        data: $("form").serialize(), 
        success:  function(ret){
            alert(ret.message);
            if(ret.error == true){ 

              if(ret.message.indexOf("Storieserror")>=0){
                  $('#stories-error').css('display', 'block');
                  $('#stories-error').html('Please enter number of stories at your building');
              }else{
                  $('#stories-error').html(''); 
              }

              if(ret.message.indexOf("Bedroomserror")>=0){
                  $('#bedrooms-error').css('display', 'block');
                  $('#bedrooms-error').html('Please enter number of bedrooms at your building');
              }else{
                  $('#bedrooms-error').html(''); 
              }
         }else{

              $('#stories-error').html(''); 
              $('#bedrooms-error').html('');

           }
        },
        error: function(){
           // the AJAX request failed as in timed out / bad url etc.
        } 
   });
}
</script>
</html>

My PHP code at server side for validation is

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

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

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

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

}

// 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);
?>

The problem here is for SELECT for bedrooms , no matter how I change option values to 1,2,3,4,.., the server side always comes back as Bedroomserror , that means no matter how I change other option values, client side always send 'Bedrooms' value to server. Stories is working fine . What could be the problem?

EDIT: Now I found my problem. I see the serialized data as

alert($("form").serialize());

What the serialized data is shown in the attached image, interesting thing there is there are repeated data (underlined). The first one is fine stories=3&bedrooms=2&bathrooms=2 . Then there is another repeated message with bedrooms=Bedrooms&bathroom=Bathrooms , I think my PHP code caught the second one and the value is never changed. 在此处输入图片说明

When recreating your code for testing here, I did not encounter the problem you describe. Selecting a numbered option for bedrooms did not display an error, and the returned value was correct.

To troubleshoot this type of issue, I'd suggest the following:

  • Make sure the values being serialized by your sendToServer javascript function are what you expect. Output them via console.log() or similar to check that what you select in the form is actually being sent to the PHP script.

I had to makes some changes to the code you provided to get it working. My assumption here is that you already have this in place, but it's not included in your question so I've referenced the changes I made below, as they were required to get the test working:

  • Add a valid DOCTYPE and head tag to the HTML markup
  • Add an input button to the form for submission
  • Add a script tag which pulls in jQuery
  • Wrap the call to your sendToServer function in a $(document).ready(function(){}); call, triggered by a click event on the input submit element (or however you submit the form)
  • [Optional] I added an else section after your if statement checking the $_POST['bedrooms'] value, so that I could check what the selected value was

Hope this helps.

in your html form code place a hidden field

<input type="hidden" id="bedroomsVal" name="bedroomsVal" value="" />

in php code check value of bedroomsVal

if ($_POST['bedroomsVal'] == "Bedrooms"){
            //your logic       
        }

in js do this

$(document).ready(function(){
 $("#bedroomsVal").val($("#bedrooms option:selected").text());
 $("#bedrooms").change(function(){
 $("#bedroomsVal").val($("#bedrooms option:selected").text());
 });     
})

At the first step you need to pass the parameters from your AJAX code to PHP page. then you can check the posted value in your PHP section.

HTML

<select name="stories"  id="stories"  required="required"/>  
 <option value="Stories" >Number of stories</option>  
 <option value="1">1</option> 
 <option value="2">2</option> 
 <option value="3">3</option>
 <option value="4">4</option> 
 <option value="morethan4">More than 4</option>
</select>
<select name="bedrooms" id="bedrooms" required="required"/>  
 <option value="Bedrooms" >Number of bedrooms</option>  
 <option value="1">1</option> 
 <option value="2">2</option> 
 <option value="3">3</option>
 <option value="4">4</option> 
 <option value="5">5</option>
<select/>

JavaScript

<script>
function sendtoServer() {
    $.ajax({
       url: "advertisementdatavalidationatserver.php",
       type: "POST",
       data: {story: $('#stories').val(), bedroom: $('#bedrooms').val()}, 
       success:  function(ret){
           // Any logic when return TRUE;
       },error: function(){
           // the AJAX request failed as in timed out / bad url etc.
       } 
    });
}

PHP

Check the all posted parameters

<?php 
if(! isset($_POST)){
    // return FALSE;
}
else
{
    // check the posted parameters
    // write your query;
    // return TRUE or retrieved value
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM