php variable to ajax function - php

hi im trying to access a php variable in an ajax function but apparently it isnt working...i have used an onClick event to activate the ajax function where i pass my local php variable as an argument parameter...
<?php
$name = $_GET['name'];
?>
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(x){
var nm = x;
var hr = new XMLHttpRequest();
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var vars = "todo="+fn+"&name="+nm;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<?php
$display =' Name of list:;
echo <label for="name"></label>
<input type="text" name="name" id="name">
</p>
<p>Name of item:
<input id="first_name" name="first_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post(' . $name . ');">
</p>
<p>Your list has been succesfully created.</p>
<form name="form1" method="post" action="">
<input type="submit" name="AddItem" id="AddItem" value="Add Items">
</form>
<p><br />
<br />
</p>
<div id="status"></div>
</body>
</html>';
?>
<?php
echo $display;
?>

Echo the var into a hidden span or input an snag it from there when you need it.

It looks like you're sending the request via POST and then trying to access it via GET. Try changing it to:
<?php
$name = $_POST['name'];
?>

Related

Inserting comment to database using ajax

I know this has been mentioned many times in this thread but I still couldn't figure out how to solve my problem. I'm having difficulty on how to send and fetch my data from the comment.php to the insert.php
Here is my code for my comment.php:
(Notice the comments in javascript the method part [there's three of them], I've tried experimenting with them so that I could insert my data to the database but to no avail they didn't work. I'm still learning after all).Could someone help me. I'm still a beginner so I might find it difficult to understand an advance but i'll do my best.
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Comment</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
<link rel="stylesheet" type="text/css" href="bootstrap.min" />
<script type = "text/javascript" >
<!-- method 1-->
//$(document).ready( function() {
// $('#submit').click( function() {
//
// $('#getResponse').html('<img src="bootstrap/images /loading.gif">');
// $.post( 'insert.php', function(sendRequest) {
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"&web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
// $('#getResponse').html(sendRequest);
// });
// });
//});
<!-- -->
<!-- method 2-->
//function sendRequest() (
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.onreadystatechange = function()
// (
// if(xmlhttp.onreadystatechange == 4 && xmlhttp.status == 200)
// (
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
// )
// )
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,true);
// xmlhttp.send();
//)
<!-- -->
<!-- method 3-->
// function sendRequest()
//{
// var xmlhttp = new XMLHttpRequest();
// xmlhttp.open("GET","insert.php?name="+document.getElementbyId("name").value+" &email="+document.getElementbyId("email").value+"& web="+document.getElementbyId("url").value+"& comment="+document.getElementbyId("body").value+,false);
// xmlhttp.send(null);
// document.getElementbyId("getResponse").innerHTML = xmlhttp.responseText;
//}
<!-- -->
</script>
</head>
<body>
<form method = "post" action="">
<div id="main">
<div class="comment" style="display: block;">
<div class="avatar">
<img src="img/default_avatar.gif">
</div>
<div class="name">Avatar</div>
<div class="date" title="Added at 02:24 on 20 Feb 2015">20 Feb 2015</div>
<p>Avatar</p>
</div>
<div id="addCommentContainer">
<p>Add a Comment</p>
<form id="addCommentForm" method="Get" action="">
<div>
<label for="name">Your Name</label>
<input type="text" name="name" id="name">
<label for="email">Your Email</label>
<input type="text" name="email" id="email">
<label for="url">Website (not required)</label>
<input type="text" name="url" id="url">
<label for="body">Comment Body</label>
<textarea name="body" id="body" cols="20" rows="5"> </textarea>
<input type="submit" name="submit" id="submit" value="Submit" >
</div>
</form>
<div id = "getResponse"></div>
</div>
</div>
</form>
</body>
</html>
Here is my code for the insert.php my php file where I perform the insertion of data to my database.
<?php
mysql_connect("localhost","root");
mysql_select_db("comment");
$name = $_GET['name'];
$email = $_GET['email'];
$web = $_GET['web'];
$comment = $_GET['comment'];
mysql_query("INSERT INTO demo (c_name,c_email,c_web,c_comment) VALUES ('$name','$email','$web','$comment')");
echo "Inserted Successfully";
?>
In your comment.php file , use Button,not submit.
And on click event of that button , call jQuery ajax
$('#button_id').click(function(){
//Get values of input fields from DOM structure
var params,name,email,url,body;
name=$("#name").val();
email=$("#email").val();
url=$("#url").val();
body=$("#body").val();
params = {'name':name,'email':email,'web':url,'comment':body};
$.ajax({
url:'insert.php',
data:params,
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});
Update
I dont know whether you used button or submit. So I am specifying for you.
<input type="button" name="submit" id="button_id" value="Submit" >
you can use this to submit the record to insert.php action in the form should be action = "insert.php"
$('form#addCommentForm').on('submit', function(){
$("#response").show();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value ){
$('#response').html('<img src="images/loadingbar.gif"> loading...');
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$(".ajax")[0].reset();
$("#response").hide();
}
});
return false;
});
form the db connection script use this
<?php
$connect_error = 'sorry we\'re experiencing connection problems';
mysql_connect('localhost', 'root', '') or die($connect_error) ;
mysql_select_db('comment') or die($connect_error);
?>
you can also use the form serialize function, its good approach.
$('#addCommentForm').submit(function(form){
$.ajax({
url:'insert.php',
data: $(form).serialize(),
success:function(){
alert("hello , your comment is added successfully , now play soccer :) !!");
}
});
});

