0

I have no idea how to fix it. The value that i got is always"undefined" even when the response i get and I show by alert Here is my ajax code and two picture that I collected from my result. one when I show the json response and another when I show the json property


when

alert(json_data).

enter image description here


when

alert(json_data.status)

, it shows "undefined" enter image description here

ajax code:

 $("#input-form").submit(function(e) {
    var test = checkFile();
    var file_data = $('#imgInpbanner').prop('files')[0];
    var form_data = new FormData();
    if (test == true) {
        form_data.append('avatar', file_data);
    }
    form_data.append('_token', $('#_token').val());
    form_data.append('experient_period', $("#experient-period").val());
    form_data.append('married', $("#married").val());
    form_data.append('acc_id', <?php echo $teacher->acc_id; ?>);
    form_data.append('official_staff', $("#official_staff").val());
    form_data.append('certificate', $("#certificate").val());
    form_data.append('birth', $("#birth").val());
    form_data.append('beginning_date', $("#beginning-date").val());
    form_data.append('gender', $("#gender").val());
    form_data.append('user_name', $("#user_name").val());
    form_data.append('email', $("#email").val());
    form_data.append('password', $("#password").val());
    form_data.append('first_name', $("#first_name").val());
    form_data.append('last_name', $("#last_name").val());
    form_data.append('phone_number', $("#phone_number").val());
    form_data.append('address', $("#address").val());
    form_data.append('colleague', $("#colleague").val());
    var formURL = $(this).attr("action");
    $.ajax({
        url: formURL,
        dataType: 'text', // what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        type: "POST",
        data: form_data,
        success: function(data, textStatus, jqXHR) {
            //data: return data from server
            var json_data = JSON.parse(JSON.stringify(data));
            alert(json_data.status);
            if (json_data.status == 200) {
                $('#modal-header').css('background-color', '#00c0ef');
                $('#result_inform').text(json_data.message);
                $('#modaltest').trigger("click");
            } else {
                $('#modal-header').css('background-color', '#d33724');
                $('#result_inform').text(json_data.message);
                $('#modaltest').trigger("click");
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            //if fails
            $('#modal-header').css('background-color', '#d33724');
            $('#result_inform').text("Có lỗi xảy ra");
            $('#modaltest').trigger("click");

        }
    });
    e.preventDefault(); //STOP default action
    e.unbind(); //unbind. to stop multiple form submit.
});

PHP controller

 $isOldPw = strcmp(Input::get('password'), '');
    $acc_id = Input::get('acc_id');
    try {
        $teacher = Teachers::findOrFail($acc_id);
        $user = Users::findOrFail($acc_id);
        $isOldEmail = strcmp(Input::get('email'), $user - > email);
        $isOldUrNm = strcmp(Input::get('user_name'), $user - > user_name);
        $rules = array(
            'first_name' => 'required|max:10',
            'last_name' => 'required|max:30',
            'address' => 'required|max:100',
            'phone_number' => 'required|max:15|regex:/(0)[0-9]{9}/',
            'user_name' => 'required|min:5|unique:user',
            'email' => 'required|email|unique:user',
            'password' => 'required|min:6'
        );
        if ($isOldPw == 0) array_splice($rules, 6, 1);
        if ($isOldEmail == 0) array_splice($rules, 5, 1);
        if ($isOldUrNm == 0) array_splice($rules, 4, 1);
        $validator = Validator::make(Input::all(), $rules);
        if ($validator - > fails()) {
            $messages = $validator - > messages();
            return response() - > json(['status' => 400, 'message' => $messages - > toJson()]);
        } else {
            $user - > user_name = Input::get('user_name');
            $user - > first_name = Input::get('first_name');
            $user - > last_name = Input::get('last_name');
            $user - > email = Input::get('email');
            $user - > address = Input::get('address');
            $user - > phone_number = Input::get('phone_number');
            if ($isOldPw != 0)
                $user - > password = Hash::make(Input::get('password'));
            $user - > gender = (Input::get('gender'));
            $user - > birth = date('Y-m-d', strtotime(Input::get('birth')));
            $teacher - > certificate = (Input::get('certificate'));
            $teacher - > beginning_time = date('Y-m-d', strtotime(Input::get('beginning_date')));
            $teacher - > colleague = (Input::get('colleague'));
            $teacher - > official_staff = (Input::get('official_staff'));
            $teacher - > married = (Input::get('married'));
            $teacher - > experient_period = (Input::get('experient_period'));

            if (Request::hasFile('avatar') && Input::file('avatar') - > isValid()) {
                if (strlen($user - > image_url) > strlen(SysConst::get('DEFAULT_AVATAR_PATH')))
                    File::delete(public_path().$user - > image_url);
                $img_path = SysConst::get('IMAGE_PATH_USERAVATAR');
                $file = Input::file('avatar');
                $image_name = time().
                '-'.$file - > getClientOriginalName();
                $file - > move(public_path().$img_path, $image_name);
                $image_alter = Image::make(sprintf(public_path().$img_path.
                    '%s', $image_name)) - > resize(128, 128) - > save();
                $image_url = $img_path.$image_name; // Note we add the image path to the databse field before the save.
                $user - > image_url = $image_url;
            } else {
                $user - > image_url = SysConst::get('DEFAULT_AVATAR_PATH');
            }
            DB::beginTransaction();
            $user - > save();
            $teacher - > acc_id = $user - > id;
            $teacher - > save();
            DB::commit();
            return response() - > json(['status' => 200, 'message' => 'Cập   nhật thành công']);
        }
    } catch (\PDOException $ex) {
        DB::rollBack();
        return response() - > json([
            "status" => 500,
            "message" => $ex - > getMessage()
        ]);
    } catch (\Exception $ex) {
        return response() - > json(['status' => 400, 'message' => $ex - > getMessage()]);
    }
1
  • any errors in the browser developer tools console? As a guess, data is not a valid JSON string, so JSON.parse fails Commented Dec 2, 2016 at 4:21

1 Answer 1

1

You don't need JSON.stringify(data) as your data is already in json string you just need to parse it.

Change this

var json_data = JSON.parse(JSON.stringify(data));

To

var json_data = JSON.parse(data); 
Sign up to request clarification or add additional context in comments.

2 Comments

thank you, i fixed it, but i am still confused since it had worked fined for a long time ago although i used JSON.stringify.
You would have changed something i guess.

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.