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});
});
Related
This is what my PHP file looks like and I want to run this on a click of a button
<?php
include("connection.php");
include("formulaYT.php");
$query = "UPDATE `songs` SET `views` = '".mysqli_real_escape_string($link, $_POST['content'])."' WHERE link = '".currentViews($soHigh)."'";
mysqli_query($link, $query);
?>
Following is my ajax code. What should I put in ajax 'data:'.
<body>
<button class="buttonTest">
Test
</button>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<script>
$(".buttonTest").click(function()
{
$.ajax({
method: "POST",
url: "updatedatabase.php",
data: { content: $(".buttonTest").val() }
});
});
</script>
I have tried finding it on other forums but couldn't figure out anything at all
the "data" option is what you send to the php script with the $ _POST function.
If you have nothing to send (as in your case) just don't use the "data" option
try this:
file.html
<button type="button">TEST</button>
<p></p>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){ //the ajax starts only when the button
//identified by "type = button" is clicked
$.ajax({
type: 'POST', //type post (like php function $_POST)
url: 'updatedatabase.php', //your file
success: function(data) { //what to do when the php script it's done
alert(data);
$("p").text(data); //inside the <p></p> it will print
// the echo, in this case "done!"
}
});
});
});
</script>
ATTENTION! because the database queries are not safe, you can do sql injection attacks as they are now.
I suggest you to correct them!
updatedatabase.php
<?php
include("connection.php");
include("formulaYT.php");
$query = "UPDATE `songs` SET `views` =
'".mysqli_real_escape_string($link, $_POST['content'])."' WHERE link =
'".currentViews($soHigh)."'";
mysqli_query($link, $query);
echo "done!" //all it's done
?>
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 display the details of projects in database and and allow admins to them delete them.
Here's what I have so far:
<?php
include 'dbc.php';
$query=mysql_query("select * from pro1");
while($result=mysql_fetch_array($query)){
echo '<span>'.$result['name'].'</span>'.'delet'.'<br/>';
}
?>
<html>
<head>
</head>
<body>
<span>test10</span>delet
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function delete(proid){
//alert(proid);
$.post("back.php",{
proid:proid
},function(data){
alert(data);
});
});//ready func end
</script>
</body>
</html>
I'm getting the proid from db... now I need to send the id with ajax.
The loop output will be something like this:
<span>test10</span>
delete
Explanation
There is missing one closing bracket for the function.
Note: The function must not be wrapped to be executed on load, otherwise it won't be accessible !
Solution
(JSFiddle)
Javascript/jQuery
function delet(proid){
//alert(proid);
$.post("back.php",{
proid:proid
},function(data){
alert(data);
});
} /*This one here */
Move the delet function out of the document.ready wrapper. It can't be accessed because it's out of scope:
// no $(document).ready()
function delet(proid){
$.post("back.php",{
proid:proid
},function(data){
alert(data);
}); // <-- this was missing
}
Perhaps you want like this
JQuery :-
$(document).ready(function(){
function delete(proid)
{
$.ajax({
url: 'back.php',
type: "get",
data:'id='+ proid,
success: function (response) {
alert(data);
}
});
}
});
PHP:-
<?php
include 'dbc.php';
$id=$_GET['id'];
$sql=mysql_query("DELETE FROM pro1 WHERE pro_id='$id'");
if($sql)
echo "Deleted Succesfully<br>";
else
echo "Problem to delete :(<br>";
$query=mysql_query("select * from pro1");
while($result=mysql_fetch_array($query)){
echo '<span>'.$result['name'].'</span>'.'delet'.'<br/>';
}
?>
My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.
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.