I've been handling success/error messages by returning json encoded arrays as a response, but it suddenly occurred to me that this probably isn't the correct way of handling notifications.
For example, my controller will look like this:
public function controller_name() {
//validate form input
$this->form_validation->set_rules('id', 'id', 'required|is_natural_no_zero');
// if validation was successful with no errors
if ($this->form_validation->run() && $this->model_name->method()) {
$this->data['status'] = 'success';
$this->data['message'] = 'This is the success message';
echo json_encode($this->data);
} else {
$this->data['status'] = 'error';
$this->data['message'] = validation_errors();
echo json_encode($this->data);
}
}
Then the jQuery:
$.ajax({
url: url,
type: 'POST',
data: data,
success: function (r) {
json = $.parseJSON(r);
if (json.status == 'success') {
if (json.message == 'added') {
$this.addClass('success');
} else {
$this.removeClass('success');
}
} else {
console.log('There was an error')
}
What's the best practice way to do this? Can I throw exceptions to use the ajax error?
Sending erroneous http status code should trigger the jQuery ajax error handler:
public function controller_name() {
//validate form input
$this->form_validation->set_rules('id', 'id', 'required|is_natural_no_zero');
// if validation was successful with no errors
if ($this->form_validation->run() && $this->model_name->method()) {
$this->data['message'] = 'This is the success message';
} else {
$this->output->set_status_header('400'); //Triggers the jQuery error callback
$this->data['message'] = validation_errors();
}
echo json_encode($this->data);
}
JS:
$.ajax({
url: url,
type: 'POST',
data: data,
success: function (r) {
var json = $.parseJSON(r);
},
error: function( jqXhr ) {
if( jqXhr.status == 400 ) { //Validation error or other reason for Bad Request 400
var json = $.parseJSON( jqXhr.responseText );
}
}
});
Related
When I run this script, instead of the error inserting HTML in the page, it returns an alert like the success function - but with the error message instead.
AJAX
$(function() {
$('form').submit(function() {
$page_title = $('input[name="page_title"]').val();
$.ajax({
method: 'GET',
url: 'test-script.php',
datatype: 'jsonp',
jsonp: 'jsonp_callback',
data: {
page_title: ($page_title),
},
success: function(result){
alert(result);
},
error: function(result) {
$('#error').html('result');
}
});
});
});
PHP
<?php
if(isset($_GET)) {
if (! empty($_GET['page_title'])) {
$title = $_GET['page_title'];
print $title;
} else {
$error = ('Name required');
print $error;
}
}
add a http_response_code(); to your php to tell js, that there was an error. Also you better should send back a json encoded error string, that can be understood by javascript.
<?php
if(isset($_GET)) {
if (! empty($_GET['page_title'])) {
$title = $_GET['page_title'];
echo $title;
} else {
http_response_code(400);
$error = ["message"=>"Name required"];
echo json_encode($error);
}
}
See the list of appropriate response codes
EDIT:
Response to your comment "the HTML is inserted... then disappears"_:
You need to prevent the form from beeing submitted. To do that add event.preventDefault() to your onSubmit handler:
$('form').submit(function( event ) {
event.preventDefault();
// rest of your code...
This is the event that will trigger the login
$('#btnLogin').click(function(){
//var data = $('#loginForm').serialize();
var email = $('#loginEmail').val();
var password = $('#loginPass').val();
var result = '';
if( email.trim() =='' ){
//username.addClass('alert-danger');
alert('email is required');
}else{
//username.removeClass('alert-danger');
result +='1';
}
if( password.trim()==''){
alert('password is required');
}else if(password.length < 8){
alert('password length must be atleast 8 characters');
}else{
//password.removeClass('alert-danger');
result +='2';
}
/*var postData = {
'email' : email,
'password' : password
};*/
if (result=='12') {
$.ajax({
type: "POST",
url: '<?php echo site_url('login/identifying_usertype'); ?>',
data: { email : email, password : password },
dataType: 'json',
success: function(response){
//console.log(response);
//alert(email);
$('#myModal').modal('hide');
},
error: function (XHR, status, error){
console.log('error', error);
}
});
}
});
This is my controller:
public function identifying_usertype()
{
if( $email = $this->input->post('email') )
{
echo json_encode( array('email' => $email) );
}
else
{
echo json_encode( array('error' => 'No email address') );
}
}
Now im getting {"error":"No email address"} on my console there's no error. Is there something I'm missing? on my ajax i added dataType: 'json', i changed the url from base_url to site url
Since you have success: function(response){, the return value of the Ajax is on the variable response and not on email. So doing this will fix your issue:
success: function(response){
email = response;
alert(email);
//$('#myModal').modal('hide');
},
1) The best way to create a link to one of your own controller/methods in CodeIgniter is to use site_url(), not base_url(). With site_url, your url becomes:
url: '<?php echo site_url('login/identifying_usertype'); ?>',
2) jQuery's $.ajax needs you to declare a dataType. Although if you leave it out jQuery will attempt to guess what it is, I've found it's wrong many times. Most people will use 'json':
dataType: 'json',
3) In your controller, if you are declaring that you want a json dataType, then it's really easy to send that back as the response:
echo json_encode( array('email' => $email) );
4) In your ajax success function, you can then do like this:
success: function( response ){
if( response.email ){
console.log(response.email);
}else{
console.log('email not verified');
}
}
5) Lastly, you are not showing code that would create an event to execute your ajax. If you need help with that, let me know and I'll show you.
6) All of the network traffic is available for you to view in your browser's console. Check it, as it is very helpful when creating these ajax requests.
Regarding your comment, how about this in the controller:
public function identifying_usertype()
{
if( $email = $this->input->post('email') )
{
echo json_encode( array('email' => $email) );
}
else
{
echo json_encode( array('error' => 'No email address') );
}
}
I need help. I am getting problem in returning value from Codeigniter. Whenever, I use exit; after echo it work fine but whenever i try return true it's dosen't work.
Same as i have comment code in PHP code. if i use exit after echo it works but if i don't do that it returns nothing
Ajax Request
$('#social-form').on('submit', function(e){
e.preventDefault();
var str = $( "#social-form" ).serialize();
if (str === '') {
swal("Please Fill All Fields");
} else {
$.ajax({
type: "POST",
url: baseUrl + "/admin/social/",
data: str
})
.done(function (data) {
console.log(data);
swal("Information", data, "info");
})
.error(function () {
swal("Oops", "We couldn't connect to the server!", "error");
});
}
});
Codeigniter-3
public function social(){
$name = $this->input->post('name');
$profile = $this->input->post('profile');
$this->form_validation->set_rules('name', 'name', 'required|trim');
$this->form_validation->set_rules('profile', 'profile', 'required|trim');
if ($this->input->post() && $this->form_validation->run() != FALSE) {
$this->load->model('Social_model','social');
$this->social->update($name,$profile);
echo 1;
//exit;
//return true;
}
else
{
echo 0;
//exit;
//return false;
}
}
CodeIgniter has a layout, so after outputting a response there could be views that are outputted after your response, such as a footer or a debug bar.
Try using your console to see the status code of the response. Also note that it isn't bad practice in CodeIgniter to exit after AJAX calls, so perhaps you should just write a AJAX response helper which does all that for you (like setting the header and adding the exit).
You probably need to be more specific about what you echo. This is one of several possible solutions.
controller
public function social(){
$name = $this->input->post('name');
$profile = $this->input->post('profile');
$this->form_validation->set_rules('name', 'name', 'required|trim');
$this->form_validation->set_rules('profile', 'profile', 'required|trim');
if ($name && $this->form_validation->run() != FALSE) {
$this->load->model('Social_model','social');
$this->social->update($name,$profile);
$out = json_encode(array('result' => 'success'));
}
else
{
$out = json_encode(array('result' => 'failed'));
}
echo $out;
}
javascript
$('#social-form').on('submit', function (e) {
e.preventDefault();
var str = $("#social-form").serialize();
if (str === '') {
swal("Please Fill All Fields");
} else {
$.ajax({
type: "POST",
url: baseUrl + "/admin/social/",
data: str,
dataType: 'json'
})
.done(function (data) {
console.log(data);
if (data.result === 'success') {
swal("Information", "Success", "info");
} else {
swal("Information", "Failed", "info");
}
})
.error(function () {
swal("Oops", "We couldn't connect to the server!", "error");
});
}
});
I don't think I am passing the variable the right way between my separate PHP and AJAX files.
I am debugging this by triggering the second condition $status = 'info'; in my PHP file.
Currently, status is coming up as "undefined" for alert(data.status);
signup_process.php
if (condition){
$status = 'success';
else {
$status = 'info';
}
AJAX
function send() {
var data = $('#signup_form').serialize();
$.ajax({
type: "POST",
url: "signup_process.php",
data: data,
success: function (data) {
alert(data.status);
if (data.status == 'success') {
// everything went alright, submit
$('#signup_form').submit();
} else if (data.status == 'info')
{
console.log(data.status);
$("label#email_error").show();
return false;
}
}
});
return false;
};
I know that the 2nd condition is being triggered because I put a header redirect there just for testing and it worked fine.
Good to use json while return back data from php to ajax.
$return_data = array();
if (condition){
$return_data['status'] = 'success';
} else {
$return_data['status'] = 'info';
}
echo json_encode($return_data);
exit();
Now, if you are return back json data to ajax, then you need to specify return data type into ajax call as below
function send() {
var data = $('#signup_form').serialize();
$.ajax({
type: "POST",
url: "signup_process.php",
data: data,
dataType: 'json',
success: function (data) {
alert(data.status);
if (data.status == 'success') {
// everything went alright, submit
$('#signup_form').submit();
} else if (data.status == 'info')
{
console.log(data.status);
$("label#email_error").show();
return false;
}
}
});
return false;
};
You should send a JSON object back from php:
$data = array();
if (condition){
$data['status'] = 'success';
else {
$data['status'] = 'info';
}
header('Content-type: application/json');
echo json_encode($data);
The json_encode() method converts the array to a JSON object so you can access each array key by name on the js side.
this works:
$.ajax({
type: 'POST',
url: 'register.php',
data: {captcha: captcha
},
success: function() {
$('#loading').hide();
$('#success').fadeIn();
}
error: function() {
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
});
sends captcha response to PHP and if entered correctly, you can register. problem is, is that if you incorectly enter your captcha, the JQuery still runs the functions for a successful run although the PHP ran a "die" and did nothing.
In PHP, if the captcha is entered incorrectly is does this
if (!$resp->is_valid) {
die ("false");
}
else
{
register
}
How do I request the error that PHP spits out so I can do something like?
success: function(find error) {
if(error == "false")
{
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
else
{
$('#loading').hide();
$('#success').fadeIn();
}
}
EDIT!:
With your help heres what it looks like now and it works fantastic!!
$.ajax({
type: 'POST',
url: 'register.php',
dataType: "json",
data: {
challenge: challenge,
response: response,
zip: zip
},
success: function(result) {
if (!result.success) {
$('#loading').hide();
$('#captcha').fadeIn();
$('#catErrorB').fadeIn();
}
else {
$('#loading').hide();
$('#success').fadeIn();
}
}
});
and the PHP
if (!$resp->is_valid) {
$response = array(success => false);
echo json_encode($response);
}
else
{
$response = array(success => true);
echo json_encode($response);
Ya'll are the coolest. My first JQuery I've ever done, It's came out so awesome. This site rules!
I wouldn't use success/failure. Even if the script dies it is still going to return a 200 SUCCESS to your ajax call.
Use JSON to return responses depending on whether or not it is a success and parse and proceed with correct logic
<?php
if ( $resp->is_valid ) {
echo json_encode( array( 'status' => 'true' ) );
} else {
echo json_encode( array( 'status' => 'false' ) );
}
?>
Then you can parse the response in your AJAX call. Remember, if you call die('false'); that is still going to return a success message to your ajax function.
PHP:
if (!$resp->is_valid) {
$response = array(success => false);
echo json_encode($response);
}
else {
$response = array(success => true);
echo json_encode($response);
}
jQuery:
success: function(result) {
if (!result.success) {
// Wrong input submitted ..
}
else {
// Correct input submitted ..
}
}