September 15, 2013

Sending json with php and parse it in ajax call

User2589904’s Question:

I don’t have experience using JSON with php and ajax and I need your help.

I have a php page that validates user input… Before using json, I used to store them in an array. I was able to parse the json when I store my values in an array like this
$data = array(“success”=>true, “msg”=>”my masg”);
json_decode($data);

and then in my ajax call on success function I data.success and data.msg

How do I store multipe msgs or errors in my array and parse them in my ajax call?
here is my code

here I want to validate user input and I would like to validate many fields

    if(isset($_POST['txt_username']) &&($_POST['txt_username']!=""))
    {
        $username =trim( $_POST['txt_username']);
        $username  = filter_input(INPUT_POST, 'txt_username',
                    FILTER_SANITIZE_STRING);
    }
    else
    {

             }

So how do I do it in the else statement?

here is my ajax call

 $.ajax({       
            type: "POST",
            dataType: "json",
            cache: false,
            data: {txt_username:$("#username").val(), txt_password:$("#password").val()},

            beforeSend: function(x) {

                if(x && x.overrideMimeType) {

                    x.overrideMimeType("application/json;charset=UTF-8");
                }

            },

            url: 'proccessing_forms/admin_login.php',

            success: function(data) {

                // parse the data
            }
    });


    }

You can use multidimensional arrays for this:

$msg = array("success" => array(), "error" => array());

// ... DO you processing on if and else

//When you need to add to an success do
$msg['success'][] = "My Success";

//When you need to add to an error do
$msg['error'][] = "My error";


echo json_encode($msg); exit;

On the ajax’s success event, you can access both of these variables individually.

success: function(data) {
    var errors = data.error;
    var succesess = data.success

    //Process each msg
    $.each(errors, function(index, msg) {
         console.log(msg);
    });
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!