How to submit a form on SUBMIT or ENTER button - php

I am trying to follow a tutorial and demo. But when I press SUBMIT or ENTER button, it is not submitting, it is just refreshing the page :( and showing an error.
It shows an alert
There was a problem with the request.
And the page refreshes.
My form
<form class="well-home span6 form-horizontal" name="ajax-demo" id="ajax-demo"> <div class="control-group">
<label class="control-label" for="book">Book</label>
<div class="controls">
<input type="text" id="book" onKeyUp="book_suggestion()">
<div id="suggestion"></div>
</div> </div> <div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
And my Javascript
<script>
function book_suggestion()
{
var book = document.getElementById("book").value;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "book_name=" + book;
xhr.open("POST", "book-suggestion.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//alert(xhr.responseText);
document.getElementById("suggestion").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
book-suggestion.php
<?php
include('../includes/dbopen.php');
$book_name = $_POST['book_name'];
$sql = "select book_name from book_mast where book_name LIKE '$book_name%'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<p>".$row['book_name']."</p>";
}
?>

The submit button used there is not participating in the demo. The purpose of the demo is to show how to fetch data with ajax when user types data in the text box. It may, for sure be extended so that the submit button acts upon and adds some more functions, but for now, that has not been added to the demo.

Related

Modal ajax form stuck on success message when refired

I have a page with roughly 20 enquiry buttons. Each button fires the same modal ajax PHP form. The form system works as it should, sending an email and triggering the success message. The success message displays inside the form tags but the rest of the form disappears leaving just tags.
The success message has a close button which closes the modal but the problem is that when I click any of the other enquiry buttons on the page they fire the modal but its still stuck on the success message.
Is there a way of using the modal close button as a sort of clear form trigger?
This is the ajax script im using…
<script>
function _(id){ return document.getElementById(id); }
function submitForm() {
_("sendenquiry").disabled = true;
_("status").innerHTML = 'please wait…';
var formdata = new FormData();
formdata.append( "n", _("n").value );
formdata.append( "e", _("e").value );
formdata.append( "m", _("m").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "enquire.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("enquiry_form").innerHTML = '<p>Thanks '+_("n").value+', we will be in touch shortly.</p>';
} else {
_("status").innerHTML = ajax.responseText;
_("sendenquiry").disabled = false;
}
}
}
ajax.send( formdata );
}
</script>
This is my html
<!--enquiry modal-->
<div class="enquire-form-modal ef-effect" id="efmodal">
<div class="ef-content">
<div>
<form class="enquire-message" id="enquiry_form" onsubmit="submitForm(); return false;">
<fieldset>
<legend>Please fill out your enquiry below and we'll quickly get back to you.</legend>
<div class="">
<label class="" for="">Name</label>
<span><input type="text" id="n" class="" name="" placeholder="My name" required></span>
</div>
<div class="">
<label class="" for="">Email</label>
<span><input type="email" id="e" class="" name="email" placeholder="My email" required></span>
</div>
<div class="">
<label class="" for="">Enquiry</label>
<span><textarea id="m" class="" name="" placeholder="My enquiry" required></textarea></span>
</div>
<div>
<input id="sendenquiry" type="submit" value="SEND"> <span id="status"></span>
</div>
</fieldset>
</form>
<button class="ef-close">Close</button>
</div>
</div>
</div>
<div class="enquire-form-overlay"></div>
<!--enquiry modal end-->
Any help would be hugely appreciated. I’ve tried various things but nothing is working yet. If you need more code please let me know.
Thanks in advance
The problem is that you're replacing all of the form's html when the ajax call is complete. Try using the "status" div for housing the success message. Then, perhaps a simple setTimeout will suffice for clearing the message.
<script>
function _(id){ return document.getElementById(id); }
function submitForm() {
_("sendenquiry").disabled = true;
_("status").innerHTML = 'please wait…';
var formdata = new FormData();
formdata.append( "n", _("n").value );
formdata.append( "e", _("e").value );
formdata.append( "m", _("m").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "enquire.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("status").innerHTML = '<p>Thanks '+_("n").value+', we will be in touch shortly.</p>';
} else {
_("status").innerHTML = ajax.responseText;
}
// clear the "status" message after 5 seconds
setTimeout(function() {
_("status").innerHTML = "";
}, 5000);
_("sendenquiry").disabled = false;
}
}
ajax.send( formdata );
}
</script>

XMLHttpRequest not getting response after inserting in MySQL using PHP

