简体   繁体   中英

Submiting a Form without Refreshing the page with jQuery and Ajax Not updating MySQL database

I'm a newbie to JQuery and have a problem, when I click submit button on the form everything says registration was successful but my MYSQL database was not updated everything worked fine until I tried to add the JQuery to the picture.

Can someone help me fix this problem so my database is updated?

Thanks

Here is the JQuery code.

$(function() {

$(".save-button").click(function() {
    var address = $("#address").val();
    var address_two = $("#address_two").val();
    var city_town = $("#city_town").val();
    var state_province = $("#state_province").val();
    var zipcode = $("#zipcode").val();
    var country = $("#country").val();
    var email = $("#email").val();

    var dataString = 'address='+ address + '&address_two=' + address_two + '&city_town=' + city_town + '&state_province=' + state_province + '&zipcode=' + zipcode + '&country=' + country + '$email=' + email;

    if(address=='' || address_two=='' || city_town=='' || state_province=='' || zipcode=='' || country=='' || email=='') {
        $('.success').fadeOut(200).hide();
        $('.error').fadeOut(200).show();
    }

    else
    {
    $.ajax({
    type: "POST",
    url: "http://localhost/New%20Project/home/index.php",
    data: dataString,
    success: function(){
    $('.success').fadeIn(200).show();
    $('.error').fadeOut(200).hide();

   }
});
    }

    return false;

    });
});

Here is the PHP code.

