Sending form value using ajax, jquery,php - 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);
}
});
});

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");
}
});
});
});

ajax not working .No alert shown after submission

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.

PHP Jquery Ajax POST call, not work

As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>
Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {
You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>

return data json from ajax

First of all I'm sorry if my English isn't totally correct.
I'm learning to use json and I want to try with this simple code, where I insert name and surname and with Ajax I send them to a json struct for then show them in a table.
ajax.php
<form id="iscrizione">
Nome: <input type="text" id="nome" /><br />
Cognome: <input type="text" id="cognome" /></br >
<input type="submit" id="invia" value="ISCRIVITI" />
</form>
<table>
<tr><td>Nome: </td><td><span id="td_nome"></span></td></tr>
<tr><td>Cognome: </td><td><span id="td_cognome"></span></td></tr>
</table>
<script type="text/javascript">
$("#iscrizione").submit(function(){
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("span#td_nome").html(msg.nome);
$("span#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
});
</script>
json.php
<?php
header("Content-Type: application/json", true);
$dati = array( 'nome'=>$_POST['nome'], 'cognome'=>$_POST['cognome'] );
echo json_encode($dati);
?>
Where are the mistakes? Because the outputs are shown for just a second and then they will disappear.
Thank you to everybody.
When you submit the form it will reload all page again, so assigned html visible for short time only.
Use preventDefault() function to overcome this situation.
<script type="text/javascript">
$("#iscrizione").submit(function(event){
event.preventDefault()
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("span#td_nome").html(msg.nome);
$("span#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
});
On submitting form, it will reload page by default. We can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler. Read more about .submit() event.
1.On using returning false after ajax call.
$("#iscrizione").submit(function(){
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
....
....
});
return false; // add return false here
});
2.By using event.preventDefault()
$("#iscrizione").submit(function(event){
event.preventDefault();// use preventDefault() on event
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
....
....
});
});
Either return false or preventDefault() will work, as the other two answers have described. However, it's important to understand that you don't have to submit the form at all, and indeed it isn't best practice to do so. After all, it doesn't make much sense to use HTML to submit the form and then disable the submit behavior in your code. Especially when you don't have to.
AJAX was invented to overcome the problems (such as yours) that result when you reload the page. The point about AJAX is that it gives you the ability to update your page with new data without reloading it.
So, the cleaner way to do what you want is to make your button simply a button, and call your code from the button's click event. Have a look at this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>
Test
</title>
<!--jQuery file-->
<script src="includes/jquery/jquery-2.2.3.js"></script>
<script type="text/javascript">
$(document).ready(function () {
function showMyPHP() {
var nome = $("#nome").val();
var cognome = $("#cognome").val();
$.ajax({
url: "json.php",
type: "POST",
data: {nome: nome, cognome: cognome},
dataType: "json",
success: function(msg){
$("#td_nome").html(msg.nome);
$("#td_cognome").html(msg.cognome);
},
error: function() {
alert ("Chiamata Fallita");
}
});
}
$('#invia').on('click', function(e, ui){
showMyPHP();
});
});
</script>
</head>
<body>
<form id="iscrizione">
Nome: <input type="text" id="nome" /><br />
Cognome: <input type="text" id="cognome" /></br >
<button type="button" id="invia">"ISCRIVITI"</button>
</form>
<table>
<tr><td>Nome: </td><td><span id="td_nome"></span></td></tr>
<tr><td>Cognome: </td><td><span id="td_cognome"></span></td></tr>
</table>
</body>
</html>
You can see that we're not submitting the form at all here. Rather, we're calling the AJAX through the button's click event. You'll see that you get the results you're looking for, without resorting to using HTML to submit the form and then disabling the default submit behavior in code.

Jquery Post + run php file > hide the form > give message