How to send data from one page to another without page load?

I have two page one customform.php and another is preview.php.
I want to send some data which are values of some text-fields on customform.php using jquery post method. But I dont want the page to load. So I have used some JQuery code for this work. But now working for me.
the html code on customform.php is:
<form action="#" method="post">
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="button" value="preview" id="preview">
</form>
The jQuery code on customform.php is:
$('#previewph').click( function() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
alert("Mail: " + v1 + " Message: " + v2);
$.post( "http://www.lexiconofsustainability.com/lex_tmp2/preview/" ,{ name : v1 , title :v2 });
window.open("http://www.lexiconofsustainability.com/lex_tmp2/preview/", '_blank');
});
And on the preview.php I want to retrieve value form post method and echo them.
<?php
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
?>
Simply Try this
<form action="#" method="post" >
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="submit" value="preview" id="preview" onclick="senddata()" >
</form>
<div id="message"></div>
function senddata() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
$.post("http://www.lexiconofsustainability.com/lex_tmp2/preview/", { name : v1 , title :v2 },
function(data) {
document.getElementById("message").innerHTML = data;
});
}
You can use AJAX for this..
The jQuery code on customform.php should be:
$('#previewph').click( function() {
var v1 = $('#text1').val();
var v2 = $('#text2').val();
$.post("preview.php", {name:v1, title:v2}, function(data)
{
alert(data);
});
});
preview.php
<?php
if(isset($_POST['name'])&&($_POST['title']))
{
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
}
?>

Form gets re-rendered after submit Ajax

<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "index2.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Your First Name: <input id="first_name" name="first_name" type="text" />
<br /><br />
Your Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();">
<br /><br />
<div id="status"></div>
</body>
</html>
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
The code above works and submits the data and gets the result, along with the result it renders the form again. Image --> http://oi47.tinypic.com/1bt02.jpg
How to fix it?
Thanks in advance.
Don't include the form in the response you send to the Ajax request.

using ajax to display a message when data get inserted in to the data base

