2

I have a form, where user can insert up to 4 age ranges. User can add or remove input fields dynamically.

I am trying to send the array to my PHP file and then insert it to database (insert new row for each range pair, lets say 1-3 and 4-6 will be on separate rows with correct user_id) with PDO.

The callback is success in PHP file, but nothing is inserted, which means it cannot get the values from JS and I am pretty lost how to send the array with the rest of the form data.

In html I have a button where, user can add fields dynamically and the ID will increment by 1 each time.

HTML file

<div class="row default" id="childAgeRange1">
    <div class="col-md-6">
        <input type="text" class="form-control" id="userProfileAgeFrom" name="userProfileAgeFrom[]" placeholder="Alates..." />
    </div>
    <div class="col-md-6">
        <input type="text" class="form-control" id="userProfileAgeTo" name="userProfileAgeTo[]" placeholder="Kuni..." />
    </div>
</div>

My JS file:

    $(document).on("click", "#btnUpdateInformation", function (e) {


                var userProfileAgeFrom = $("input[name^='userProfileAgeFrom']").map(function (idx, ele) {
                    return $(ele).val();
                }).get();

                var userProfileAgeTo = $("input[name^='userProfileAgeTo']").map(function (idx, ele) {
                    return $(ele).val();
                }).get();

                var formData = {
                    'user_id'                     : $("#hiddenUserID").val(),
                    'userPassword'                : $('#userPassword').val(),
                    'userRetypePassword'          : $('#userRetypePassword').val(),
                    'userBirthCountry'            : $('#userBirthCountry').val(),
                    'userBirthCity'               : $('#userBirthCity').val(),
                    'userBirthAddress'            : $('#userBirthAddress').val(),
                    'UserZipCode'                 : $('#UserZipCode').val(),
                    'userFirstName'               : $('#userFirstName').val(),
                    'userLastName'                : $('#userLastName').val(),
                    'userSex'                     : $('#userSex').val(),
                    'userBirthDay'                : $('#userBirthDay').val(),
                    'userBirthMonth'              : $('#userBirthMonth').val(),
                    'userBirthYear'               : $('#userBirthYear').val(),
                    'userPhoneNr'                 : $('#userPhoneNr').val(),
                    'userPasswordConfirm'         : $('#userPasswordConfirm').val(),
                    'userQuote'                   : $('#userQuote').val(),
                    'userDescription'             : $('#userDescription').val(),
                    'userProfileAgeFrom'          : userProfileAgeFrom,
                    'userProfileAgeTo'            : userProfileAgeTo,
                    'userProfileWage'             : userFinalWage

                };
        console.log(formData);
        $.ajax({
            type: "POST",
            url: "PHP/updateUserProfile.php",
            data: formData,  
            success: function(data){
                console.log(data);
                if(data.status == 'success'){
                    console.log("success");
                }else if(data.status == 'error'){
                    console.log("error");
                }else if(data.status == 'no_results'){
                    console.log("no results");
                }else if(data.status == 'results'){
                    console.log("there are results");
                }else if(data.status == 'password_matches'){
                    console.log("password matches");
                }

            },
            error: function(jqXHR, textStatus, errorThrown, data){
                console.log(jqXHR, textStatus, errorThrown, data);
            }
        });
        $('#btnUpdateInformation').unbind('click');
        e.preventDefault();
    });

PHP file

        if(isset($_POST['userProfileAgeFrom']) && isset($_POST['userProfileAgeTo'])){
            $data = array( 
                $userProfileAgeFrom => $_POST['userProfileAgeFrom'], 
                $userProfileAgeTo => $_POST['userProfileAgeTo']
            );

            $user_profile_age_range = $user_home->runQuery("UPDATE nanny_age_range SET age_minimum=:userProfileAgeFrom, age_maximum=:userProfileAgeTo WHERE user_id=:user_id ");
            $user_profile_age_range->bindparam(':userProfileAgeFrom', $userProfileAgeFrom, PDO::PARAM_STR);
            $user_profile_age_range->bindparam(':userProfileAgeTo', $userProfileAgeTo, PDO::PARAM_STR);
            $user_profile_age_range->bindparam(':user_id', $user_id, PDO::PARAM_STR);
            $user_profile_age_range->execute(); 
            $response_array['status'] = 'success';
        }

And database Table:

enter image description here

EDIT Console.log(formData) shows

