ajax not working .No alert shown after submission - php

I am trying to insert a name into my database. There is a form asking to enter name.There is also a submit button.on clicking the submit button no alert is show.I am new to ajax.
this is index.php.
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").submit(function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: "name=" + name,
success: function() {
alert("sucess");
}
});
});
});
</script>
</head>
<body>
<form action="" method="post">
Name:
<input type="text" name="name" id="name" />
<br />
<input type="submit" name="submit" id="submit" />
</form>
</body>
</html>
This is ajax.php
<html>
<body>
<?php
$query=mysql_connect("localhost","root","root");
mysql_select_db("freeze",$query);
$name='l';//$_POST['name'];
mysql_query("insert into tt values('','$name')");
?>
</body>
</html>

Be careful with url's in ajax. Your url is 'ajax.php', this is a relative url, so, if your page is at url http://localhost.com/index.html (for example), ajax will fire a post to http://localhost.com/index.html/ajax.php (and that's probably wrong). Try use absolute url, for that, add '/' at begin of url, then ajax will be fired against http://localhost.com/ajax.php.
Your ajax code should look like code below:
$(document).ready(function() {
$("#submit").submit(function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "name=" + name,
success: function() {
alert("sucess");
}
});
});
});

The submit event is triggered on the form, not the submit button. So
$("#submit").submit(function() {
will not ever be triggered, because #submit selects the button, not the form. You need to give an ID to the form:
<form id="myform">
then use
$("#myform").submit(function() {
You also need to use event.preventDefault() or return null in the event handler, to prevent the form from being submitted normally when the function returns.

Related

What is error in code below while submitting AJAX from handeled by PHP?

I have a file called try.php where there is code below having all javascript, PHP and html file in itself.
<?php
if(isset($_POST["submit"])){
echo "hello";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Submit Form Using AJAX and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<form method="POST" id="myForm">
<input name="name" type="text" placeholder="Your Name">
<input name="email" type="text" placeholder="email">
<input name="submit" type="submit" value="Submit">
<div id="display"></div>
</form>
<script>
$(document).ready(function(){
$("#myForm").submit(function(event) {
event.preventDefault(); //prevent default action
window.history.back();
var form_Data = $(this).serialize();
$.ajax({
type: "POST",
url: "try.php",
data: form_data,
cache: false,
success:function(response){
alert(response);
}
});
});
});
</script>
</body>
</html>
The target of above code is just to submit form without reloading the page simply using AJAX and the form data should be handled by php here just echo "hello". The above code works fine it submits and php handles all properly but page is reloading. What should be the change in code?
Try this as javascript code
$(document).ready(function(){
$("#myForm").click(function(event) {
event.preventDefault(); //prevent default action
var form_Data = $(this).serialize();
$.ajax({
type: "POST",
url: "try.php",
data: form_Data,
cache: false,
success:function(){
alert("hello");
}
});
});
});

Sending form value using ajax, jquery,php

I am new to ajax and jQuery. I am trying get html form value using ajax and jQuery. I am getting the value but i can not pass that value to another php file. I don't know what i am missing.. can someone help me please..
Here is my form.php file code:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Form</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
});
});
});
</script>
</head>
<body>
<form id="input" method="post" action="">
First Name:<input type="text" name="firstName" id="firstName">
Last Name: <input type="text" name="lastName" id="lastName">
<input type="submit" id="submit" value="submit " name="submit">
</form>
<div id="someElement"></div>
</body>
</html>
Here is my database.php file code:
<?php
if(isset($_POST['submit']))
{
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
echo $firstName;
echo $lastName;
}
You need to add:
return false;
to the end of your click handler. Otherwise, the default submit button action takes place, and the page is refreshed.
Also, remove the line:
if (isset($_POST['submit']))
Submit buttons aren't included when you call .serialize() on a form, they're only sent when the submit button is performing normal browser submission (in case there are multiple submit buttons, this allows the server to know which was used).
You need to do the following
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
return false;
});
Form default event will fire if you dont use return false.
You can use as below
$("#input").submit(function(event) {
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
})
return false;
});
You need to prevent the default action of click event or the form will be processed using the default form action and your ajax call will never be complete.
$("#input").submit(function(event) {
event.preventDefault(); // prevent default action
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
});
});