I've searched through the StackOverFlow but didn't found what I was looking for so I'm posting what I want to ask you.
I'm a new comer to the world of PHP any how I've started to write a script which will get data and display on a WAP interface that part is ok my issue is in the part I'm writing for the data insert page or the Admin page. I've got every thing working but I love to know how to use AJAX to display a message with out going to the particular processing page.
The Process Page,
<?php
include ('connect.php');
$data = ("SELECT * FROM poiinfo");
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
/*$poiImg = $_REQUEST['Image']; */
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
?>
Can I know how to use AJAX to get an message.
I've used the code examples that you guys gave me but I'm still not getting the job done please can you help me to find what I'm doing wrong.
My Form,
<!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" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#save_data").click(function(){
var name = document.getElementById("Name");
var desc = document.getElementById("Descrip");
var con = document.getElementById("ConInfo");
var dataString = 'Name='+name'&Descrip='+desc'&ConInfo='con;
$.ajax({
type:'POST',
data:dataString,
url:'addpoipro.php',
success:function(data){
if(data="Data inserted") {
alert("Insertion Success");
} else {
alert("Not Inserted");
}
}
});
});
});
</script>
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image :</label>
<!--<input type="file" name="Image" id="Image" /> -->
</p>
<p> </p>
<p>
<div align="center">
<input type="button" name="Submit" id="save_data" value="Submit" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
Above4 is my form and the process.php is before that please help me thank you.
Example using jQuery's $.ajax:
$.ajax({
url: "process.php",
type: "POST",
data : { Name : 'John', Descrip : 'some description..', ConInfo : 'some info...' },
success : function(data){
if(data == "Data inserted")
{
console.log("Success!");
}
else
{
console.log("fail!");
}
}
});
Here is another solution without using jquery.
index.html
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<!-- reply from process.php is shown in this div -->
<div id=message></div>
<!-- click to send data -->
click here
</body>
</html>
test.js
function sendData(Name,description,info) {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function()
{
var ajaxDisplay = document.getElementById('message');
if(ajaxRequest.readyState == 4)
{ ajaxDisplay.innerHTML = ajaxRequest.responseText;}
else { document.getElementById('message').innerHTML="<span style=\"color:green;\">Loading..</span>"; }
}
var url="process.php?name="+Name+"&Descrip="+description+"&ConInfo="+info;
ajaxRequest.open("POST", url, true);
ajaxRequest.send(null);
}
You can do it like this also.
You HTML
<label>Name</labe><input type="text" id="name" name="full_name" value="" />
<label>Address</labe><input type="text" id="addr" name="addr" value="" />
<input type="button" name="save" id="save_data" value="Save" />
in the head section after adding jQuery do something like this
<script>
$(document).ready(function(){
$("#save_data").click(function(){
var name = $("#name").val();
var addr = $("#addr").val();
var dataString = 'name='+name'&address='+address;
$.ajax({
type:'POST',
data:dataString,
url:'process.php',
success:function(data){
if(data="inserted") {
alert("Insertion Success");
} else {
alert("Not Inserted");
}
}
});
});
});
</script>
"process.php page"
$name = $_POST['name'];
$address = $_POST['address'];
// DO YOUR INSERT QUERY
$insert_query = mysql_query("INSERT QUERY GOES HERE");
if(// CHECK FOR AFFECTED ROWS) {
echo "inserted";
} else {
echo "not";
}

Why is this POST not being sent w/ Jquery?

I have a form that I am trying to submit with POST. When I go to catch the POST vars, nothing is being sent.
<?php require_once("../includes/initialize.php"); ?>
<html><head>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script src="jquery-1.8.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('form').submit(function (e) {
var $this = $(this);
e.preventDefault(); // This prevents the form submission.
$("#messageSent").show("slow");
$this.closest('#contactForm').slideUp('slow', function () {
$this[0].submit(); // Actual submission.
});
});
$("#contactLink").click(function(){
if ($("#contactForm").is(":hidden")){
$("#contactForm").slideDown("slow");
}else{
$("#contactForm").slideUp("slow");
}
});
});
</script></head><body>
<?php
if(isset($_POST['signupSubmit'])){
echo "Post is set";
echo $_POST['name'], "<br />";
echo $_POST['email'];
}else{
echo "post is not set";
}
if(isset($_POST['signupSubmit'])){
$signup = new Signup();
$signup->name = $_POST['name'];
$signup->email = $_POST['email'];
if($signup->save()) {
$session->message("We will contact you with details.");
} else {
$session->message("Failed", $signup->errors);
}
}
echo output_message($message);
?>
<div id="contactFormContainer">
<div id="contactLink"></div>
<div id="contactForm">
<form action="test2.php" enctype="multipart/form-data" method="post">
<fieldset>
<label for="name">Name *</label>
<input id="name" type="text" name="name" />
<label for="email">Email address *</label>
<input id="email" type="text" name="email" />
<input id="sendMail" type="submit" name="signupSubmit" />
<span id="messageSent"></span>
</fieldset>
</form>
</div>
</div>
</body>
</html>
Any help would be appreciated!
That's because when you submit the form with $this[0].submit(); it still runs the submit handler which unconditionally prevents the form from submitting. Set some flag so the form will submit after the animation.
$('form').submit(function (e) {
var $this = $(this);
if (!$this.data('afteranimation')){
$("#messageSent").show("slow");
$this.closest('#contactForm').slideUp('slow', function () {
$this.data('afteranimation', true);
$this.submit(); // Actual submission.
});
e.preventDefault(); // This prevents the form submission.
}
});

Categories