0

My complete script is as follows

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>        
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script type="text/javascript">
        $(window).on('load',function(){
            $('#myModal').modal('show');
        });
    </script>
    <script>
        $( document ).ready(function () {
            $("#vote").click(function (e) {
                var poll_id = $('input[name=pollID]', '#myForm').val();
                var poll_option_id = $('input[name=voteOpt]:checked', '#myForm').val() ;
                //alert(poll_id + "AND" + poll_option_id);
                $.ajax({
                    type: "POST",
                    url: "http://localhost/poll/index.php/form/poll",
                    data: {poll_id: poll_id, poll_option_id: poll_option_id},
                    dataType: "json",
                    success: function(data) {
                        alert(data);
                    }, error: function() {
                        alert("ERROR");
                    }
                });
            });
        });
    </script>

And I have the following inside poll function in form controller

public function poll() {
        $pollid = $this->input->post('pollID');
        $voteData = array(
            'poll_id' => $pollid,
            'poll_option_id' => $this->input->post('voteOpt')
        );
        $voteSubmit = $this->modal->vote($voteData);
        if($voteSubmit){ 
            echo 'Your Vote Has Been Submitted successfully.';
        }else{
            echo 'You Had Already Voted.';
        }

}

Now the thing is that, modal is executing perfectly on page load. But ajax is not working neither success part is executing nor error. Also on uncommenting the alert before ajax, correct values are alerted. I cannot figure the error. Please help

0

4 Answers 4

2

I can see there are many javascript libraries included. Very sure some of them are conflicting. Try this before $(document).ready():-

$.noConflict();

After looking at your form controller code, I can see you are just returning a text. So ajax dataType should be HTML and not json. dataType parameter is to define the type of return value. I can only see this one wrong point in your code. Your console response status is also fine, which means it is the dataType which is wrong.

dataType = The data type expected of the server response.

dataType:'html'
Sign up to request clarification or add additional context in comments.

3 Comments

On alerting error i.e., through alert(JSON.stringify(data)); it alerts {"readyState":4,"responseText":"\r\n\r\n","status":200,"stat‌​usText":"OK"}
Yup you are correct, now poll_id and poll_option_id values are not being accessed in function poll when I tried to print their values using print_r
just use $_POST instead of $this->input->post to access values. If you are returning text then put dataType as html in ajax.
1

For Example.

See you can check is you script is actually sending post values or not these way.

Example

In you console > Network Tab. You can view which post values are sent as POST.

Now I had code in PHP Codeigniter and for me following code worked fine.

$("#username").keyup(check_if_username_exists);

    function check_if_username_exists() {

    var username = $("#username").val();

    var sRet = false;

    $.ajax(
     {
        type:"post",
        async: false,
        url: "<?php echo site_url('distributor/tenant/check_username_exists'); ?>",
        data:{ username:username},

        success:function(response)
        {   

            var parent_fieldset = $("#username").parents('fieldset');
            $("#username").parent().addClass('has-error');

            if (response == "true") 
            {
                $('#span').html('<span style="color: #0fa7b5;">'+"Login Username"+"</span>");

                $("#username").removeClass('input-error');

                $("#username").parent().removeClass('has-error');

                console.log('Success! This Username is available');

                hideToastr();

                sRet = true;

            }
            else 
            {   
                show_error("Error","Oops! This Username is already taken");

                $("#username").addClass('input-error');

                $('#span').html('<span style="color:red;">Username already Exists!</span>');

                console.log('Oops! This Username is already taken');     

                sRet = false;
            }  


        }
      });

    console.log("End Of Username Exists " + sRet);
    return sRet;
}

Also there is third party application POSTMAN which will help your debug your application. It allows you to sent post data with form values.

Update

Also I think you might have multiple JS files include issue or problem with the order they are placed. FYI I used only bootstrap.js and jquery.min.js and everything worked fine. So try removing

<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>

UPDATE 2 :

Now for your controller I don't see where you encode or decode your json data. If Your are sending the values as JSON POST to your controller then you must decode it.

First Check is you are getting JSON data in your controller. If its working fine, then try for second step. Step 1:

public function poll() {
        $polldata = json_decode($_POST);

        echo $polldata;

} 

Step 2:

public function poll() {


        $polldata = json_decode($_POST);

        echo $polldata;
        $pollid = $polldata->pollID;
        $voteData = array(
            'poll_id' => $pollid,
            'poll_option_id' => $polldata->pollID->voteOpt
        );
        $voteSubmit = $this->modal->vote($voteData);
        if($voteSubmit){ 
            echo 'Your Vote Has Been Submitted successfully.';
        }else{
            echo 'You Had Already Voted.';
        }

} 

Let me know if you face any issues.

6 Comments

On alerting error i.e., through alert(JSON.stringify(data)); it alerts {"readyState":4,"responseText":"\r\n\r\n","status":200,"stat‌​usText":"OK"}
Where is your json encoding of string ??? I guess you are using PHP so where do you encode your json data ? Can you post your PHP Code where you encode your data
my php function poll is already in the question where data is being submitted
Yes i can see that but where is your json encoding and decoding ?? I am posting an update to my answer
after changing dataType from json to html it did worked and success function is called but the values of poll_id and poll_option_id are not being accessed inside function poll
|
0

Your pool if should be like

   if($voteSubmit){ 
                echo json_encode(array('msg' =>'Your Vote Has Been Submitted successfully.'));
            }else{
                echo json_encode(array('msg' =>'You Had Already Voted.'));
            }

and ur ajax success should be like

 success: function(data) {
                    alert(data.msg);
                }, 
error: function() {
                    alert("ERROR");
                }

Comments

0

//change your Poll function

public function poll() {
    $this->output->set_content_type('application/json');
    $pollid = $this->input->post('pollID');
    $voteData = array(
        'poll_id' => $pollid,
        'poll_option_id' => $this->input->post('voteOpt')
    );
    $voteSubmit =$this->modal->vote($voteData);
    if($voteSubmit){ 
        $this->output->set_output(json_encode(array('msg' => 'Your Vote Has Been Submitted successfully.')));
    }else{
        $this->output->set_output(json_encode(array('msg' => 'You Had Already Voted.')));
    }
}

And a small change in success callback of Ajax

success: function(data) {
    alert(data.msg);
    //option to view data in console log
    console.log(data);
},

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.