$.ajax data not posting specified value to $_POST

Okay, what have I done wrong here?
I'm trying to .POST data from a Form with JQuery $.ajax function and return json data. But every time the post data is null.
Here is the HTML/JQuery Part
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
</head>
<body>
<form action="testform" method="post">
OLD ID:
<input id="OldID" name="OldID" type="text"><br>
NewID:
<input id="NewID" name="NewID" type="text"><br>
<input id="do" name="do" type="button" value="Get New ID">
</form>
<script type="text/javascript">
var CID = $('#OldID').val();
$(document).ready(function(){
$('#do').click(function(){
sendValue();
});
function sendValue(CID){
$.ajax({
type: 'POST',
url: 'getNewID.php',
data: {OldID: CID},
dataType: 'json',
cache: false,
success:
function(data){
$('#NewID').val(data.NewID);
}
}) }
});
</script>
</body>
</html>
Here's the PHP page
<?php
if (isset($_POST['OldID'])){
$value = $_POST['OldID'];
}else{
$value = "ELSE VALUE";
}
echo json_encode(array("NewID"=>$value));
?>
I'm sure this is a simple mistake on my part but I'm just going in circles at this point.
Thanks in advance!
$('#do').click(function(){
sendValue();
});
should be:
$('#do').click(function(){
sendValue("VALUE TO SEND TO THE SERVER");
});
because
function sendValue(CID){
takes the scope of CID which it seems you might think should be this var CID = $('#OldID').val();
Your mistake is that you are getting the value of the OldID field in your script, and not on some event handler method. This causes when the script is loaded (when the page is being viewed), the value of the text input is kept on variable CID. and when the user clicks on the #do button, then the value of CID is still the same as the one when the page was loaded. So no value is stored in CID variable, so no value is sent via AJAX.
Define another function (Say sendOldID) that reads the value of the text input in the CID variable, and then calls the sendValue() method with CID paramter. The use that function as the event handler of the #do button clicked.
<script type="text/javascript">
$(document).ready(function(){
$('#do').click(function(){
sendOldID();
});
function sendOldID() {
var CID = $('#OldID').val();
sendValue(CID);
}
function sendValue(CID) {
$.ajax({
type: 'POST',
url: 'getNewID.php',
data: {OldID: CID},
dataType: 'json',
cache: false,
success:
function(data){
$('#NewID').val(data.NewID);
}
}) }
});
</script>

jquery-ajax: pass values from a textfield to a php variable (same a file)

jquery-ajax: pass values from a textfield to php file and show the value
i made a variation of the link above this time using only one file and no div tag.
test.php
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "test.php",
data: "dataString=" + dataString,
success: function(result){
window.location.reload(true);
}
});
window.location.reload(true);
});
});
</script>
</head>
<body>
<input type="text" id="inputtext">
<input type="button" id="submit" value="send">
<?PHP
if(isset($_POST['dataString'])){
$searchquery = trim($_POST['dataString']);
print "Hello " . $searchquery;
}
?>
</body>
</html>
value from dataString won't show. why?
Sorry for the question, but what's the point of using ajax to reload the same page?? Use it to call another page and then load the result, not the way you're doing it.
Try this
In test.php:
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "anothepage.php",
data: dataString,
success: function(result){
$('#result').html(result).
}
});
return false; //so the browser doesn't actually reload the page
});
And you should actually use a form, not just inputs. And use the name attribute for them, or php won't pick the value! ID is for javascript and css.
<form method="POST" action="">
<input type="text" id="inputtext" value="" name="inputtext">
<input type="submit" id="submit" value="send" name="submit">
</form>
<div id="result"> <!-- result from ajax call will be written here --> </div>
In anotherpage.php:
if(isset($_POST['inputtext'])){
$searchquery = trim($_POST['inputtext']);
echo htmlentities($searchquery); // We don't want people to write malicious scripts here and have them printed and run on the page, wouldn't we?
}
When you refresh the page using JavaScript, you lose any POST parameters you sent to the page. That is one reason why you never saw any valid results.
You are also missing the benefits from using AJAX - A motivating reason to deploy AJAX is to remove the requirement to refresh the page while still accepting and processing user input.
If you prefer to process the data from AJAX on the same page that is serving the HTML, here is a working example based on your supplied code.
<?php
if( isset($_POST['dataString']))
{
echo 'Hello ' . trim( $_POST['dataString']);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<title>Testing jQuery AJAX</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "test.php",
data: "dataString=" + dataString,
success: function( data){
alert( data);
}
});
});
});
</script>
</head>
<body>
<form action="test.php" method="post">
<input type="text" id="inputtext" />
<input type="button" id="submit" value="send" />
</form>
</body>
</html>

