Inserting comment to database using ajax - php

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

Related

Issue with Ajax Contact Form

I am trying to put together a simple contact form with ajax, where users are not redirected to the contact.php file once the submission is done..
There is no errors.. I am always redirected..
Any idea please? Any suggestion is highly appreciated. Thanks!
contact.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<form action="contact.php" method="post" class="ajax">
<div>
<input type="text" name="name" placeholder="Your Name">
</div>
<div>
<input type="email" name="email" placeholder="Your Email">
</div>
<div>
<textarea name="message" placeholder="Your Message"></textarea>
<div>
<input type="submit" value="Send">
</form>
</body>
</html>
contact.php
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
print_r($_POST);
}
?>
main.js
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
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);
}
});
return false;
});
You need to prevent the default form behavior.
$('form.ajax').on('submit', function(evt) {
evt.preventDefault();
You need to ouput json format so header need to be setting and you need to return json value to ajax success so need json_encode($object_or_array_form_php);
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
header("Content-type:application/json");
$_POST['success'] = "You form is sending ...";
echo json_encode($_POST); //this is the "response" param form ajax
}
?>
Hacked! Here's a little bit different way ..
<script>
$(document).ready(function() {
$('form').submit(function (event) {
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var message = $("#mail-message").val();
var submit = $("#mail-submit").val();
$(".form-message").load("contact.php", {
name: name,
email: email,
message: message,
submit: submit
});
});
});
</script>

Post ID on Keyup AJAX/PHP/MYSQL

I have the below code. Currently it submits only the first_name which is exactly what I want and it does that on the fly without the page refreshing.
However I need to parse an ID number along the same ajax request through the hidden id field.
Can anybody suggest any ideas to help me?
Thanks in advance
CODE:
<html>
<head>
<script>
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "my_parse_file.php";
var fn = document.getElementById("first_name").value;
var vars = "firstname="+fn+;
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>
<input type="hidden" name="my_id" value="1234">
First Name: <input id="first_name" name="first_name" type="text" onkeyup="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>
Use jquery
<!DOCTYPE html>
<html>
<head>
<title>TITLE</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function ajax_post(){
var $elementStatus = $('#status');
$elementStatus.html('processing...');
var url = 'my_parse_file.php';
var data = { firstname : $('#first_name').val() };
var success = function(responseText, textStatus, jqXHR) {
if(jqXHR.status != 200)
return;
$elementStatus.html(responseText);
};
$.post(url, data, success);
};
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
<input type="hidden" name="my_id" value="1234">
First Name: <input id="first_name" name="first_name" type="text" onkeyup="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>

AngularJS pass form array to php

I am struggling to get this form to work was wondering if anyone can give me any ideas why! So what I have is an index page with an ng-app=especial. In the DIV main_area_holder goes the ng_view. The Ng-view displays fine and form displays on index page (from localtion app/partials/cust_form.php). What I am struggling to get working is the http request to php file so I can import form data into DB. I know the php code works without ajax (straight post request). If you can help out I would be very grateful.
app.js UPDATED
var especial = angular.module('especial', ['ngRoute']);
especial.config(function($routeProvider) {
$routeProvider.when('/',
{
controller: 'custPage',
templateUrl: 'app/partials/cust_form.tpl.html'
});
});
especial.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(request){
if(typeof(request)!='object'){
return request;
}
var str = [];
for(var k in request){
if(k.charAt(0)=='$'){
delete request[k];
continue;
}
var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
};
$httpProvider.defaults.timeout=10000;
$httpProvider.defaults.headers.post = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
});
especial.controller('custPage', function($scope, $http){
$scope = {};
$scope.custCreUpd = function(){
$http({
method: 'POST',
url: 'app/php/cust_cre_upd.php',
data: $scope.cust,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
console.log("OK", data)
}).error(function(err){"ERR", console.log(err)})
};
});
cust_cre_upd.php
<?php
$post = file_get_contents("php://input");
$values = json_decode($post, true);
$table='customers';
$conn = new PDO('mysql:host=localhost;dbname=displaytrends;charset=utf8', 'displaytrends', 'displaytrends');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Strip array to fields with values
$values=array_filter($values);
//Take array keys from array
$field_keys=array_keys($values);
//Implode for insert fields
$ins_fields=implode(",", $field_keys);
//Implode for insert value fields (values will binded later)
$value_fields=":" . implode(", :", $field_keys);
//Create update fields for each array create value = 'value = :value'.
$update_fields=array_keys($values);
foreach($update_fields as &$val){
$val=$val." = :".$val;
}
$update_fields=implode(", ", $update_fields);
//SQL Query
$insert = "INSERT INTO $table ($ins_fields) VALUES ($value_fields) ON DUPLICATE KEY UPDATE $update_fields";
$query = $conn->prepare($insert);
//Bind each value based on value coming in.
foreach ($values as $key => &$value) {
switch(gettype($value)) {
case 'integer':
case 'double':
$query->bindParam(':' . $key, $value, PDO::PARAM_INT);
break;
default:
$query->bindParam(':' . $key, $value, PDO::PARAM_STR);
}
}
$query->execute();
?>
index.php
<!doctype html>
<html ng-app="especial">
<head>
<meta charset="UTF-8">
<title>Especial - Database</title>
<link rel="stylesheet" href="css/index.css">
<script src="scripts/angular.js"></script>
<script src="scripts/angular-route.js"></script>
<script src="scripts/angular-animate.js"></script>
</head>
<body>
<div class="header">
<img id="logo" src="images/especial-logo.jpg">
<a id="logout" href="logout.php">Logout</a>
<div class="menu"></div>
</div>
<div class="sub_menu"></div>
<div class="main_area">
<div id="main_area_holder" ng-view>
</div>
</div>
<div class="footer"></div>
<script src="app/app.js"></script>
</body>
</html>
cust_form.php
<div ng-controller="custPage">
<div id="form">
<form name="cust_form">
<label>Account No:</label>
<input type="text" ng-model="cust.int_custID" name="cust[int_custID]" id="int_custID"/>
<label>Company:</label>
<input type="text" ng-model="cust.cust_company" name="cust[cust_company]" id="cust_company"/>
<label>Address:</label>
<textarea type="text" rows=5 ng-model="cust.cust_address" name="cust[cust_address]" id="cust_address"></textarea>
<label>Postcode:</label>
<input type="text" ng-model="cust.cust_postcode" name="cust[cust_postcode]" id="cust_postcode"/>
<label>Contact 1:</label>
<input type="text" ng-model="cust.cust_contact_1" name="cust[cust_contact_1]" id="cust_contact_1"/>
<label>Contact 2:</label>
<input type="text" ng-model="cust.cust_contact_2" name="cust[cust_contact_2]" id="cust_contact_2"/>
<label>Telephone:</label>
<input type="text" ng-model="cust.cust_tel" name="cust[cust_tel]" id="cust_tel"/>
<label>Mobile:</label>
<input type="text" ng-model="cust.cust_mob" name="cust[cust_mob]" id="cust_mob"/>
<label>DDI:</label>
<input type="text" ng-model="cust.cust_DDI" name="cust[cust_DDI]" id="cust_DDI"/>
<label>Email:</label>
<input type="email" ng-model="cust.cust_email" name="cust[cust_email]" id="cust_email"/>
<label>Notes:</label>
<textarea type="text" rows=5 colums=1 ng-model="cust.cust_notes" name="cust[cust_notes]" id="cust_notes"></textarea>
<button type="submit" ng-click="custCreUpd()"> Submit </button>
</form>
</div>
</div>
app.js:
var especial = angular.module('especial', ['ngRoute']);
especial.config(function($routeProvider) {
$routeProvider.when('/',
{
controller: 'custPage',
templateUrl: 'app/partials/cust_form.tpl.html'
});
});
especial.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(request){
if(typeof(request)!='object'){
return request;
}
var str = [];
for(var k in request){
if(k.charAt(0)=='$'){
delete request[k];
continue;
}
var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
};
$httpProvider.defaults.timeout=10000;
$httpProvider.defaults.headers.post = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
});
especial.controller('custPage', function($scope, $http){
$scope.cust = {};
$scope.custCreUpd = function(){
$http({
method: 'POST',
url: 'app/php/cust_cre_upd.php',
data: $scope.cust,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data){
console.log(data)
}).error(function(err){
console.log(err)
})
};
});
cust_cre_upd.php
<?php
//print_r($_POST); you can print_r it for understanding
//use $_POST as usual, example $_POST["cust_ID"] means your
$values = $_POST;
$conn = new PDO('mysql:host=localhost;dbname=displaytrends;charset=utf8', 'displaytrends', 'displaytrends');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Strip array to fields with values
$values=array_filter($values);
//Take array keys from array
$field_keys=array_keys($values);
//Implode for insert fields
$ins_fields=implode(",", $field_keys);
//Implode for insert value fields (values will binded later)
$value_fields=":" . implode(", :", $field_keys);
//Create update fields for each array create value = 'value = :value'.
$update_fields=array_keys($values);
foreach($update_fields as &$val){
$val=$val." = :".$val;
}
$update_fields=implode(", ", $update_fields);
//SQL Query
$insert = "INSERT INTO $table ($ins_fields) VALUES ($value_fields) ON DUPLICATE KEY UPDATE $update_fields";
$query = $conn->prepare($insert);
//Bind each value based on value coming in.
foreach ($values as $key => &$value) {
switch(gettype($value)) {
case 'integer':
case 'double':
$query->bindParam(':' . $key, $value, PDO::PARAM_INT);
break;
default:
$query->bindParam(':' . $key, $value, PDO::PARAM_STR);
}
}
$query->execute();
index.php:
<!doctype html>
<html ng-app="especial">
<head>
<meta charset="UTF-8">
<title>Especial - Database</title>
<!-- <link rel="stylesheet" href="css/index.css">-->
<script src="scripts/angular-1.3.8.min.js"></script>
<script src="scripts/angular-route.min.js"></script>
<!-- <script src="scripts/angular-animate.js"></script>-->
</head>
<body>
<div class="header">
<img id="logo" src="images/especial-logo.jpg">
<a id="logout" href="logout.php">Logout</a>
<div class="menu"></div>
</div>
<div class="sub_menu"></div>
<div class="main_area">
<div id="main_area_holder" ng-view>
</div>
</div>
<div class="footer"></div>
<script src="app/app.js"></script>
</body>
</html>
cust_form.php (cust_form.tpl.html):
<div id="form">
<form name="cust_form">
<label>Account No:</label>
<input type="text" ng-model="cust.int_custID" id="int_custID"/>
<label>Company:</label>
<input type="text" ng-model="cust.cust_company" id="cust_company"/>
<label>Address:</label>
<textarea type="text" rows=5 ng-model="cust.cust_address" id="cust_address"></textarea>
<label>Postcode:</label>
<input type="text" ng-model="cust.cust_postcode" id="cust_postcode"/>
<label>Contact 1:</label>
<input type="text" ng-model="cust.cust_contact_1" id="cust_contact_1"/>
<label>Contact 2:</label>
<input type="text" ng-model="cust.cust_contact_2" id="cust_contact_2"/>
<label>Telephone:</label>
<input type="text" ng-model="cust.cust_tel" id="cust_tel"/>
<label>Mobile:</label>
<input type="text" ng-model="cust.cust_mob" id="cust_mob"/>
<label>DDI:</label>
<input type="text" ng-model="cust.cust_DDI" id="cust_DDI"/>
<label>Email:</label>
<input type="email" ng-model="cust.cust_email" id="cust_email"/>
<label>Notes:</label>
<textarea type="text" rows=5 colums=1 ng-model="cust.cust_notes" id="cust_notes"></textarea>
<button type="submit" ng-click="custCreUpd()"> Submit </button>
</form>
</div>
I creat a repository here https://github.com/Danzeer/forJoshCrocker
To debug with script in web browser, you can use chrome's Developer's tools - network (option+command+i in OSX, F12 in window, and chose the network card).When you click submit, you can see request in network card and check http header by clicking the request.
I think you can find answer for "post" here AngularJs $http.post() does not send data
angualr's get works well, but angular's post does not seralize form-data as jquery.
my solution (maybe wrong, according to what I have searched) was rewriting angular's httpProvider:
app.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(request){
if(typeof(request)!='object'){
return request;
}
var str = [];
for(var k in request){
if(k.charAt(0)=='$'){
delete request[k];
continue;
}
var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
};
$httpProvider.defaults.timeout=10000;
$httpProvider.defaults.headers.post = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
});
2 your
ng-click="custCreUpd"
should be
ng-click="custCreUpd()"
3 check the result of below, I'm not familiar with it
$.param($scope.cust)
I have rewrite your code, that seems sending post. You can compare it with yours:
app.js :
var especial = angular.module('especial', ['ngRoute']);
especial.config(function($routeProvider) {
$routeProvider.when('/',
{
controller: 'custPage',
templateUrl: 'app/partials/cust_form.tpl.html'
});
});
especial.config(function($httpProvider) {
$httpProvider.defaults.transformRequest = function(request){
if(typeof(request)!='object'){
return request;
}
var str = [];
for(var k in request){
if(k.charAt(0)=='$'){
delete request[k];
continue;
}
var v='object'==typeof(request[k])?JSON.stringify(request[k]):request[k];
str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
return str.join("&");
};
$httpProvider.defaults.timeout=10000;
$httpProvider.defaults.headers.post = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
});
//when using 1.3.8 version , consider how to write controller with []
especial.controller('custPage', ['$scope', '$http', function($scope, $http){
$scope.cust = {};
//$scope = {}; !!!!
$scope.custCreUpd = function(){ // pay attention of params
$http({
method: 'POST',
url: "app/php/cust_cre_upd.php",
data: $scope.cust,
headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(data){
console.log("OK", data)
}).error(function(err){"ERR", console.log(err)})
};
}]);
index.php:
!doctype html>
<html ng-app="especial">
<head>
<meta charset="UTF-8">
<title>Especial - Database</title>
<script src="js/angular-1.3.8.min.js"></script>
<script src="js/angular-route.min.js"></script>
<!-- <script src="scripts/angular-animate.js"></script>-->
</head>
<body>
<div id="main_area_holder" ng-view>
</div>
<script src="app/app.js"></script>
</body>
</html>
custForm.tpl.html(your cust_form.php):
<!--<div ng-controller="custPage"> !none ng-controller when using ng-route-->
<div id="form">
<form name="cust_form">
<label>Account No:</label>
<input type="text" ng-model="cust.int_custID" name="cust[int_custID]" id="int_custID"/>
<button type="submit" ng-click="custCreUpd()"> Submit </button>
</form>
</div>
naming custForm.tpl.html instead of cust_form.php seems much meaningful) and request of .php will be pass to php executor by apache/nginx while request for html only through apache/nginx. And pay attention to angular cache problem when using ng-route. -- some tools not relavent https://github.com/karlgoldstein/grunt-html2js and https://github.com/angular-ui/bootstrap, enjoy!
Points:
1 definition of controller
2 post of angularjs
3 how to use ng-view with ng-route
4 params-"$scope" of function custCreUpd hide $scope service

Changes to text file with php and ajax-driven form

i have created a simple html form with one field and it post to the server side php and the value of the field is saved to a text file.
This is the parts of the code:
Html:
<form action="videorefresh.php" method="POST">
<input name="videolink" type="text" size="70" />
<input type="submit" name="submit" value="Save Data">
</form>
php:
<?php
$open = fopen("video.txt","w+");
$txt = "video.txt";
if (isset($_POST['videolink'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['videolink'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
here everythink works fine!
I want to drive all this through Ajax so the main html form wont refresh.
so here is the html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="./JS/videolink.js"></script>
</head>
<body>
<div id="mainform">
<div id="form">
<div>
<input name="videolink" type="text" id="videolink" size="70">
<input id="submit" type="button" value="Submit">
</div>
</div>
</div>
</body>
</html>
And here is the js:
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#videolink").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'videolink1='+ videolink ;
if(videolink=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "./videorefresh.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
What i do wrong here and it doesnt work?
Please help
I think you want to do is:
var dataString = '?videolink='+ name;//typo videolink
// or better put an id on the form and use serialize()
// var dataString = $('#myform).serialize();
NOT
var dataString = 'videolink1='+ videolink ;
You have the value of the input in name, videolink is undefined

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

Categories