I have surfed a lot and i have also tried all the possibilities to get this done, but still it is not working. What I am doing is, trying to insert product category using XMLHttpRequest and if recorded inserted successfully it should return true as response else false as response.
front page:
<form id="form_validation" method="POST" onsubmit="InsertCategory()">
<div class="form-group form-float">
<div class="form-line">
<input type="text" class="form-control" name="category_name" id="category_name" required>
<label class="form-label">Category Name</label>
</div>
</div>
<button class="btn btn-primary waves-effect" type="submit" name="submit">SUBMIT</button>
</form>
<script>
function InsertCategory()
{
var category_name=document.getElementById("category_name").value;
var operation="insert";
var url = "includes/ajax/category_master/categoryOperations.php";
//var url = "includes/ajax/getDocuments.php";
var params = "category_name="+category_name+"&operation="+operation;
var http = new XMLHttpRequest();
http.onreadystatechange = function()
{
console.log("rs "+http.response);
console.log(http.readyState);
console.log(http.status);
if(http.readyState == 4 && http.status == 200)
{
}
}
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
}
</script>
here is categoryOperations page
<?php include_once("connection.php");
$operation=$_POST["operation"];
switch($operation)
{
case "insert":
$category_name=$_POST["category_name"];
$query="insert into product_category(category_name)values(:category_name)";
$stmt=$con->prepare($query);
$stmt->bindParam(":category_name",$category_name);
if($stmt->execute())
{
echo "true";
}
else
{
echo "false";
}
break;
case "update":
break;
case "delete":
break;
}
?>
What happens here is, all code work fine, category inserts in product_category table but i am not able to receive true as response.
if I comment $stmt->execute() in categoryOperations page and echo true then it works fine, on console I get true. but if query is executed it does not return anything.
I am not able to understand this behavior of the code.
Got Solution
The problem was, i have written
<form id="form_validation" method="POST" onsubmit="InsertCategory()">
that was sending two request. with form as well as from xmlhttprequest.
i just removed <form> tag and called InsertCateory() on submit button
<button class="btn btn-primary waves-effect" type="submit" onClick="InsertCategory()" name="submit">SUBMIT</button>

how to check which button is clicked in php file with ajax call

