Reputation:
I am using Ajax and jQuery to get output on click event of submit button
I have two files
Index.php
(contains the jQuery & Ajax Code)actionfile.php
(A php file that extracts the data sent by Ajax code in Index.php
and stores the data in a file)Index.php:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form name="myform" method="post">
<input type="text" name="txt1" id="txt1" value="121212"/>
<input type="submit" value="submit" id="submit" name="submit" />
</form>
<script>
$("#submit").click(function() {
var txt =document.getElementById('txt1').value; //textbox value
alert(txt);
var txt1 = "txt1="+txt;
alert(txt1);
$.ajax({
type: "POST",
url: "actionfile.php",
data:txt1,
success: function() {
alert("success");
}
});
});
</script>
</body>
</html>
And actionfile.php:
<?php
error_reporting(E_ALL);
$map=$_POST['txt1'];
$fp=fopen("file.txt","w");
fwrite($fp,$map);
fclose($fp);
?>
The problem is, if I remove the piece of code $("#submit").click(function()
ajax works fine, meaning it submits data when the page is loaded (provided I give default value in textbox). When I keep the code $("#submit").click(function()
intact, the function is called only when submit button is pressed but in this case AJAX fails.
The code is available on http://www.code.guru99.com/kishore
What is causing this issue?
Upvotes: 2
Views: 1853
Reputation: 2368
Use Like this:
Change submit into button.
<form name="myform" method="post">
<input type="text" name="txt1" id="txt1" value="121212"/>
<input type="button" value="submit" id="submit" name="submit" onclick="test();" />
<script>
function test()
{
var txt =document.getElementById('txt1').value; //textbox value
alert(txt);
var txt1 = "txt1="+txt;
alert(txt1);
$.ajax({
type: "POST",
url: "actionfile.php",
data:txt1,
success: function() {
alert("success");
}
});
}
</script>
hope this will give you some solution.
Upvotes: 0
Reputation: 227240
Your code works when you remove the $("#submit").click(function()
because your <form>
is posted and the data is sent.
To have AJAX submit the data, you need to use type="button"
, or change your event to:
$("#submit").click(function(e) {
e.preventDefault();
Upvotes: 0
Reputation: 5136
Just change the type form submit
to button
:
<input type="button" value="submit" id="submit" name="submit" />
Upvotes: 0
Reputation: 2799
try this:
$("form").submit(function(e){
e.preventDefault();
var txt =document.getElementById('txt1').value; //textbox value
alert(txt);
var txt1 = "txt1="+txt;
alert(txt1);
$.ajax({
type: "POST",
url: "actionfile.php",
data:txt1,
success: function() {
alert("success");
//here you can simulate click submit
}
});
});
});
Upvotes: 1