if (isset($_POST['contact_info_submitted'])) { // Handle the form.

    // Query member data from the database and ready it for display
    $mysqli = mysqli_connect("localhost", "root", "", "sitename");
    $dbc = mysqli_query($mysqli,"SELECT users.*, contact_info.*
                                 FROM users 
                                 INNER JOIN contact_info ON contact_info.user_id = users.user_id 
                                 WHERE users.user_id=3");

    $user_id = mysqli_real_escape_string($mysqli, htmlentities('3'));
    $address = mysqli_real_escape_string($mysqli, htmlentities($_POST['address']));
    $address_two = mysqli_real_escape_string($mysqli, htmlentities($_POST['address_two']));
    $city_town = mysqli_real_escape_string($mysqli, htmlentities($_POST['city_town']));
    $state_province = mysqli_real_escape_string($mysqli, htmlentities($_POST['state_province']));
    $zipcode = mysqli_real_escape_string($mysqli, htmlentities($_POST['zipcode']));
    $country = mysqli_real_escape_string($mysqli, htmlentities($_POST['country']));
    $email = mysqli_real_escape_string($mysqli, strip_tags($_POST['email']));


//If the table is not found add it to the database
if (mysqli_num_rows($dbc) == 0) {
        $mysqli = mysqli_connect("localhost", "root", "", "sitename");
        $dbc = mysqli_query($mysqli,"INSERT INTO contact_info (user_id, address, address_two, city_town, state_province, zipcode, country, email) 
                                     VALUES ('$user_id', '$address', '$address_two', '$city_town', '$state_province', '$zipcode', '$country', '$email')");
}



//If the table is in the database update each field when needed
if ($dbc == TRUE) {
        $dbc = mysqli_query($mysqli,"UPDATE contact_info 
                                     SET address = '$address', address_two = '$address_two', city_town = '$city_town', state_province = '$state_province', zipcode = '$zipcode', country = '$country', email = '$email' 
                                     WHERE user_id = '$user_id'");
}


if (!$dbc) {
        // There was an error...do something about it here...
        print mysqli_error($mysqli);
        return;
}

}

Here is the XHTML code.

<form method="post" action="index.php">
    <fieldset>
        <ul>
            <li><label for="address">Address 1: </label><input type="text" name="address" id="address" size="25" class="input-size" value="<?php if (isset($_POST['address'])) { echo $_POST['address']; } else if(!empty($address)) { echo $address; } ?>" /></li>
            <li><label for="address_two">Address 2: </label><input type="text" name="address_two" id="address_two" size="25" class="input-size" value="<?php if (isset($_POST['address_two'])) { echo $_POST['address_two']; } else if(!empty($address_two)) { echo $address_two; } ?>" /></li>
            <li><label for="city_town">City/Town: </label><input type="text" name="city_town" id="city_town" size="25" class="input-size" value="<?php if (isset($_POST['city_town'])) { echo $_POST['city_town']; } else if(!empty($city_town)) { echo $city_town; } ?>" /></li>
            <li><label for="state_province">State/Province: </label>
            <?php

            echo '<select name="state_province" id="state_province">' . "\n";
              foreach($state_options as $option) {
                if ($option == $state_province) {
                  echo '<option value="' . $option . '" selected="selected">' . $option . '</option>' . "\n";
                } else {
                  echo '<option value="'. $option . '">' . $option . '</option>'."\n";
                }
              }
            echo '</select>';

            ?>
            </li>

            <li><label for="zipcode">Zip/Post Code: </label><input type="text" name="zipcode" id="zipcode" size="5" class="input-size" value="<?php if (isset($_POST['zipcode'])) { echo $_POST['zipcode']; } else if(!empty($zipcode)) { echo $zipcode; } ?>" /></li>

            <li><label for="country">Country: </label>
            <?php

            echo '<select name="country" id="country">' . "\n";
              foreach($countries as $option) {
                if ($option == $country) {
                  echo '<option value="' . $option . '" selected="selected">' . $option . '</option>' . "\n";
                } 
                else if($option == "-------------") {
                  echo '<option value="' . $option . '" disabled="disabled">' . $option . '</option>';
                }
                else {
                  echo '<option value="'. $option . '">' . $option . '</option>'."\n";
                }
              }
            echo '</select>';

            ?>
            </li>

            <li><label for="email">Email Address: </label><input type="text" name="email" id="email" size="25" class="input-size" value="<?php if (isset($_POST['email'])) { echo $_POST['email']; } else if(!empty($email)) { echo $email; } ?>" /><br /><span>We don't spam or share your email with third parties. We respect your privacy.</span></li>

            <li><input type="submit" name="submit" value="Save Changes" class="save-button" />
                <input type="hidden" name="contact_info_submitted" value="true" />
            <input type="submit" name="submit" value="Preview Changes" class="preview-changes-button" /></li>
        </ul>
    </fieldset>

</form>

You should may be think about refactorng your code ? i can clean your the else block of the code here is your code

else
{
   $.load(
          "http://localhost/New%20Project/home/index.php",dataString,
           function()
           { 
             $('.success').fadeIn(200).show();
             $('.error').fadeOut(200).hide();
           }
         );
}

Put all your jQuery within

$(document).ready(function(){ //evething here });

Put an id on the form. For example id="myform".

Use a plug-in for form validation. To use the plug-in put class="required in the input tag of all required fields."

The documentation for the validation plug-in is here so you can see which option fit your needs. But, it looks like you'll want to set the submit handler to submit the form via AJAX .

$("#myform").validate({
   submitHandler: function(form) {
    $(form).ajaxSubmit();
   }
})

That should hopefully fix your jQuery problems, if it works for regular submission there's no problems with your server-side code.

$dbc = mysqli_query($mysqli,"SELECT users.*, contact_info.*
                             FROM users 
                             INNER JOIN contact_info ON contact_info.user_id = users.user_id 
                             WHERE users.user_id=3");


if ($dbc == TRUE) {
        $dbc = mysqli_query($mysqli,"UPDATE contact_info 
                                     SET address = '$address', address_two = '$address_two', city_town = '$city_town', state_province = '$state_province', zipcode = '$zipcode', country = '$country', email = '$email' 
                                     WHERE user_id = '$user_id'");
}

A mysql(i)_query will never return true, it will only return a resource on success or FALSE on failure.

This may be more what you're trying to do

if ($dbc !== FALSE) {
  // do update query

instead of $.load try $.get because load is ment to be used in context like $('#result_of_query).load(...) where the result would be loaded into '#result_of_query', im assuming it looks like a reload due to this.

so maybe you should try this:

else
{
   $.get(
          "http://localhost/New%20Project/home/index.php",dataString,
           function()
           { 
             $('.success').fadeIn(200).show();
             $('.error').fadeOut(200).hide();
           }
         );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM