With an array like mine below, how can I read the values of only the first line and the loop through the other from the second line onward? I’ve included comments in the code to give you an idea of what I’m trying to achieve.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>PHP, jQuery search demo</title>
<link rel="stylesheet" type="text/css" href="my.css">
<script type="text/javascript" src="http://localhost/dev/ajax/jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".errCheck").click(function() {
$.ajax({
type: "GET",
url: "test_errors.php",
dataType:"json",
cache:false,
success: function(data){
//if 1st line of array: success == True How can I do this?
//Redirect
//else
$('#errors div').empty();
$.each(data, function (loc, msg) {//start from the second array value, in this case errOne
$(loc).html(msg);
});
},
});
return false;
});
});
</script>
</head>
<body>
<div id="container">
<div id="errors">
<div id="errOne"></div>
<div id="errTwo"></div>
<div id="errThree"></div>
</div>
<input type="submit" class="errCheck" value="Check">
</div>
</body>
</html>
My test error messages file:
<?php
$errors['success'] = "false";
$errors['#errOne'] = "Enter a valid username";
$errors['#errTwo'] = "Enter a valid email";
$errors['#errThree'] = "Enter a valid password";
echo json_encode($errors);
?>
You can use shift() to return the first element in an array and remove it from the arrayvar error = data.shift();So, var error will be your check and data can then be used in you $.each()@Joseph Silber – Congratulations on spotting my deliberate mistake above ;-P
Use
As per How do I remove a property from a JavaScript object?
EDIT I guess this is now the same as another answer but I felt like I might as well write the code in…
And use a proper boolean as stated elsewhere
Although I’d prefer to arrange the Json like this
Etc.