简体   繁体   English

AJAX jquery移动php表单提交不刷新不更新

[英]AJAX jquery mobile php form submission not updating without refresh

I feel like I'm trying to do the most basic background form submission using AJAX (to php/mySQL) and just cannot get it to work. 我觉得我正在尝试使用AJAX(至php / mySQL)提交最基本的后台表单提交,但无法使其正常工作。 I've probably spend 15 hours searching and trying different combinations, but can't get my site to work. 我可能已经花了15个小时来搜索和尝试不同的组合,但是无法使我的网站正常工作。

Basically what happens is a user types into a form two pieces of data - a name and a team. 基本上,发生的事情是用户将两种数据形式输入一个表单-一个名称和一个团队。 He also selects a photo from the camera's library. 他还从相机库中选择一张照片。 Then a javascript function submitForm() reads the data from the form and submits it to upload2.php , which stores the text fields and a link to the photo in a mySQL database. 然后,一个javascript函数submitForm()从表单中读取数据,并将其提交给upload2.php ,该文件将文本字段和指向照片的链接存储在mySQL数据库中。 It also saves the photo upload. 它还可以保存照片上传。

All of that works correctly. 所有这些都能正常工作。 What doesn't is that after submission, the fields are returned to their previous values (before submission). 并不是说,提交后,字段将恢复为以前的值(提交前)。 This confuses the user, as it looks like his changes didn't go through. 这使用户感到困惑,因为看起来他的更改没有通过。

However, they do go through - he just has to manually hit refresh to view them on the page. 但是,它们确实可以通过-他只需要手动单击刷新即可在页面上查看它们。 This seems like the simplest of questions, but I have been completely unable to solve for it. 这似乎是最简单的问题,但是我完全无法解决。

Here is the javascript: 这是JavaScript:

function submitForm() {
        console.log("submit event");
        var fd = new FormData(document.getElementById("fileinfo"));
        fd.append("label", "WEBUPLOAD");
        $.ajax({
          url: "upload2.php",
          type: "POST",
          data: fd,
          cache: false,
          enctype: 'multipart/form-data',
          processData: false,  // tell jQuery not to process the data
          contentType: false   // tell jQuery not to set contentType
        }).done(function( data ) {
            console.log("PHP Output:");
            console.log( data );
        });
        return false;
    }

And here is the php: 这是PHP:

if ($_POST["label"]) {
include 'config.php';
$label = $_POST["label"];
$uid = $_POST["uid"];
echo "uid=" . $uid;
$fullname = addslashes($_POST["fullname"]);
$pairingID = $_POST["pairingID"];
$query = "update usertable set fullname ='$fullname', pairingID = $pairingID where id = $uid";
echo $query;
//run update query
mysql_query($query,$dbconnection) or print "DB ERROR: ".mysql_error($dbconnection);     

if ($_FILES["file"]) {
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    } else {
        $filename = time(). $label.$_FILES["file"]["name"];
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

        if (file_exists("upload/" . $filename)) {
            echo $filename . " already exists. ";
        } else {
            move_uploaded_file($_FILES["file"]["tmp_name"],
            "upload/" . $filename);
            echo "Stored in: " . "upload/" . $filename;
            echo "fullname=" . $fullname;
            $imgurl = "upload/" . $filename;
            include 'config.php';
            $time_stamp = date('Y-m-d H:i:s');
            //$uname = trim($_POST["uname"]);
            //update tblFeed

            $query = "update usertable set selfie = '$imgurl' where id = $uid";
            echo $query;
            //run update query
            mysql_query($query,$dbconnection) or print "DB ERROR: ".mysql_error($dbconnection);     


        }
    }
} else {
    echo "Invalid file";
    echo "filetype:" . $_FILES["file"]["type"];
    echo "filesize:" . $_FILES["file"]["size"];
}               
}
}

And here is the html form: 这是html形式:

<form method="post" id="fileinfo" name="fileinfo">
    <label>Name:</label>
    <input type="text" style="max-width: 80%" name="fullname" value="temp" id="fullname" />
    <input type="hidden" name="uid" value="44" id="uid" />
    <label>Selfie:</label><br>
    <img style="width:50px;" src="" />
    <input type="file" name="file" style="max-width:80%;"/><br/>Today's pairing:</br>

<select name="pairingID" id="pairingID">Day 1<ul data-role="listview" data-inset="true"><option selected value="1">Andy/Mark (Day 1)</option><option value="2">Cory/Adam (Day 1)</option><option value="3">Morgan/Brandon (Day 1)</option><option value="4">John/Phil (Day 1)</option><option value="5">Casey/Kyle (Day 1)</option><option value="6">Foskey/Taylor (Day 1)</option><option value="7">Clint/James (Day 1)</option><option value="8">Matt/Desha (Day 1)</option><option value="9">Ross/Ryan H (Day 1)</option><option value="10">Ryan V/Dan (Day 1)</option><option value="11">Rene/JZ (Day 1)</option><option value="12">AD/Jake (Day 1)</option></ul>Day 2<ul data-role="listview" data-inset="true"><option value="13">Andy/Mark (Day 2)</option><option value="14">Cory/Adam (Day 2)</option><option value="15">Morgan/Phil (Day 2)</option><option value="16">John/Brandon (Day 2)</option><option value="17">Foskey/Kyle (Day 2)</option><option value="18">Casey/Taylor (Day 2)</option><option value="19">Matt/James (Day 2)</option><option value="20">Clint/Desha (Day 2)</option><option value="21">Dan/Ryan H (Day 2)</option><option value="22">Ross/Ryan V (Day 2)</option><option value="23">AD/Rene (Day 2)</option><option value="24">JZ/Jake (Day 2)</option></select>


Formatting in these comments is lacking for sure!! 肯定缺少这些注释中的格式!! So I'm hoping over to one of these 'answers' sections... 因此,我希望转到这些“答案”部分之一...

Short answer: I'd use JSON. 简短的答案:我将使用JSON。

For example, maybe have your PHP return JSON (json_encode()) where the keys of the array match the id's of your HTML. 例如,也许您的PHP返回JSON(json_encode()),其中数组的键与HTML的ID匹配。 Then use jQuery's JSON 'parser' ( http://api.jquery.com/jquery.parsejson/ ) to get a JS Object. 然后使用jQuery的JSON'parser'( http://api.jquery.com/jquery.parsejson/ )获取JS对象。 Loop over this object and put the 'value' into each element in your form (identified by id). 循环遍历此对象,并将“值”放入表单中的每个元素(由id标识)。

You could even throw in an 'extra' element in your JSON that includes 'other-stuff' to tell the user. 您甚至可以在JSON中添加一个包含“其他东西”的“额外”元素来告诉用户。

Something like: 就像是:

PHP: PHP:
$json_array = array('fullname'=>$fullname, 'pairingID'=>$pairingID); $ json_array = array('fullname'=> $ fullname,'pairingID'=> $ pairingID);
echo jsone_encode($json_array); 回声jsone_encode($ json_array);

Then in your JS something like: 然后在您的JS中类似:

var items = $.parseJSON(data); var items = $ .parseJSON(data);
// error checking stuff here //在这里检查错误
$("#fullname").val(items.fullname); $(“#fullname”)。val(items.fullname);
// can't remember how to select an item by value in JS at the moment, but do that here with items.pairingID being the 'value' to 'select'. //目前还不记得如何在JS中通过值选择项目,但是在这里使用items.pairingID作为“选择”的“值”来进行选择。

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

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