I have a form post.php where the user inputs data and receivepost.php where the data entered is transferred through Ajax post. I want to achieve the following in the receivepost.php:
if (button save is pressed) {
save to database
} else if (button retrieve is pressed) {
retrieve from database
}
I tried using isset($_POST['submit']) on the reveivepost.php but it does not detect the button which is pressed. The Ajax post is working and all the data is available on the receivepost page. I have another solution that is to create 2 different PHP files and run them according to the button pressed but I think there is a better solution to it.
Here is my ajax call :
$("document").ready(function () {
$("#submit").click(function () {
var xmlhttp;
// test browsers
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// get the values of textboxes
var desc_text = $("#desc").val();
var speed_text = $("#speed").val();
var tarea_text = $("#tarea").val();
// variable to hold value of textboxes
var content = "desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
// open the request
xmlhttp.open("POST", "receivepost.php", true);
// set header
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// check xmlhttp state and status and display text in div
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('para').innerHTML = xmlhttp.responseText;
}
}
// send the content of the textboxes
xmlhttp.send(content);
});
});
Here is my post.php form:
<form id="myform">
<label for="description">Description:</label>
<input type="text" id="desc" name="desc" /><br/>
<label for="speed">Speed: </label>
<input type="text" id="speed" name="speed" /><br/>
<textarea id="tarea" cols="10" rows="10" name="tarea"></textarea><br/>
<input type="button" id="submit" name = "submit" value="Save">
<input type="button" id="retrieve" name="retrieve" value="Retrieve">
</form>
<div id="para"></div>
Try to add to the content an extra parameter called button-pressed which you can later use in receivepost.php as below:
if($_POST['button-pressed']=="save"){
//savetodb code
}
else if($_POST['button-pressed']=="retrieve"){
//retreivefromdb code
}
Perhaps you have two JavaScript functions, one on each button:
$("#submit").click(function () {
var content = "button-pressed=save" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
$("#retrieve").click(function () {
var content = "button-pressed=retrieve" + "&desc=" + desc_text + "&speed=" + speed_text + "&tarea=" + tarea_text;
Hope this helps?
<input type="button" id="submit" name ="submit" value="save" onClick="fnc(this.id)">
<input type="button" id="retrieve" name="retrieve" value="retrieve" onClick="fnc(this.id)">
<script type="text/javascript">
function fnc(myid) {
var val=document.getElementById(myid).value;
alert(val);
}
</script>

Display AJAX Loader on submitting a from

I would like to display an ajax loader icon when user try to submit a form, and block the content of the page (Fade in).
I have this code, but it works wrongly, it display the loader icon before submitting the form and hide it after submitting the form.
<script type="text/javascript">
function ajaxFunction() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
document.getElementById("content").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", "?action=sms&pageaction=Send SMS", true);
xmlHttp.send(null);
}​
</Script>
And I have DIV :
<!---progress-->
<div id="content" >
<br/>
<br/>
<br/>
<h1>Loading ... Please wait </h1>
<br/>
<br/>
<img src="image//loading.gif" />
</div>
<!---progress-->
And the submit button is calling the ajaxFunction()
<input type="submit" name="pageaction" class="send_sms" value="Send SMS" onclick="ajaxFunction()" />
Anybody please help me in correcting my code to make it work as follow:
display a transparent background to block the page while submitting the form.
display a loading icon.
Hide the transparent background and hide the loading icon.
Thanks for all
Set your content to hide. You can do that simply:
<div id="content" style="display:none;">
...
</div>
Put it visible before sending the AJAX request.
document.getElementById("content").style.display = "block";​​​​​​
xmlHttp.send(null);

jQuery and JavaScript AJAX Database Queries

I seem to have no luck with these darn AJAX MySQL queries...
I'm trying to query the database when a selection from a drop-down menu is made, and fill a div with the results from the script. I've tried two different ways, with no luck either time.
METHOD 1
Javascript
var ajaxRequest;
var create_url = "create_script.php";
var process_url = "process.php";
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
}
}
}
function races(id)
{
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
document.getElementById('race_info').innerHTML = ajaxRequest.responseText;
}
}
var params = "mode=race&id="+id;
ajaxRequest.open("POST", create_url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", params.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(params);
}
function classes(id)
{
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
document.getElementById('class_info').innerHTML = ajaxRequest.responseText;
}
}
var params = "mode=classes&id="+id;
ajaxRequest.open("POST", create_url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", params.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(params);
}
the page body:
<div id="contentwrapper">
<div id="contentcolumn">
<div class="innertube">
<?php
if($step == 0)
{
?>
<form action="<?php echo $u_create; ?>" method="post">
<h2>Races</h2>
<select id="race_select" name="race_select">
<?php
$sql = 'SELECT * FROM '.RACES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option onfocus="races('.$row['race_id'].');" value="'.$row['race_id'].'">'.$row['race_name'].'</option>'."\n";
}
?>
</select>
<h2>Classes</h2>
<select id="class_select" name="class_select">
<?php
$sql = 'SELECT * FROM '.CLASSES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option onfocus="classes('.$row['race_id'].');" value="'.$row['class_id'].'">'.$row['class_name'].'</option>'."\n";
}
?>
</select>
<br />
<input type="submit" value="Select" name="submit" />
</form>
<br />
<div id="race_info"></div>
<br />
<hr />
<br />
<div id="class_info"></div>
<?php
}
?>
</div>
</div>
</div>
METHOD 2
AJAX
$(document).ready(function() {
$("#race_select").change(function() {
var race = $("#race").val();
$.ajax({
url: 'create_script.php',
data: 'mode=race&id=' + race,
dataType: 'json',
success: function(data)
{
$("#race_info").html(data);
}
});
});
$("#class_select").change(function() {
var class = $("#class").val();
$.post("create_script.php", { mode: "class", id: class }, function(data) {
$("#class_info").html(data);
});
});
});
The page body:
<div id="contentwrapper">
<div id="contentcolumn">
<div class="innertube">
<?php
if($step == 0)
{
?>
<form action="<?php echo $u_create; ?>" method="post">
<h2>Races</h2>
<select id="race_select" name="race_select">
<?php
$sql = 'SELECT * FROM '.RACES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option id="race" value="'.$row['race_id'].'">'.$row['race_name'].'</option>'."\n";
}
?>
</select>
<h2>Classes</h2>
<select id="class_select" name="class_select">
<?php
$sql = 'SELECT * FROM '.CLASSES_TABLE;
$result = $db->sql_query($sql);
while($row = $db->sql_fetchrow($result))
{
echo '<option id="class" value="'.$row['class_id'].'">'.$row['class_name'].'</option>'."\n";
}
?>
</select>
<br />
<input type="submit" value="Select" name="submit" />
</form>
<div id="race_info"></div>
<hr />
<div id="class_info"></div>
<?php
}
?>
</div>
</div>
</div>
None of the attempts have worked at all. I'm not sure what I'm doing wrong. There's not even a POST request being made on the select option change, according to firebug.
well for starters, in method two, all of your select options have the same ids. therefore, when querying:
var race = $("#race").val();
you will always get the first option.
instead, within the change function, this will refer to the selected element. so:
var race = $(this).val();
will get what you want
EDIT
Here is a simplified example using your code demonstrating your desired behavior in jsfiddle form: http://jsfiddle.net/7Xtqv/1/
hope that helps
In your jQuery AJAX request, you're setting dataType to JSON. So jQuery attempts to parse the JSON once received. If it fails, nothing happens. Not even the request shown in Firebug.
If you're using html in your AJAX return, you should set the dataType to HTML.
EDIT
Oh and in the second request in your jQuery file, you're doing var class = $("#class").val();. You might want to avoid naming your vars with reserved names: http://www.quackit.com/javascript/javascript_reserved_words.cfm
EDIT2
As #pthurlow noticed, there's a big fail with your IDs names. You're trying to get #race select, but there's no race ID in your HTML. There's a #race_select but it's different from #race.
It also fails with your #class stuff.

Categories