I am trying to learn Ajax. I am inserting some data to mysql database from a Html Form by php. It works nicely. But my ajax part does not work. I get the success message but data dont go to my php file. My html and js code:
<!DOCTYPE html>
<html>
<head>
<title>Insertion of data with Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
</head>
<body>
<form id="myForm" method="POST" action="ajax-save.php">
Title: <input type="text" name="title" id="title"><br /><br />
Description: <textarea name="description" id="description" rows="20" cols="40"></textarea><br /><br />
Url: <input type="text" name="url" id="url"><br /><br />
<input type="submit" id="submit" name="submit" value="submit">
</form>
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
url: 'ajax-save.php',
async: true,
cache: false,
data: $('#myForm').serialize() ,
type: 'POST',
success: function(){
alert("success");
clearForm();
}
});
return false;
});
});
</script>
</body>
</html>
My php codes are working properly. I have tested it without ajax. Here is my php code.
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('hospital');
if (isset($_POST['title'])) { $title = $_POST['title'];}
if (isset($_POST['description'])) { $description = $_POST['description'];}
if (isset($_POST['url'])) { $url = $_POST['url'];}
if(isset($_POST['submit'])){
if(mysql_query("insert into `wp_upload_video` (`id`, `title`, `description`, `url`) values (NULL, '$title', '$description', '$url')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
}
Please let me know where is my fault.
When you submit via ajax on a click of the submit button.... that condition is always true.
Checking if $_POST['submit'] is set in the PHP will always result in true because if it is not true the ajax never gets processed.
So... remove the if submit condition in the PHP and handle error notification in the ajax call.
Also, as pointed out by #NiettheDarkAbsol in comments, it's a good idea to add e.preventDefault() to the jquery as well to stop the submit button submitting the form as it normally would and allow the jquery to handle the submit (via ajax).
Related
I am new to AJAX, and I want to learn how to validate a form. Suppose, I have a form with two input fields. When I click in submit I want to check the page with a php script. When the validation is succesfull I want to redirect to the action="submitForm.php". When one or more fields are not valid according to the validation.php I want to stay on the page and gives a error message next to the field.
What is the best way to do that?
<html>
<head>
</head>
<body>
<form action="submitForm.php" action="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</body>
</html>
submitForm.php:
<?php
echo $_POST["username"];
echo "<br />";
echo $_POST["password"];
?>
In order to process the fields before actually submitting the form, you can catch its submit event:
<form action="submitForm.php" action="post" onsubmit="return MyValidation()">
Then, in your javascript:
function MyValidation() {
var valid = false;
$.ajax({
type: "POST",
url: "validation.php",
async: false,
data: { name: $('#username').val(), password : $('#password').val() }
})
.done(function( data ) {
if(data == 'true') {
valid = true;
}
});
// not valid, return false and show some hidden message
return valid;
}
(you need to add an ID to the <input> fields in order for the jquery selectors to work...)
There is two solutions who might help you
http://www.w3resource.com/ajax/working-with-PHP-and-MySQL.php
http://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59
I`m trying to make somethig like login with jquery. There should be a validation on text fields to echo error message. If the form is completely validated then function in jquery should update the div, where there is the input form and change it to the session name. But There is a problem, when posted form is validated then div remains empty, there is no session name.
HTML:
<html>
<head>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery('#form').submit(function(){
jQuery.ajax({
type: 'POST',
url: jQuery('#form').attr('action'),
data: jQuery('#form').serialize(),
success: function(data){
if(data == 'success'){
jQuery('#user').load(location.href+' #user>*');
}else{
jQuery('#info').html(data);
}
}
});
return false;
});
});
</script>
</head>
<body>
<div id="user">
<div id="info"></div>
<?php
session_start();
if(isset($_SESSION['user'])){
echo $_SESSION['user'];
}else{
echo '
<form method="post" action="session.php" id="form">
<input type="text" name="user" />
<input type="submit" name="do" value="ok" />
</form>
';
}
?>
</div>
</body>
</html>
PHP:
<?php
$user = mysql_real_escape_string($_POST['user']);
if(empty($user)){
echo 'psc';
}else{
echo 'success';
session_start();
$_SESSION['user'] = $user;
}
?>
I think type: 'POST' in your ajax call is usually done in lower case: type: 'post'. I am not sure if this is the issue, but you may want to try it.
Aside from that, the other problem with your code is that you are not preventing the form from being submitted. So basically you are sending an ajax message, but then immediately loading a new page with the default submit that occurs when clicking the submit button. I would think that this has the effect of loading a blank page?
To fix this you could add to your submit handler the following lines:
jQuery('#form').submit(function(event){
event.preventDefault();
Notice I have added event to the handlers arguments, and then called the preventDefault() method to stop the form from actually submitting. Returning false in the handler does not do this for you.
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.";
?>
This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 7 years ago.
I'm still new to JQuery, AJAX and PHP.
I was wondering what I could be doing wrong here. I am taking in information about a customer and trying to return a confirmation message on the same page.
So the problems I am having:
1) Clicking on the submit button refreshes my page? Why?
2) I have a underneath my submit button. How would I be able to change the text of that with the results of addCustomer.php?
3) Is it okay to have my javascript and php code in the same file under customer.php?
Edit: Also I am using Firefox's Tamper Data Addon - when I click submit, no data is sent for some reason.
Customer.php
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function() {
$.ajax({
type : 'POST',
url : 'addCustomer.php',
dataType : 'json',
data:{
add_LN : $('#add_LN').val(),
add_FN : $('#add_FN').val(),
add_PN : $('#add_PN').val(),
add_DOB : $('#add_DOB').val()
},
success : function(data){
//I want to change the "confirmMsg" to the string given back from addCustomer.php
}
}
}
}
</script>
<p> </p>
<p>Add New Customer:</p>
<div align="center">
<form>
<table width="396" border="1">
<tr>
<td width="133"><p>Last Name:</p>
<p>First Name:</p>
<p>Phone Number:</p>
<p>Date of Birth:</p></td>
<td width="144"><p>
<input type="text" name="add_LN" id="add_LN" />
</p>
<p>
<input type="text" name="add_FN" id="add_FN" />
</p>
<p>
<input type="text" name="add_PN" id="add_PN" />
</p>
<p>
<input type="text" name="add_DOB" id="add_DOB" />
</p> </td>
<td width="97"><input type="submit" name="submit" id="submit" value="Add Customer" /></td>
<div id="confirmMsg"/>
</tr>
</table>
</form>
</div>
<p> </p>
</div>
</div>
addCustomer.php
<?php
$username="******";
$password="******";
$database="******";
if (isset ($_POST['add_LN']))
$lastName=$_POST['add_LN'];
else
die("Last Name not passed in POST");
if (isset ($_POST['add_FN']))
$firstName=$_POST['add_FN'];
else
die ("First Name not passed in POST");
if (isset ( $_POST['add_PN']))
$phone=$_POST['add_PN'];
else
die("Phone Number not passed in POST");
if (isset ($_POST['add_DOB']))
$dob=$_POST['add_DOB'];
else
die("Date of Birth not passed in Post");
//$membership==$_POST['membership'];
mysql_connect("dbs4.cpsc.u.ca",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO customer (last_name, first_name, phone_no, date_of_birth, membership) VALUES ('$lastName', '$firstName', '$phone', '$dob', 'T')";
if (mysql_query($query)){
echo "Thanks";
} else
{
echo "Failed to insert customer into database";
}
mysql_close();
?>
Thanks so much for the help!
Ok, to answer your questions in order:
You should be able to check from Firebug (you are using Firebug, right?) in the Console tab to see that addCustomer.php is the endpoint being called by your Ajax request. Failing that, you can add the following code into your scripts:
$('#confirmMsg').ajaxComplete(function(e, xhr, settings) {
$(this).text('The response from your page is ' + xhr.responseHTML);
});
I'm assuming that your question here is "I have a div underneath my submit button...". Try the following command (which is a shortened version of the full Ajax method):
$.post('addCustomer.php', {
add_LN : $('#add_LN').val(),
add_FN : $('#add_FN').val(),
add_PN : $('#add_PN').val(),
add_DOB : $('#add_DOB').val()
}, function(data){
$('#confirmMsg').text(data);
});
Finally, yes - it is ok to have your script and PHP code on the same page. The PHP code is executed on the server before being rendered to your browser and the JavaScript works on the client side, executing once the page is delivered.
1) you can use the "preventDefault" on the click function.
2) you can add a success message by just displaying the "confirmMsg" div (hide it first with css)
3) if thats works for you it's oke. but i self try to keep all the code just on one place eg. "main.js"
See the code: ^my changes^ "just remove the ^ to make it work :)"
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(^e^) {
^e.preventDefault();^
$.ajax({
type : 'POST',
url : 'addCustomer.php',
^data: $('form').serializeArray(),^
success : function(data){
^$('#confirmMsg').show();^
}
}
}
}
</script>
I think this should do the trick :)
I've added the serializeArray function to make it more dynamic because if you have more input fields you don't have to change the js code again. http://api.jquery.com/serializeArray/
You can see what the form sends to first open firebug and reload the page then field the fields then submit it. You will see in the "console" tab some change ;)
I hope this will help you out.
I suggest you change dataType: 'json' to dataType: 'text', that might be what's tripping jQuery up.
And change your success handler to
success: function(data){
$("#confirmMsg").html(data);
}
Problem was the was not in the head of that file. It fixed all my problems but not sure why. Thanks to everyone who contributed
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<style type="text/css">
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(e) {
$.ajax({
type : 'POST',
url : 'addCustomer.php',
dataType : 'json',
data:{
lastName : $('#add_LN').val(),
firstName : $('#add_FN').val(),
phone : $('#add_PN').val(),
dob : $('#add_DOB').val()
},
success : function(data){
if (data.error === true){
alert("there was an error in the post layer");
} else {
$('#confirmMsg').html(data);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
return false;
});
});
</script>
I'm trying to get this to work, but I am having issues. What am I missing here?
I'm trying to insert some data via jQuery to a local MySQL table. If I run save.php on its own, it inserts a blank row in the DB, so that works. Any ideas?
**index.php**
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('form#submit').submit(function () {
var nume = $('#nume').val();
$.ajax({
type: "POST",
url: "save.php",
data: "nume="+ nume,
success: function() {
$('#nume').val('');
}
});
return false;
});
});
</script>
</head>
<body>
<form id="submit" method="post">
<p>Nume: <input id="nume" name="nume" type="text"></p>
<p><input id="submitButton" type="button" value="Submit"></p>
</form>
</body>
</html>
**save.php**
<?php
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$nume = htmlspecialchars(trim($_POST['nume']));
$add = "INSERT INTO ajax_test (nume) VALUES ('$nume')";
mysql_query($add) or die(mysql_error());
?>
Are you sure the form is submitting? Your button is not an input type="submit" - it's just a button. It won't submit the form on its own.
If the solution of Scott Saunders does not work try this:
instead of
url: "save.php",
try:
url: "save.php?nume=testvalue",
If that also does not work, check if your PHP script reads the input value out of $_GET['nume'] or $_POST
instead of $_REQUEST['nume']
couple of things you could do to help with troubleshooting.
Stick an alert alert("submit"); in after the $('form#submit').submit(function () {
to see if the form is submitting. Also stick one in the success alert("success"); to see if you're getting a callback. This will show you at what stage it's failing and help you liit your search.
You can also use the firebug plugin for firefox to see what's being sent via ajax, if it's working, to see if you've got any values wrong. Think you need to tick Show XMLHttpRequests in Console