onclick get the project id and send it to back.php - php

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/>';
}
?>

Related

How to send values of Select button from Mysqli database and send to second pages?

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.

How to inject javascript code that uses php variables into php page

I created a php page and javascript code that contains some variables from the PHP page, this is a code that inserts php variables into the database using Javascript :
<?php
$id = "Kevin";
$user = "Calvin";
?>
<!-- include jquery library file-->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!-- The ajax/jquery stuff -->
<script type="text/javascript">
function send(e){
if(e.keyCode == 13 && !e.shiftKey){
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
//Get values of the input fields and store it into the variables.
var msg=$("#reply").val();
clear();
//here you start PHP->>
//here we put the PHP Variables ^^^^^^^^^///\\\
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('full.php', {msgg: msg, from: <?php echo json_encode($id); ?>, to: <?php echo json_encode($user); ?>},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(200);
});
function clear() {
$("#myre :input").each( function() {
$(this) .val('');
});
}
});
}
}
</script>
and in the full.php page
<?php
mysql_connect("localhost","root","");
mysql_select_db("db");
$to=mysql_real_escape_string($_POST['to']);
$from=mysql_real_escape_string($_POST['from']);
$msg=mysql_real_escape_string($_POST['msgg']);
$to = mysql_real_escape_string($to);
$from = mysql_real_escape_string($from);
$msg = mysql_real_escape_string($msg);
if(empty($msg)){
exit();
}
$query=mysql_query("INSERT INTO `message`(`user`,`who`,`message`) VALUES ('$to','$from','$msg')");
if($query){
echo "Perfect!";
}else{
echo "Failed!!";
?>
so is there any way to put the Javascript code into another page and inject it using ajax?
Assign PHP variable's value to java script variable :
<script type="text/javascript">
var json{
"id":<?php echo $id;?>,
"user" : "<?php echo $user;?>"
};
</script>
Change this line from your code :
$.post('full.php', {msgg: msg, from: json.id, to: json.user}
Now you'll have separate js file like:
function send(e){
if(e.keyCode == 13 && !e.shiftKey){
$(document).ready(function(){
//Get the input data using the post method when Push into mysql is clicked .. we pull it using the id fields of ID, Name and Email respectively...
//Get values of the input fields and store it into the variables.
var msg=$("#reply").val();
clear();
//here you start PHP->>
//here we put the PHP Variables ^^^^^^^^^///\\\
//use the $.post() method to call insert.php file.. this is the ajax request
$.post('full.php', {msgg: msg, from: json.id, to: json.user},
function(data){
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(200);
});
function clear() {
$("#myre :input").each( function() {
$(this) .val('');
});
}
});
}
}
Say this file is myjs.js now include it in php file:
<script type="text/javascript" src="myjs.js" />

Jquery and ajax on button click

I have this submit button without a form..
<input type='submit' id='conx' name='X' value='TEST x'>
Now when the button is clicked i need to execute this code.
$con = fopen("/tmp/myFIFO", "w");
fwrite($con, "XcOn");
close($con);
How can i execute it in jquery and ajax?.
$("#conx").click(function(){
//Execute this code
//$con = fopen("/tmp/myFIFO", "w");
//fwrite($con, "XcOn");
//close($con);
});
Thanks.
Post that to a PHP page with Ajax and execute those ther
$("#conx").click(function(){
$.post("yourPHPPageWithMagicCode.php");
});
Make sure yo have that PHP code in yourPHPPageWithMagicCode.php file.
If you want to show a response after the process is done, you can return something from your PHP page and let the callback of $.post handle it.
In your PHP page after your code,put an echo
echo "successfully finised";
Now change the jquery code to handle the callback
$("#conx").click(function(){
$.post("yourPHPPageWithMagicCode.php",function(repsonse){
alert(response);
});
});
Let's say your PHP file is called write.php. I believe you can do this:
$("#conx").click(function() {
$.ajax({
url: "/write.php"
});
});
All in one file.
test.php
<?php
if ($_POST['cmd'] === 'ajax') {
$con = fopen("/tmp/myFIFO", "w");
fwrite($con, "XcOn");
fclose($con);
exit;
}
?>
<!doctype html>
<head>
<meta charset="utf-8">
<title>meh</title>
</head>
<body>
<input type="submit" id="conx" name="X" value="TEST x">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function(){
$("#conx").bind('click', function(){
$.post("test.php", { cmd: "ajax" } );
});
});
</script>
</body>
</html>
Add something like below inside your click function to call a PHP script:
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "URL/TO/PHP/SCRIPT",true);
xmlhttp.send();
You need a jquery ajax call between the click event block
$("#conx").click(function(){
$.ajax({
url: "phpfile.php",
type: "post",
//data: serializedData,
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
// log a message to the console
alert(response);
}
});
});
put whatever code you want in the phpfile.php file.
You need to load the 'click event' on the document load i.e.:
$(document).ready(function($){
$("#conx").click(function(){ .....
one way is
$("#conx").click(function(){
$.post("PHPFILENAME.PHP",{
whatdo:otherstuff
},function(d){
// return d here
}
})
run your code in the php file.
You could call a javascript function from the button:
<input type='submit' onclick="myFunction()" id='conx' name='X' value='TEST x'>
and have a page load in your function:
function myFunction(){
var loadUrl = "magic.php";
var result = $("#result").load(loadUrl);
}
Then have magic.php run your method:
//Execute this code
//$con = fopen("/tmp/myFIFO", "w");
//fwrite($con, "XcOn");
//close($con);
This is all untested pseudo-code...

Send mysql query with just a click

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

How to merge php-mysql data with jquery to fade data

I'm having a simple select statement using php-mysql and I have this script to change text with another.
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("text2");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<div id=deletesuccess > text1 </div>
Trying to display data from table using php-mysql and jquery above script but it's displaying only the last row the loop is not working
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("<?php echo $row['desc']; ?>");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<?php
}
But couldn't use it with the above PHP code to display data one by one.
You can do this easily by using jQuery ajax.
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
url: 'getData.php',
dataType: 'json',
type: 'POST',
success: function(data) {
$('#deletesuccess').delay(500).fadeOut(function(){
$.each(data,function(key, value){
$('#deletesuccess').html(value);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
}
});
});
</script>
Now in getData.php page you need to do query and echo json_encode data. That means the getData.php file should contain the following code:
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
$json = '';
while($row = mysql_fetch_array($getTextR)){
$json .= $row['desc'];
}
echo json_encode($json);
?>
Attention, you have not a clear difference between php and javascript code execution. The php code will make an echo of that javascript code, and after php has finish execution(on document ready) the javascript code will be executed at istant, so the last echo of javascript will have effect in the execution. try to separate the codes.
The problem is that you overwrite your JavaScript each time the loop runs. Instead you should make it like this:
<script type="text/javascript">
var php_results = '';
</script>
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
php_results += "<?php echo $row['desc']; ?> | ";
</script>
<?php
}
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html(php_results);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
Of course this would have to be cleaned up to make it pretty, but it should work. I added the pipe as a separator between the different descriptions from the database.

Categories