Return errors from PHP run via. AJAX?
I don't know about jQuery, but if it distinguishes between successful and unsuccessful (HTTP 200 OK vs. HTTP != 200) Ajax requests, you might want your PHP script respond with an HTTP code not equal to 200:
if ($everything_is_ok) { header('Content-Type: application/json'); print json_encode($result); }else { header('HTTP/1.1 500 Internal Server Booboo'); header('Content-Type: application/json; charset=UTF-8'); die(json_encode(array('message' => 'ERROR', 'code' => 1337))); }
$return = array();$return['msg'] = "Could not connect to DB";if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'){ header('Cache-Control: no-cache, must-revalidate'); header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); header('Content-type: application/json'); die(json_encode($return));}
try this out. Hope it helps.
<!-- This is index.php ---><html> <head> <script src="js/jquery.js" type="text/javascript"></script><!-- link to jQuery --> <script language="javascript"> $(document).ready(function () { $('input#send').click(function(){ /* Empty div#error and div#result incase they contain info from the last submission */ $('#error').empty(''); $('#result').empty(''); /* Client-side validation */ var name = $("input#name").val(); var age = $("input#age").val(); if (name==''){ alert('Insert your name.'); } else if (age==''){ alert('Insert your age.'); } else { var params = 'name=' + name + '&age=' + age; $.ajax({ url:'b.php', type:'post', dataType:'html', data:params, cache: false, success:data }); function data (html) { var $html = $( html ); // create DOM elements in a jQuery object /* Return errors from 'b.php' */ $html.filter('#err').appendTo("#error"); /* Return valid Post */ $html.filter('#res').appendTo("#result"); /* Clear name input */ $('input#name').val(''); /* Clear age input */ $('input#age').val(''); } } }); }); </script> <style type='text/css'> #error{ color:maroon; font-weight:bold; } #result{ color:green; font-weight:bold; } </style> </head> <body> <div id="error"></div><!-- View Errors --> <div id="result"></div><!-- View valid Post --> <input type='text' name='name' id="name" value='' /><br/ > <input type='text' name='age' id="age" value='' /><br/ > <input type='submit' name='send' id="send" value='Send' /> </body>
<?php/* This is b.php */if(($_POST['name']=='')||($_POST['age']=='')){ $error = '<div id="err">Error: Fill in ALL fields.</div>';} elseif(is_numeric($_POST['name'])){ $error = '<div id="err">Error: Name should NOT contain numbers.</div>';} elseif(!is_numeric($_POST['age'])){ $error = '<div id="err">Error: Age should ONLY contain numbers.</div>';} else{ $result = '<div id="res">Hi '.$_POST['name'].', you are '.$_POST['age'].' years old.</div>';}echo $error;echo $result;?>