Home > Back-end >  How to parse array with ajax PHP
How to parse array with ajax PHP

Time:12-29

I am working on Ajax with php and i am getting response from "Controller" as json response but i am unable to parse response(alert in empty) Here is my code

$.ajax({
            type: "post",
            url:'<?php echo base_url();?>Main/GetFollowingCoinUsers',
            data: {coin_id:coin_id},
            success: function (datan) {
            var data2 = JSON.parse(datan);
            alert(data2)
            }
        });

    

And here is my code in controller

function GetFollowingCoinUsers()
    {
        $CoinId=$_POST['coin_id'];
        $result = $this->M_main->GetAllCoinFollower($CoinId);
        $UserId=array();
        foreach($result as $res)
        {
            $UserId[]=$res['UserId'];
        }
        echo json_encode($UserId);
    }

    

Where i am wrong ?

CodePudding user response:

Usually, there might be many possible reasons.

Generally, some of the reasons could be:

  1. The ajax URL is not correctly mentioned.
  2. The server is giving errors and therefore makes it impossible to parse the response as a JSON object. (Use Developer Tool > console or/and Developer Tool > network to check the problem more in-depth.
  3. The request is getting blocked due to Cross-Origin Request Header (CORS Policies), and you are not noticing it because you haven't checked the network section under Developer Tool.

I'd suggest figuring the problem out using console.log(datan), and seeing what data type is it.

CodePudding user response:

Controller seems to be fine just update your ajax request and add data type which is expecting from controller

$.ajax({
        type: "post",
        dataType: "json",
        url:'<?php echo base_url();?>Main/GetFollowingCoinUsers',
        data: {coin_id:coin_id},
        success: function (datan) {
        var data2 = JSON.parse(datan);
        alert(data2)
        }
    });

CodePudding user response:

In api use of "echo" is not a best practice. You can use 'return' instead of echo. While assigning values inside foreach loop, use array_push()

  • Related