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

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.

Related

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>

Posting data to sql database without reloading page

the problem is that i am unable to insert data in my database without reloading
i have tested it without the note_sql.js and my note_sql.php works fine but there seems to be a problem in my js file if some body could point me in the right direction it would be wonderful
Index.php
<form id="noteform" action="note_sql.php" method="POST">
<input type="text" name="note"></input>
<input id="sub" type="submit" value="Save Note" />
</form>
<span id="result_note"><span>
<script type ="text/javascript" src="jquery/note_sql.js"></script>
note_sql.js
$("#sub").click(function(){
var data = $("#noteform: input").serializeArray();
$.post($("#noteform").attr("action"),data,function(info){$("result_note").html(info); });
clearInput();
});
$("#noteform").submit(function(){
return false;
});
function clearInput(){
$("#noteform :input").each(function(){
$(this).val('');
});
}
Use Jquery Ajax the working code is given below :
please add ID to Note Form Element :
<pre>
<script>
$(document).ready(function () {
$("#sub").click(function () {
var name = $("#note").val();
var message = $("#message").val();
$.ajax({
type: "post",
url: "note_sql.php",
data: "name=" + name,
success: function (data) {
alert(data);
}
});
});
});
</script>
</pre>

Callback message for php form

I just want to know how i can send a "callback" message for "success" or "error".
I really don't know much about jquery/ajax, but, i tried to do this:
I have a basic form with some informations and i sent the informations for a "test.php" with POST method.
My send (not input) have this id: "#send". And here is my JS in the index.html
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
$(".message").load('teste.php');
});
});
And, in my PHP (test.php) have this:
<?php
$name = $_POST['name'];
if($name == "Test")
{
echo "Success!";
}
else{
echo "Error :(";
}
?>
When i click in the button, the message is always:
Notice: Undefined index: name in /Applications/XAMPP/xamppfiles/htdocs/sites/port/public/test.php on line 3
Error :(
Help :'(
This is your new JS:
$(document).ready(function()
{
$("#send").click(function(e) {
e.preventDefault();
var form_data = $("#my_form").serialize();
$.post('teste.php', form_data, function(data){
$(".message").empty().append(data);
});
});
});
This is your new HTML:
<form id="my_form">
<input type="text" name="name" value="" />
<input type="button" id="send" value="Send" />
</form>
The problem is you have not passed name data to your PHP Use My Javascript Code.
Problem in understanding please reply
$(document).ready(function() {
$(document).on('click','#send',function(e)
{
var params={};
params.name="Your Name ";
$.post('test.php',params,function(response)
{
e.preventDefault();
alert(response); //Alert Response
$(".message").html(response); //Load Response in message class div span or anywhere
});
});
});
This is somewhat more complicated by you can use it more generally in your project. just add a new callback function for each of the forms that you want to use.
<form method="POST" action="test.php" id="nameForm">
<input name="name">
<input type="submit">
</form>
<script>
// wrap everything in an anonymous function
// as not to pollute the global namespace
(function($){
// document ready
$(function(){
$('#nameForm').on('submit', {callback: nameFormCallback },submitForm);
});
// specific code to your form
var nameFormCallback = function(data) {
alert(data);
};
// general form submit function
var submitForm = function(event) {
event.preventDefault();
event.stopPropagation();
var data = $(event.target).serialize();
// you could validate your form here
// post the form data to your form action
$.ajax({
url : event.target.action,
type: 'POST',
data: data,
success: function(data){
event.data.callback(data);
}
});
};
}(jQuery));
</script>

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

Pass javascript variable to php with ajax and the result doesn't show anything

This is my code and i want to pass javascript variable with ajax to php when i click submit button then the result doesn't show var_data variable from javascript What code is wrong?
This is edit order one before everybody help me
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<?php
$test = $_GET['var_PHP_data'];
echo $test;
?>
</body>
</html>
and this is source code now
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
this statement if(isset($_GET['var_PHP_data'])) output false and then show Hello World What should i do to do for isset($_GET['var_PHP_data']) is true?
Your solution has PHP issues: you don't check if the data exists, and also, you don't do anything with the result. I've modified the script to do the following:
Check if the var_PHP_data var is set (in PHP, on the server).
If yes, just send a blank text response containing that data.
If no, then draw the form and everything else.
In the form, I've created a #result div.
Ajax response will be shown in this div.
Also make sure that you host the script at localhost and that it is called test.php. To make sure this is resilient, you can change the Ajax URL to
<?php echo $_SERVER['PHP_SELF'];?> to make sure that you'll hit the correct script.
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
Try jQuery Form its this will help to solve many problems.
For you question: try url without domain name, add tags 'form', change event click to submit, add data type
what are the contents of PassVariable.php ? if is the same where you have they jquery bit wont work coz php will print all the page again, if the file is different try
success: function(data) {
alert('databack = '+ data);
}
Try placing your input into a form and attaching the ajax call to the form onsubmit event. The way it happens in the provided happen is when you click in the field, in which case it submits before you can write anything really.
$(document).ready(function() {
$('#brn').click(function() {
var var_data = "Hello World";
alert("click works");
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { x: var_data },
success: function(data) {
alert(data);
}
});
});
});
change it to this code
then in PassVariable.php put
make button
<input type="button" id="btn" value="click me" />
it should work because it is very basic example. If it doesn't work check your console if there are any JavaScript errors and remove them.

Categories