0

im trying to submit a form on ajax success under if-else statement but it is not working i dont understand why? see the code below

$.ajax({
            type: "POST",
            url:'<?php echo base_url() ?>signup/order_validations',
            data:$("#orderform").serialize(),
            dataType: 'json',
            success: function (data) {
                if(data.length > 0){
                    $(".err").html(data);
                    $(".err").show();
                    $('html, body').animate({scrollTop: $(".progras-bar-area").offset().top}, 800);
                }else{
                    $("#orderform").submit();
                }

            },
            error:function(){
              $(".err").html("Something went wrong...Please try again."); 
            }
        });
Wasif Khalil
  • 2,217
  • 9
  • 33
  • 58

2 Answers2

1

Is the back end doing what you expect it to do?

In your signup/order_validations controller, write a simple test:

public function order_validations(){
    echo json_encode(array("test"=>"test"));
}

Then, in your AJAX call, try to echo the result:

success: function (data) {
    console.debug(data);
    alert(data);
}

and check this in your Chrome/Firefox console.

Now you know what you're returning, you should be able to control it properly.

Also, wouldnt it be easier to handle the form submission by sending the data to the back end in your AJAX response rather than submitting it again seperately??

RonnyKnoxville
  • 6,166
  • 10
  • 46
  • 75
0

It looks like you are trying to get the length of a json object, which will always return as undefined or 0 because it is not an array.

You can do this to get the count:

var count = Object.keys(data).length;
if(count > 0) {
   //your code here
}

There is a lot more detail here: How to list the properties of a JavaScript object

Alternately you can use something like underscore.js. It will allow you to check the size, like so:

_.size(data);
Community
  • 1
  • 1
spacebean
  • 1,554
  • 1
  • 10
  • 13