I am trying to create a feature on my website that automatically updates the database onchange of the textarea below (which is going to be act as a 'post-it note for reminders'). I am new to ajax, and I was wondering if someone can show me a basic example of how I would make an AJAX call to update my database onChange of the textarea below?
<?php
//Create mysql connect variable
$conn = mysql_connect('samplesource.com', 'example', 'pass');
//kill connection if error occurs
if(!$conn){
die('Error: Unable to connect.' . '<br>' . mysql_error());
}
//connect to mysql database
mysql_select_db("mydb", $conn);
session_start();
$userid = $_SESSION['id'];
$results = ("SELECT * FROM notes WHERE userid='$userid'");
?>
<html>
<head>
<title>practice</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".sometext").change(function(){
//make ajax call to update database onChange
});
});
</script>
</head>
<body>
<textarea class="note" style="resize:none; width:300px; height:200px;"> </textarea>
</body>
</html>
First, you'd need to move your database save script into a new file e.g save.php
On your <textarea> i'd add
<textarea onchange="saveChanges(this);"></textarea>
For the javascript save function that's called when a change is made:
function saveChanges(object){
$.ajax({
url: 'save.php',
data: 'content=' + object.value,
cache: false,
error: function(e){
alert(e);
},
success: function(response){
// A response to say if it's updated or not
alert(response);
}
});
}
This is a very quick and dirty way of doing it.
Related
I tried to coding it. I am still getting stuck over it. The main goal was if user select value from mysqli database selected it and send the values to other pages. I know people recommend it use by AJAX. I tried to use it. still not working. I'll put details code below.
Main pages Code(main.php)-
<?php
session_start();
$conn=mysqli_connect('localhost','root','','user');
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$resultset=$conn->query("SELECT name from newtable"); ?>
<!DOCTYPE html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
</head>
<body>
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
click
</center>
<script type="text/javascript">
$(document).ready(function(){
var search='';
$("#tables option:selected").each(function() {
if ($(this).attr('value') !== '') {
search=$(this).attr('value');
}
});
$("a").click(function() {
$.ajax({
method: 'post',
url: 'database1.php',
data: {key:search},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
</body>
</html>
as alert box i am getting value of it but second pages get error that key value doesn't exist. here the second one pages (database1.php) -
<?php
$conn=mysqli_connect('localhost','root','','user');
session_start();
if(!$conn){
die('Please check an Connection.'.mysqli_error());
}
$database=$_POST['key'];
echo'You Selected'.$database.'from table';
$sql = "SELECT * FROM $database";
$result=mysqli_query($conn,$sql);
if($result){
echo'Worked';
}else{
echo'ERROR!';
}
?>
so what the problem occurred?
UPDATED ANSWER
Thanks to #swati which she mentioned that use form tag instead of AJAX (i know its simple answer) still by the way thanks for answer. :)
UPDATED CODE FULL -
<body>
<form action="database1.php" method="GET">
<center>
Select DataBase to Insert it<select name="tables" id="tables">
<?php
while($rows=$resultset->fetch_assoc()){
echo'<option
value='.$rows['name'].'>'.$rows['name'].'</option>';
}
?>
</select>
<input type="submit">
</center>
</form>
</body>
SECOND PAGE(database1.php) CHANGES LITTLE -
$database=$_GET['tables'];
You are calling each loop on page load that will give you the already selected value not the value which is selected by user.Also , this loop is not need as you have to pass only one value .
Your script should look like below :
<script type="text/javascript">
$(document).ready(function() {
//no need to add loop here
var search = '';
$("a").click(function() {
search = $("#tables option:selected").val(); //getting selected value of select-box
$.ajax({
method: 'post',
url: 'database1.php',
data: {
key: search
},
beforeSend: function() {
$('body').css("opacity", "0.3");
},
success: function(response) {
alert(response);
},
complete: function() {
$('body').css("opacity", "1");
}
});
});
});
</script>
Also , as you are using ajax no need to give href="database1.php" to a tag because you are calling this page using ajax .i.e: Your a tag should be like below :
<a>click</a>
And whatever you will echo in php side will be return as response to your ajax .So , your alert inside success function will show you that value.
I'm trying to show MySQL data using Ajax. Unfortunately, I am unable to find the correct way. I was trying to show MySQL data on a select box. When I click on "select category" option then all category will show as dropdown.
here is my HTML code.
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
</head>
<body>
<select id='category'>
</select>
<script src='fetch.js'></script>
</body>
</html>
I have used this JS code to send request. Here is my JS code.
$('#category').onclick(function(){
$.getJSON(
'fetch.php',
function(result){
$('#category').empty();
$.each(result.result, function(){
$('#category').append('<option>'+this['category']+'</option>');
});
}
);
});
I have used this php code to complete ajax request and database connection. Here is my PHP code.
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','ajax');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$category = $_GET['category'];
$sql = "select category from ajaxx where category='$category'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('category'=>$row[0]));
}
echo json_encode(array('result'=>$result));
enter code here
mysqli_close($con);
?>
When you make the AJAX request, it's to this URL:
fetch.php
But then in the server-side code, you try to get a query string value:
$category = $_GET['category'];
You can't get a query string value that you never provided. So when you build your SQL query (which is wide open to SQL injection by the way), there's nothing to get from the database.
If you want to use a query string value, you have to provide one:
$.getJSON(
'fetch.php?category=someValue',
function(result){
//...
}
);
What value you provide or where you get that value is up to you. (Perhaps from $('#category').val()?) But it has to exist before you can use it.
You may have confused two things: (a) initially fetching the HTML code to populate the options of your <select> control, and (b) Catching the selected option and using it to perform another DB query, returning new data.
Please review this modified (untested) code sample:
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
</head>
<body>
<select id='category'>
</select>
<div id="resultDIV"></div>
<script src='fetch.js'></script>
</body>
</html>
javascript/jQuery:
//Run on document ready to populate the dropdown box
$(document).ready(function(){
$.getJSON(function(){
'fetch.php',
function(result){
$('#category').empty();
$.each(result.result, function(){
$('#category').append('<option>'+this['category']+'</option>');
});
}
});
$(document).on('click', '#category', function(){
//run on click to take dropdown value and perform lookup
myCat = $(this).val();
$.ajax({
type: 'post',
url: 'getcategory.php',
data: 'category=' +myCat,
success: function(d){
//if (d.length) alert(d);
$('#resultDIV').html(d);
}
});
});
}); //END document.ready
I have used this php code to complete ajax request and database connection. Here is my PHP code.
<?php
/*** getcategory.php ***/
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','ajax');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$category = $_GET['category'];
$sql = "select category from ajaxx where category='$category'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('category'=>$row[0]));
}
echo json_encode(array('result'=>$result));
enter code here
mysqli_close($con);
?>
Here are some basic, simple AJAX examples to study (the three links at the bottom, but also note the information from the first link). Copy them to your server and make them work - play around with them:
AJAX request callback using jQuery
Your ajax code needs some changes :
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Insert Tutorial</title>
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
function myAjax ()
{ $.ajax( { type : 'POST',
data : { 'category' : $('#txt_cat').val() }, // SEND CATEGORY.
url : 'fetch.php',
success : function ( result )
{ $( '#category' ).empty();
var arr = JSON.parse( result );
var sel = document.getElementById("category");
for ( i = 0; i < arr.length; i++ )
{ var option = document.createElement( "option" );
option.text = arr[ i ];
sel.add( option );
}
},
error : function ( xhr )
{ alert( "error" );
}
}
);
}
</script>
</head>
<body>
Enter category <input type="text" id="txt_cat"/>
<button onclick="myAjax()">Click here to fill select</button>
<select id='category'>
<option> - empty - </option>
</select>
</body>
</html>
fetch.php
<?php
$category = $_POST[ "category" ]; // CATEGORY FROM HTML FILE.
// CONNECT TO DATABASE AND QUERY HERE.
$result = Array( "111","222","333","444" ); // SAMPLE DATA.
echo json_encode( $result );
?>
I have a simple PHP code that retrieves data from the table including image and stores it in a JSON object.
<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$selected = mysql_select_db("req2",$con)
or die("Could not select req2");
$table_first = 'locationtab';
$query=mysql_query("SELECT Id,City,Image FROM $table_first");
while ($row=mysql_fetch_assoc($query)) {
$array=$row;
$array['Image']=base64_encode($row['Image']);
$output[]=$array;
}
echo json_encode($output);
mysql_close($con);
?>
This works perfectly fine and I'm able to view the JSON object using print.
on the client side, I wrote a Javascript+Ajax code to call this PHP file and on success display the data in the JSON object. I dont know what is missing in the below code but I don't seem to get the AJAX part to work at all. PLease so help
<html>
<head>
<script src="file://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$.ajax({
url:"table.php",
dataType:'json',
type:'POST',
success:function(output) {
alert( output.Id );
}
});
});
</script>
</head>
<body>
<p>test</p>
</body>
</html>
output is an array of objects with ids.
You are treating it as a single object with an id.
You need either a for loop, or to grab a specific index.
alert( output[0].Id );
I'm making a mash-up using Google Visualizator Geomap, i want to make a Dynamic selection of filters to change everytime without any "submit" button the informations retrieved from a SQL Query.
Here is my main page source:
<?php
require 'protoext.php'
?>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geomap']});
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Code');
data.addColumn('number', 'Value');
data.addRows([
<?php while($r = mysql_fetch_assoc($res)) {
echo "['$r[COD]', $r[Value]],";
} ?>
]);
var options = {};
options['dataMode'] = 'regions';
options['region'] = 'IT';
var container = document.getElementById('map_canvas');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
};
</script>
The source in the "protoext.php" seems working just fine (no errors on firebug and map output is displayed).
The main problem is with the form that sends "gender" value with POST method to "protoext.php
<form method="post">
<select name="gender" onchange="this.form.submit();">
<option selected>Choose</option>
<option value="total">total</option>
<option value="male">male</option>
<option value="female">female</option>
</select>
</form>
<div id='map_canvas'></div>
</div>
As i said it works, but it keeps refreshing the page every time i select a new value and this is preventing me from adding some new select to the form to improve the filtering of the geomap.
I know that to prevent refreshing i have to use AJAX, and i've tried several ways but it was like nothing were sent to the protoext.php.
Any idea anyone? Thank you in advance for any reply.
EDIT
Since any AJAX call i make doesn't resolve properly i will post the other php file (protoext.php) maybe i've got a conflict between functions or just incompatibility issues.
<?php
$selection=$_POST["gender"];
$dbhost="localhost";
$dbuser="root";
$dbpass="";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn) die ("Error Mysql: ".mysql_error());
$sql= "USE csv_db";
$ok = mysql_query ($sql, $conn);
if(!$ok)
die("imposs. select DB: ".mysql_error());
$sql="SELECT COD, Value
FROM view_codes //that is the view obtained from my database
WHERE `Age` LIKE '15+ years '
AND `Qualification` LIKE 'totale'
AND `Home_Town` LIKE 'totale'
AND `Gender` LIKE '$selection'
AND `Period` LIKE 'T2-2012'";
echo "querySQL: $sql<br>";
$res=mysql_query($sql,$conn);
if (!$res)
die ("Error query" .mysql_error());
?>
EDIT-Update
I've also tried this way but still don't work.
<form method="post">
<select name="gender" onchange="this.form.submit(
function (){
$.ajax({
type: "POST",
url: "protoext.php", //www.gautam.com?id=..&value1=..
success:function(data){
alert("successfully submitted");
}
});
}
);">
What am i doing wrong?
You can use ajax
$.ajax({
type: "POST",
url: "Your url here", //www.gautam.com?id=..&value1=..
success:function(data){
alert("successfully submitted");
}
});
$('form').on('submit', function() {
$.post('http://example.com', $(this).serialize(), function() {
// Done
});
});
In your view file
<script>
$('document').ready(function(){
$.ajax({
type: "POST",
url: "Your url here", //www.gautam.com?id=..&value1=..
success:function(data){
alert("successfully submitted");
}
});
})
</script>
I can send a query to mysql database with following code:
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
My questions is, Is there any way to send a query with just a click on some text.
Let's example: there are a text name Reply. I want if i click this Reply text then mysql database field value (field name: Reply, type: int) will be increase by 1.
Sorry I DON'T KNOW ABOUT JAVASCRIPT/AJAX:(
FINAL UPDATER CODE TO #DEVELOPER:
<html>
<head>
<title>Untitled Document</title>
</head>
<script language="javascript">
$("#mylink").click(function() {
$.ajax({
url: "test.php"
}).done(function() {
$(this).addClass("done");
});
});
</script>
<body>
echo "<a href='#' id='mylink'>Reply</a>";
</body>
</html>
Php page:
<?php
include("database/db.php");
$sql = mysql_query("INSERT INTO wall VALUES('','','','','','','','1');");
?>
You should have this link or button to be clicked wired to an ajax call using jQuery
http://api.jquery.com/jQuery.ajax/
It should call a php page, which contains the query you're looking to run. You can pass in arguments with the ajax call as well, so that your $message and $replyno are set properly before executing.
<script>
$("#mylink").click(function() {
$data = $("#myform").serialize();
$.ajax({
url: "postquery.php",
data: $data
}).done(function() {
$(this).addClass("done");
});
});
</script>
then your php page would look something like this:
<?php
...
$message = mysql_real_escape_string($_REQUEST['message']);
$replyno = mysql_real_escape_string($_REQUEST['replyno']);
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
....
?>
Excaping your incoming strings using "mysql_real_escape_string" is always important to prevent SQL Injection attacks on your database.
Your HTML should look something like this:
<html>
...
<input type="textarea"></input>
Reply
...
</html>
This will cause the previously stated jquery statement to trigger when "Reply" is clicked.
Here is with your updated code. I corrected the link ID and also removed the form serialization data since your test code does not appear to need it. I also added the reference to the jQuery library:
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script language="javascript">
$("#mylink").click(function() {
$.ajax({
url: "test.php"
}).done(function() {
$(this).addClass("done");
});
});
</script>
</head>
<body>
<a href='#' id='mylink'>Reply</a>
</body>
</html>
The problems you're likely seeing are because of your query, not the front end code. Try adding some debug code like this:
<?php
include("database/db.php");
$sql = mysql_query("INSERT INTO wall VALUES('','','','','','','','1');");
if(!$sql)
{
echo mysql_error();
}
?>
Or try checking your servers error logs.
$sql = mysql_query("INSERT INTO wall VALUES('', '$message', '$replyno')");
You have to use jquery and ajax like this:-
<script type="text/javascript">
$j(document).ready(function() {
$j('#reply').click(function(){
jQuery.ajax({
url: "test.php", //Your url detail
type: 'POST' ,
data: ,
success: function(response){
}
});
});
});
</script>
In the file "updat_post.php" write:
If(isset($_GET['visit_post']))
$pdo->query('update posts set counter = counter+1');
In your js/jquery file on document ready write:
$('#mybutton').click(function() {
$.post('update_post.php', {visit_post: true});
});