Insert record using jQuery after ajax call doesn't work

I have an insert and load record (jQuery & PHP) script working fine without using AJAX. but after the AJAX call, insert (jQuery) doesn't work.
This is my code:-
$(".insert").live("click",function() {
var boxval = $("#content").val();
var dataString = 'content='+ boxval;
if(boxval==''){
alert("Please Enter Some Text");
}
else{
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(html){
$("table#update tbody").prepend(html);
$("table#update tbody tr").slideDown("slow");
document.getElementById('content').value='';
}
});
}
return false;
});
$(".load").live("click",function() {
$.ajax({
type: "POST",
url: "test.php",
success: function(msg){
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
}
});
});
});
Definitely recommend using your browsers dev tools to examine the exact request that is submitted and see if there is a problem there first.
You might also want to change the way you pass the dataString to the ajax request.
If your boxval has a "&" in it then you'll end up with an incorrectly formatted string. So, try initialising data instead as:
var data = {};
data.content = boxval;
This will ask jQuery to escape the values for you.
I'd be curious to see your form markup and your back-end PHP code; it may provide a clue.
Often I'll have a form variable called 'action', just to tell the PHP code what I want it to do (especially if that PHP script is a controller for many different actions on an object). Something like <input type="hidden" name="action" value="insert"/> or even multiple <input type="submit" name="action"/> buttons, each with a different value. In the PHP code I'll have something like:
switch ($_POST['action']) {
case 'insert':
// insert record and send HTML
break;
// other actions
}
If you've done something like this, perhaps the PHP is looking for the presence of a variable that doesn't exist.
Without being able to look at your code, I'd highly recommend the incredibly handy jQuery Form Plugin http://jquery.malsup.com/form/ . It allows you to turn a form into an AJAX form, formats your data properly, and doesn't forget the data from any of your form elements (except <input type="submit"/> buttons that weren't clicked on, which is the same behaviour that a non-AJAX form exhibits). It works just like the standard $.ajax() method.
I solved the problem
I replaced this code
$("#container").ajaxComplete(function(event, request, settings){
$("#container").html(msg);
});
with
$("#container").html(msg);
Thank you very much for your answers
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.clicker').click(function(){
var fname = $('.fname').val();
var lname = $('.lname').val();
var message=$('.message').val();
$.ajax({
type:"POST",
url: "submit.php",
cache:false,
data: "fname="+fname+"&lname="+lname+"&message="+message,
success: function(data){
$(".result").empty();
$(".result").html(data);
}
});
return(false);
});
});
</script>
</head>
<body>
<div>Data Form</div>
<form id="form1" name="form1" method="post" action="">
<input name="fname" type="text" class="fname" size="20"/><br />
<input name="lname" type="text" class="lname" size="20"/><br />
<div class="result"><textarea name="message" rows="10" cols="50" class="message"> </textarea></div>
<input type="button" value="calculate" class="clicker" />
</form>
</body>
</html>
submit.php
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("ajaxdb",$con);
$fname=$_REQUEST['fname'];
$lname=$_REQUEST['lname'];
$message=$_REQUEST['message'];
$sql="insert into person(fname,lname,message) values('$fname','$lname','$message')";
mysql_query($sql) or die(mysql_error());
echo "The data has been submitted successfully.";
?>

Categories