简体   繁体   English

提交表单而不用jQuery和Ajax刷新页面不更新MySQL数据库

[英]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. 我是JQuery的新手,但是有一个问题,当我单击表单上的Submit按钮时,所有内容都表示注册成功,但是我的MYSQL数据库未更新,一切正常,直到尝试将JQuery添加到图片中为止。

Can someone help me fix this problem so my database is updated? 有人可以帮助我解决此问题,以便更新我的数据库吗?

Thanks 谢谢

Here is the JQuery code. 这是JQuery代码。

$(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. 这是PHP代码。

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. 这是XHTML代码。

<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块,这是您的代码

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

Put all your jQuery within 将所有jQuery放入

$(document).ready(function(){ //evething here }); $(document).ready(function(){//此处是一切});

Put an id on the form. 在表单上放置一个ID。 For example id="myform". 例如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." 要使用插件,请在所有必填字段的输入标签中添加class =“ =”。

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 . 但是,您似乎想要设置提交处理程序以通过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. 这有望解决您的jQuery问题,如果它可以正常提交,则服务器端代码不会出现问题。

$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. mysql(i)_query永远不会返回true,它只会在成功时返回资源,而在失败时返回FALSE。

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. 而不是$ .load尝试$ .get因为加载是要在$('#result_of_query).load(...)这样的上下文中使用的,结果将被加载到'#result_of_query'中,我假设它看起来像一个因此重新加载。

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();
           }
         );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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