I have a piece of HTML code:
<div id="question_form">
<form method="POST" id="question_form" action="addQuestion.php">
<input type="hidden" id="u_id" name="u_id" value="6"/>
<input type="hidden" id="u_a_name" name="u_a_name" value=""/>
<textarea placeholder="question here" cols="138" rows="3" name="question" id="question_input"/>
<input type="image" class="ask_button" value="submit" src="img/ask.png"/>
</form>
</div>
And here is JavaScript:
$(".ask_button").click(function() {
$.ajax({
type: "POST",
url: "addQuestion.php",
data: $("div#question_form").formSerialize() + "&textareadata="+escape($("#question_input").value),
success: function(data)
{
if (data == "Asked") {
window.location.reload();
} else {
alert(data);
}
}
});
return false;
});
The php file checks is question is empty and if not - writes it into database.
When I click on submit button I see the addQuestion.php page, not alert, though php script is executed correctly. What can be a problem?
escape($("#question_input").value)
should be encodeURIComponent($("#question_input").val())
The jQuery object has no value property(use .val()
instead) which is causing an error in your code and presumably causing the form to submit to addQuestion.php
You also have two id
tags with the same name:
<div id="question_form">
<form method="POST" id="question_form" action="addQuestion.php">
Each id
tag must be completely unique in the HTML for jQuery to supply expected results. Try renaming one of them.
You can take a look at this similar issue here
Which is already solved by me. And hope that will help you too.
Ok, it is solved. Really I used bad script so I changed .value
to .val()
and put all parametrs by hand, so now it seems to be working.
You are probably having a Javascript error that prevents the form from being sent via ajax, and it gets submitted with regular HTTP means.
You can not see the difference because form's action
attribute is the same as ajax request url. If you change any of them you will notice what I explain.
To track the issue, you should enable "preserve logging upon navigation" or similar option in your firebug/firefox/chrome console, do the test again and see that the error pops in console exactly before you get navigated to addQuestion.php
.
You can simply do like this to avoid this type of issues,
$(document).ready(function(){
$(".ask_button").click(function() {
$.ajax({
type: "POST",
url: "addQuestion.php",
data: $("#question_form").serialize(),
success: function(data)
{
if (data == "Asked") {
window.location.reload();
} else {
alert(data);
}
}
});
return false;
});
});
and give different id for div and form...
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.