Так что я хочу отправить некоторые данные (из формы) в серверную базу данных с помощью AJAX, но по какой-то причине это означает, что скрипт AJAX вообще не работает. Когда я отправляю форму, скрипт PHP выполняется без проблем. Я смотрел повсюду, чтобы ответить, но пока ничего не получилось. Это может быть что-то глупое, но мне все равно нужна помощь.AJAX/PHP не работает
Jquery/AJAX скрипт:
$(document).ready(function() {
$('#InputForm').submit(function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
async: true,
type: type,
data: data,
success: function(response){
$(#Suc_Sub).fadeIn(800);
}
});
return false;
});
});
PHP и HTML сценарий:
$url = "";
$email = "";
$comment = "";
$stage = "";
$url_error = "";
$email_error = "";
$comment_error = "";
if(!empty($_POST['websiteURL']))
{
$url = $_POST['websiteURL'];
$regex = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i";
if (!preg_match($regex, $url))
{
$url_error = "Invalid Url";
}
}
else
{
$url_error = "Url is blank";
}
if(!empty($_POST['userEmail']))
{
$email = $_POST['userEmail'];
$email = fix_input($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$email_error = "Invalid email";
}
}
else
{
$email_error = "Email is blank";
}
if(!empty($_POST['userComment']))
{
$comment = $_POST['userComment'];
$comment = fix_input($comment);
$regex = "/^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$/";
if (!preg_match($regex, $comment))
{
$comment_error = "Invalid Comment";
}
}
else
{
$comment_error = "Comment is blank";
}
$stage = $_POST['websiteStage'];
if(empty($email_error) && empty($url_error) && empty($comment_error))
{
$date_parts = getdate(date("U"));
$post_date = "$date_parts[mday]-$date_parts[mon]-$date_parts[year] - $date_parts[hours]:$date_parts[minutes]:$date_parts[seconds]";
mysqli_query($con,"INSERT INTO submit (URL,EMAIL,COMMENT,STAGE,Date)
VALUES ('$url','$email','$comment','$stage','$post_date')");
die();
}
else
{
die();
}
<form method="post" id="InputForm" action="..\Scripts\sbt.php">
<fieldset style="border:none">
<ul style="list-style-type: none;">
<li>
<label for="websiteURL"> <img src="..\Images\blank tick.png" id="Website_Image" height="50" width="60"> </label> <!--Dont forget about the label pics-->
<input size="25" autocomplete="off" title="Type your URL" type="url" id="websiteURL_Box" class="TextInput" name="websiteURL" required="required" placeholder="Your Website URL..." autofocus="autofocus" maxlength="100"/>
<div id="flyout_hidden_url" hidden></div>
</li><br>
<li>
<label for="userEmail"> <img src="..\Images\blank tick.png" id="Email_Image" height="50" width="60"> </label> <!--Dont forget about the label pics-->
<input size="25" autocomplete="off" title="Your Email plz" type="email" id="userEmail_Box" class="TextInput" name="userEmail" required="required"required="required" placeholder="Your Email..." autofocus="autofocus" maxlength="100"/>
<div id="flyout_hidden_email" hidden></div>
</li><br>
<li>
<label for="userComment"> <img src="..\Images\blank tick.png" id="Comment_Image" height="50" width="60"> </label> <!--Dont forget about the label pics-->
<input size="25" autocomplete="off" title="Your Comment" type="text" id="userComment_Box" class="TextInput" name="userComment" placeholder="Any comments...?" autofocus="autofocus" maxlength="100"/>
<div id="flyout_hidden_comment" hidden></div>
</li><br>
<li>
<label for="websiteStage"> </label>
<select name="websiteStage" class="custom">
<option value="Alpha">Alpha Version</option>
<option value="Beta">Beta Version</option>
<option value="Finished">Finished</option>
</select>
</li><br>
<li>
<label id="botTest_Label" for="botQuestion">I am not a cyborg!</label> <!--Dont forget about the label pics-->
<input type="checkbox" required="required" value="botQ" id="botTest_Box" title="For Bot testing!">
</li><br>
<input id="SubmitButton" type="submit" disabled value="Submit">
</ul>
</fieldset>
</form>
Любой вид помощи ценится. Большое спасибо.
Что «не работает»? Любые сообщения об ошибках? Вы открыты для SQL-инъекций, используйте подготовленные заявления. – chris85
Мы не можем отлаживать это для вас.Когда вы его отлаживаете, где конкретно это происходит? Когда вы проходите через код JavaScript, он делает то, что вы ожидаете? Выполняется ли запрос POST? Он содержит данные, которые вы ожидаете? Каков ответ сервера? – David
Когда я отправляю форму, она просто выполняет скрипт PHP. И когда я проверяю консольный журнал, чтобы увидеть, что-то не так, он ничего не говорит. Его вроде он не существует. – GeorgeS