here is my code about jquery post. I can't make it work somehow. I spent hours :( what I miss here?! when I run the code, It loads same page :(
I want it to run the php code under
query.php and hide the contact form
and give "thanks!" message at send
submit button click. (with no page
loading)
appreciate helps!
PHP Form
<form id="commentForm" name="contact" method="post" action="">
<ul id="contact-form">
<li><label>Full Name: *</label><input type="text" name="full_name" class="txt_input required" /></li>
<li><input type="submit" value="Send" id="btnsend" name="btnsend" class="btn_submit" /></li>
</ul>
</form>
SCRIPT
$(function() {
$("#btnsend").click(function() {
var dataString = 'fullname='+ escape(full_name);
$.ajax({
type: "POST",
url: "query.php?act=contact",
data: dataString,
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>")
.fadeIn(1500, function() {$('#contact-form').append("");});
}
});
return false;
});
});
Your problem lies in: var dataString = 'fullname='+ escape(full_name);
Try: var dataString = 'fullname='+ escape(document.contact.full_name.value);
Eg:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#btnsend").click(function() {
var dataString = 'fullname='+ escape(document.contact.full_name.value);
$.ajax( {
type: "POST",
url: "query.php?act=contact",
data: dataString,
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>").fadeIn(1500, function() {
$('#contact-form').append("");
});
}
});
return false;
});
});
</script>
</head>
<body>
<form id="commentForm" name="contact" method="post" action="">
<ul id="contact-form">
<li><label>Full Name: *</label><input type="text" name="full_name" class="txt_input required" /></li>
<li><input type="submit" value="Send" id="btnsend" name="btnsend" class="btn_submit" /></li>
</ul>
</form>
</body>
Make sure query.php exists though else it won't execute the call back function at success.
Also make sure you click the button and not press the ENTER key as that will submit the form normally (you have only defined an event handler for click not keypress)
You can preventDefault on the button click or return false on the form's submit event:
$(function() {
$("#btnsend").click(function(e) {
e.preventDefault();
var full_name = $('input["name=full_name"]').val();
var dataString = 'fullname='+ full_name;
$.ajax({
type: "POST",
url: "query.php?act=contact",
data: dataString,
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>")
.fadeIn(1500, function() {$('#contact-form').append("");});
}
});
});
});
or:
$('#commentForm').submit(function() {
return false;
});
Try:
$(function() {
$("#btnsend").click(function() {
$.ajax({
type: "POST",
url: "query.php?act=contact",
data: { fullname: $('input[name=full_name]').val() },
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>")
.fadeIn(1500, function() {$('#contact-form').append("");});
}
});
return false;
});
});
I think that you have at least 3 problems here. First, you are referencing full_name as if it were a variable. I believe this is causing a javascript error which aborts the function and allows the default action (post) to proceed. Second, you probably need to encode ALL of the form parameters, including act. This is may be causing an invalid URL to be sent and thus the action appears not to have been invoked -- you can check this by looking at the request that is sent with Firefox/Firebug. Third, you are attempting to replace the contents of a list with a paragraph element. This is invalid HTML. I'd replace the entire list with the paragraph (and I don't get what appending an empty string does at the end so I've omitted it).
Note I've changed this to work on the submit event of the form -- so it won't matter how it's submitted. Also allows me a little jQuery niceness in not having to look up the form again.
$('#commentform').submit(function() {
var $this = $(this);
$.ajax({
url: "query.php",
data: { 'act': 'contact', 'full_name', $('input[name="full_name"]').val() },
success: function() {
$('#contact-form').remove();
$this.hide().html("<p>thanks!</p>").fadeIn(1500);
}
});
return false;
}
This is my way to call PHP function directly via jQuery
// in html file
<script language="javascript">
$.post("thisisphp.php",{ func:"true", varbl: 'valu2' },function(data) {
$('.thisdiv #subdiv').html(data);
});
</script>
PHP file thisisphp.php
<?php
// include connection creating file.
require_once("database.php");
$db = & new Database();
function getDateAppointments($varible1, $varible2, $db) {
$q_appointment = "SELECT * FROM `tbl_apoint` WHERE ap_date = '".$varible1."'";
$s_appointment = $db->SelectQuery($q_appointment);
while($r_appointment = mysql_fetch_array($s_appointment))
{
echo '<div id="appoinment">'.$r_appointment['ap_title'].'</div>';
}
}
/* This function for set positions of the day */
switch($_POST['func']) {
case 'true':
getFunc1($_POST['varbl'], 'S0001', $db);
break;
default:
getFunc2($_POST['varbl'], 'S0001', $db);
}
?>
Can this help you?
PS: you can put your hidding and showing form script inside onSucces and onError functions.

Categories