UserZipCode
:
"11111"
userBirthAddress
:
"address"
userBirthCity
:
"c"
userBirthCountry
:
"c"
userBirthDay
:
"31"
userBirthMonth
:
"08"
userBirthYear
:
"1992"
userDescription
:
"description"
:
"x"
userLastName
:
"x"
userPassword
:
""
userPasswordConfirm
:
"xxxx"
userPhoneNr
:
"555555555555"
userProfileAgeFrom
:
"["1"]"
userProfileAgeTo
:
"["3"]"
userProfileWage
:
"9.60"
userQuote
:
"c"
userRetypePassword
:
""
userSex
:
"m"
user_id
:
"6"
9
  • What does var_dump($_POST) return ? Commented May 24, 2016 at 8:28
  • @Cornwell var dump returns nothing, if I put it inside the function Commented May 24, 2016 at 8:33
  • 1
    Where are $userProfileAgeFrom, $userProfileAgeTo and $user_id defined? Your query also written as UPDATE rather than INSERT INTO. I clearly don't understand the question. Commented May 24, 2016 at 8:35
  • @Chay22, it should be update --- edited. The $userProfileAgeFrom and To comes from $_POST. They are defined like this $user_id = $_POST['user_id']; $userProfileAgeTo= trim($_POST['userProfileAgeTo']); $userProfileAgeFrom= trim($_POST['userProfileAgeFrom']); Commented May 24, 2016 at 8:39
  • 1
    please show us the output of console.log(formData); Commented May 24, 2016 at 8:48

2 Answers 2

1

Based on OP comment, console.log(formData) shows this:

userProfileAgeFrom: "["1"]"
userProfileAgeTo: "["3"]"

It means, now you have a JSON array in your values. So you need to decode it, and get the first value of it:

$userProfileAgeFrom = json_decode($_POST['userProfileAgeFrom'],true)[0], 
$userProfileAgeTo = json_decode($_POST['userProfileAgeTo'],true)[0]

EDIT

Based on OP comment.

So if you have more value in your userProfileAgeFrom and others, then iterate throught them:

for ($i = 0; $i < count($_POST['userProfileAgeFrom']); $i++) {
    $user_profile_age_range = $user_home->runQuery("UPDATE nanny_age_range SET age_minimum=:userProfileAgeFrom, age_maximum=:userProfileAgeTo WHERE user_id=:user_id ");
    $user_profile_age_range->bindparam(':userProfileAgeFrom', $_POST['userProfileAgeFrom'][$i], PDO::PARAM_STR);
    $user_profile_age_range->bindparam(':userProfileAgeTo', $_POST['userProfileAgeTo'][$i], PDO::PARAM_STR);
    $user_profile_age_range->bindparam(':user_id', $user_id, PDO::PARAM_STR);
    $user_profile_age_range->execute();
}

WARNING

But this will bad, because all your rows will be the same because of WHERE user_id=:user_id

I think you should redesign your code.

Sign up to request clarification or add additional context in comments.

6 Comments

but what if there are more? there an be up to 4 different ranges (sorry for the late reply).
Also tried, it and getting this: Warning: json_decode() expects parameter 1 to be string, array given
any suggestions how can I edit the correct rows, so they all wont be the same?
create a hidden field for all fields, like <input type="hidden" name="userProfileAgeToOld[]" value="<?php echo $oldValue[$keyOfOldValuesArray];?>" /> and say WHERE userId = ... AND userProfileAge = userProfileAgeToOld[$i] AND ... So update by all values.
so if I add hidden input and append the row id from database to the value. can I then say like update where user_id = user_id and age_range_id = id?
|
0

The result of both $userProfileAgeFrom and $userProfileAgeTo are seems to array so the insertion will be work in a for loop. And hope the count of both this array are same.

$userProfileAgeFrom = $_POST['userProfileAgeFrom'];
$userProfileAgeTo = $_POST['userProfileAgeTo'];

for ($i = 0; $i < count($userProfileAgeFrom); $i++) {
    $user_profile_age_range = $user_home->runQuery("UPDATE nanny_age_range SET age_minimum=:userProfileAgeFrom, age_maximum=:userProfileAgeTo WHERE user_id=:user_id ");
    $user_profile_age_range->bindparam(':userProfileAgeFrom', $userProfileAgeFrom[$i], PDO::PARAM_STR);
    $user_profile_age_range->bindparam(':userProfileAgeTo', $userProfileAgeTo[$i], PDO::PARAM_STR);
    $user_profile_age_range->bindparam(':user_id', $user_id, PDO::PARAM_STR);
    $user_profile_age_range->execute();
}

2 Comments

this solution does update the values in DB, but it updates the rows to the same result- lets say I typed in 1-3 and 5-7, both the rows will be 5-7
This is because you are try to run an update query with user_id. Try to provide auto increment id for the table nanny_age_range and update based on that id.

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.