0

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. enter image description here

Community
  • 1
  • 1
batuman
  • 7,066
  • 26
  • 107
  • 229
  • 1
    Suggested Reading: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – wogsland Jan 05 '16 at 04:19
  • search your code file if there any other field named 'bedrooms' – Jswq Jan 05 '16 at 05:20
  • 1
    @batuman : first of all debug this code step by step. inside of **sendtoServer** function in javascript.... type below lines to see what is being passed to server. and make that data correct first. `console.log($("form").serialize());` – Mayur Chauhan Jan 05 '16 at 05:44
  • @MayurChauhan, I did that and found that there are some repeated info sent to server. Why it is like that? I put into EDIT. Thanks – batuman Jan 05 '16 at 06:49

3 Answers3

1

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.

Jonathan Head
  • 428
  • 3
  • 7
  • Thank for the suggestion. I have all those you suggested, but to reduce the size of code in this disucssion, I just didn't show. Your suggestion is good to check serialized data. – batuman Jan 05 '16 at 06:11
  • I found the problem and posted in EDIT. – batuman Jan 05 '16 at 06:44
0

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());
 });     
})
Muhammad Atif
  • 1,050
  • 1
  • 9
  • 21
0

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
}
?>