tags:

views:

32

answers:

1

I'm having some problems displaying error messages that are being passed from a php file through an ajax request.

The problem is when I receive less than 3 errors messages that are supposed to be displayed in an unordered list. I don't want to display any "undefined" variables - that's why I'm not adding them to the unordered list through one statement.

Any suggestions?

calculator.html

 <div id="calculator">
 <form>
     <input type="text" name="years"/>
     <label>How many years have you smoked for?</label><br />

     <input type="text" name="smokes"/>
     <label>How many cigarettes do you smoke each day?</label><br />

     <input type="text" name="price"/> 
     <label>How much do you spend on each pack of cigarettes?</label><br />

     <input type="submit" value="Show My Totals" name="submit" />
 </form>

 <div id="result"></div> 
 </div><!-- end calculator -->

calculator.js

 $(function(){  
    $("#calculator form").submit(function(){
        dataString = $("#calculator form").serialize();

        $.ajax({
        type: "POST",
        url: "./calc.php",
        data: dataString,
        dataType: "json",
        success: function(data) {
            if(data.totalSmoked != null && data.totalSmoked != undefined &&
            data.totalCost != null && data.totalCost != undefined &&
            data.totalWeight != null && data.totalWeight != undefined)
            {
                $("#calculator #result").html("<ul><li>" + data.totalSmoked + "</li><li>" + data.totalCost + "</li><li>" + data.totalWeight + "</li></ul>");
            }
            else 
            {
                $("#calculator #result").html("<ul>");

                if(data.yearsError != null && data.yearsError != undefined) {
                    $("#calculator #result ul").html("<li>" + data.yearsError + "</li>");
        }

        if(data.smokesError != null && data.smokesError != undefined) {
                    $("#calculator #result ul").html("<li>" + data.smokesError + "</li>");
        }

        if(data.costError != null && data.costError != undefined) {
            $("#calculator #result ul").html("<li>" + data.costError + "</li>");
        }

        $("#calculator #result").html("</ul>");

            /**** If I replace the above content within the 'else' block, it works however - This will display an "undefined" variable if there are less than 3 errors ****/
            //$("#calculator #result").html("<ul><li>" + data.yearsError + "</li><li>" + data.smokesError + "</li><li>" + data.costError + "</li></ul>");
            }

        }
        });
        return false;  

    });  
});  

calculator.php

$yearsSmoked  = $_POST['years'];  
$smokesPerDay = $_POST['smokes'];  
$costPerPack  = $_POST['price'];  
$errors       = array();  
$results     = array();  


/**  
*  
*  
* A bunch of error checking here...  
*  
*  
*/  


if(!empty($results)) {  
    echo json_encode($results);  
}  
elseif(!empty($errors)) {  
    echo json_encode($errors);  
}  

UPDATE

I imagine it didn't work because I specified array keys in my php file. Adding this to my else block worked...kind of any ugly way.

if(data['yearsError'] != undefined) {
    $("#calculator #result ul").append("<li>" + data['yearsError'] + "</li>");
}

if(data['smokesError'] != undefined) {
    $("#calculator #result ul").append("<li>" + data['smokesError'] + "</li>");
}

if(data['costError'] != undefined) {
    $("#calculator #result ul").append("<li>" + data['costError'] + "</li>");
}
+1  A: 

Looks like that $error array in PHP is just a series of error messages, right? Since it's an array in PHP, it'll be an array on the Javascript side. You could just loop over it for a foreach loop and spit out a <li> for each element found.

You could also change your output data structure and combine both into a single message, rather than trying to detect what version of the message you sent. That way both your regular data and error structures are always present.

PHP-side:

$data = array();
$data['data'] = array(
    'totalSmoked' => 0,
    'totalCost' => 0,
    'totalWeight' => 0
);
$data['errors'] = array();
$data['errors'] = 'You smoked -1 packs? How's that possible?' // sample error message

Javascript side:

// this would only run if data.errors has a non-0 length, ie: there's error messages
for(i = 0; i < data.errors.length; i++) {
    $("#calculator #result ul").append('<li>' + data.errors[i] + '</li>'); // or whatever it would be in jquery
}
Marc B
Thanks for the tips Marc. I had already tried the for loop and have just tried it again and receive this message in my error console: data.errors is undefined.I'm not too familiar with json and can't seem to access the array this way.
Kenny Powers
Try spitting out the returned json data with `alert()` or `console.log` and see what's actually being returned.
Marc B