3

Hello guys I have a problem in getting the response from my ajax. If I display it in the console. I can view it. But How do I assign it in a variable?

Here's what I have. In my PHP code I have this

public function checkPassword($password){

            $username = $this->session->userdata('username');
            $validate = $this->members_model->checkPassword($password,$username);

            echo $validate;

}

In my jquery I have this

$('#existing').on('keyup',function(){

            var id = '<?php echo $this->session->userdata("user_id"); ?>';
            var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';

            $.ajax({
                type: 'POST',
                url: password_url,
                data: '',
                dataType: 'json',
                success: function(response){

                var g = response;
                if(g == 1){
                    $('#existing_info').html('Password is VALID'); //Doesn't display the VALID if the response is 1. Why?
                }else{
                    $('#existing_info').html('Password is INVALID!');
                }

                }

            });

        });
Jerielle
  • 7,144
  • 29
  • 98
  • 164
  • 1
    use `window.k = response` – rab Dec 05 '13 at 06:34
  • @rab are you sure that bumping a variable to global scope is a good way to access it later? How would you know it's been set? It's being set by a click event that may or may not happen after an asynch request. – HMR Dec 05 '13 at 06:35
  • post the json response – Jai Dec 05 '13 at 06:44
  • Actually it is not a json. The response is 1 or 0 only. – Jerielle Dec 05 '13 at 06:47
  • @Jerielle Try adding content type as json . See my answer http://stackoverflow.com/questions/20393093/how-to-get-the-ajax-response-from-success-and-assign-it-in-a-variable-using-jque/20393114#20393114 – Subin Jacob Dec 05 '13 at 07:09
  • If you don't want to return json, then remove both dataType and contentType. Otherwise jQuery will try to parse object from json. – Subin Jacob Dec 05 '13 at 07:13
  • Also you will be getting a string as response, but you are comparing with a numeric. try `g == '1'` instead `g == 1` – Subin Jacob Dec 05 '13 at 07:16

10 Answers10

5
$.ajax({
        type: 'POST',
        url: password_url,
        data: '',
        dataType: 'json',
        success: function(response){
           var k=response;

           if(k.indexOf("1") != -1)
             $('#existing_info').html('Password is VALID');
           else
              $('#existing_info').html('Password is INVALID!');
        }
    });

response is in response variable of success function.

indexof returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex, returns -1 if the value is not found.

Prateek
  • 6,785
  • 2
  • 24
  • 37
  • Same output. The console output is correct but it doesn't display the correct message. If 1 display VALID if 0 display INVALID. But whether the response is 1 or 0. I always end up with INVALID – Jerielle Dec 05 '13 at 06:52
  • Ok it works thanks. I still confused with the code your code. But thank you very much for the right answer. :) – Jerielle Dec 05 '13 at 07:11
3

try something like this

   <script>
        var k = null;
        $(function(){
            $('#existing').on('keyup',function(){
                var id = '<?php echo $this->session->userdata("user_id"); ?>';
                var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';

                $.ajax({
                    type: 'POST',
                    url: password_url,
                    data: '',
                    dataType: 'json',
                    success: function(response){
                        if(response == 1){
                            k = response;
                        }
                    }

                });

            });
        })
   </script>
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
  • Ok I am creating a validation that simple output 'VALID' or 'INVALID' in the console. But If the response is in '1'. It doesn't display the 'VALID' in console – Jerielle Dec 05 '13 at 06:39
2

In your success response you will get what you are set to output in php. If you want to get an array or data set you can encode it in json in your php script like

echo json_encode($validate);

Then in your jquery you can use this response like this

var responseData = jQuery.parseJSON(response);
console.log(responseData);

console.log will print json object in browser console. You can use this json object like this

responseData.some_data
Bilal
  • 2,645
  • 3
  • 28
  • 40
2

Ajax is asynch so you will have access to it after the ajax method returns:

$('#existing').on('keyup',function(){

            var id = '<?php echo $this->session->userdata("user_id"); ?>';
            var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';

            $.ajax({
                type: 'POST',
                url: password_url,
                data: '',
                dataType: 'json'
            }).then(function(response){
              var k;
              if(response == 1){
                k = response;
                //call another function that needs k here
              }
            });
        });
HMR
  • 37,593
  • 24
  • 91
  • 160
1
 $.ajax({
            type: 'POST',
            url: password_url,
            data: '',
            dataType: 'json',
            success: function(response){

               k=response;

            }

        });
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
1

Your response data is in response variable of success function. Since the response type is json you can assign it directly to javaScript variable.

Also you comparison is wrong try if(g == '1') instead if(g == 1). You are getting a string as response and your checking equality with a numeric type which won't be equal at any point.

ie:-

$.ajax({
                type: 'POST',
                url: password_url,
                data: '',
                dataType: 'json',
                contentType:"application/json",// Add Content type too
                success: function(response){
                    k=response;
                  }
        });

if your json response is as shown below

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

you can access menuitem array as

success: function(response){
               k=response.menu.popup.menuitem;
            }
Subin Jacob
  • 4,692
  • 10
  • 37
  • 69
1

response parameter itself contain data so just assign that to variable and use it.

 $.ajax({
        type: 'POST',
        url: password_url,
        success: function(response){
         if(parseInt(response) == 1){ 
          var k = response;
          }
        }
    });
sumit
  • 332
  • 2
  • 7
  • I updated the code. But I can't get the correct response if the response is 1. – Jerielle Dec 05 '13 at 06:45
  • You can check the value before assign to that a variable. console or alert that response. – sumit Dec 05 '13 at 06:46
  • Hey that was my mistake I defined data type json for response just remove that one it will work. – sumit Dec 05 '13 at 06:48
  • Same output. The console output is correct but it doesn't display the correct message. If 1 display VALID if 0 display INVALID. But whether the response is 1 or 0. I always end up with INVALID – Jerielle Dec 05 '13 at 06:51
  • I think there is problem in comparison. your are comparing response with integer value so before it parse response with integer. I have updated my answer use that. – sumit Dec 05 '13 at 06:54
  • @jerielle Please provide your feedback. did my answer work for you or not. – sumit Dec 06 '13 at 12:44
1
var k = null;

$('#existing').on('keyup', function() {
  var id           = '<?php echo $this->session->userdata("user_id"); ?>',
      password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';

  $.ajax({
    type    : 'POST',
    url     : password_url,
    success : function(data) {
      if(data === '1') {
        k = data;
      }
    }
  });
});
Chris Clower
  • 5,036
  • 2
  • 18
  • 29
0

File Name votepost.php

<?php
include("domain.php");

$csid=$_POST['CSID'];
$voteid=$_POST['VOTEID'];
$myid=$_POST['MYID'];
$usertype=$_POST['USERTYPE'];


$myurl =URL."putvote.php?csid=".$csid."&voterid=".$myid."&voteid=".$voteid."&usertype=".$usertype;
$myurl=str_replace(" ","%20",$myurl);
$jsondata = file_get_contents($myurl);
$data = json_decode($jsondata);

if($data->response=="true")
{
    echo 'true';

}
else
{
    echo 'false';

}


?>

ajax reponse use $.trim for IF ELSE

$.post("votepost.php", {CSID:csid,VOTEID:voteid,MYID:myid,USERTYPE:usertype}, function (data) {

        if($.trim(data)=='true')
        {
            alert('ok');
        }
        else
        {
            alert('error');
        }
    });

I hope you will solve your problem

Muhammad Numan
  • 23,222
  • 6
  • 63
  • 80
0

You can create the js blank array and assign it to the same array.

var resp = [];
    jQuery.ajax({
            dataType: "json",
            method: 'post',
            url: 'ajax.php',
            async: false,
            data: {postData: 'postData'},
            success: function(data){
                resp.push(data);
            }
    });
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
devendra singh
  • 219
  • 3
  • 15