I have three pages :
1)index.php (get results from select.php and put them into div#result )
2)select.php (loops into MySQL's table)
3)delete.php (gets user_id as a parameter and deletes it from MySQL's table).
My goal is : After user clicks on delete! to show updated results (after changes/deletes)
from MySQL's table
my problem is I could not know how to tell jQuery: listen process delete.php?id=123 & then
reload select.php while staying in index.php without redirecting to delete.php
so user actually does not see what happens or does not see that he's being redirected to
another page.
index.php
<html>
<title>a</title>
<head>
<script type="text/javascript" src="jquery-1.8.0.js"></script>
<script type="text/javascript">
$(function() {
$('#result').load('select.php');
});
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>
select.php
<?php
$con = mysql_connect("localhost","root","123");
if (!$con) { die('Could not connect: '); }
mysql_select_db("test", $con);
$result = mysql_query("select * from users");
while($rs3 = mysql_fetch_array($result)) {
echo $rs3["user_email"]." ".$rs3["user_name"]." ";
echo "Delete";
echo "<br />";
}
?>
delete.php
<?php
$con = mysql_connect("localhost","root","123");
if (!$con) { die('Could not connect: '); }
mysql_select_db("test", $con);
$id = mysql_escape_string($_GET["id"]);
$delete = "delete from users where user_id='{$id}'";
#mysql_query($delete);
?>
thank you.
Create not links, but AJAX query for delete. Make JQuery call for links. For example:
<script type="text/javascript">
$(function() {
function refreshContent(){
$('#result').load('select.php');
}
$('#result').on('click','a',function(event){
// prevent going by link `href`
event.preventDefault();
// get deleting row id
var ids = $(this).data('ids');
// make AJAX call for delete
$.get("delete.php", { id: ids},function(data){
// on success - refresh tcontent
refreshContent();
});
return false;
});
// making content load on start
$(document).ready(function(){
refreshContent();
});
});
</script>
Also u must add ids in <a>. In this line:
echo "<a href='delete.php?id=".$rs3[user_id]."' data-ids='".$rs3[user_id]."'>Delete</a>";
Related
I'm having trouble inserting my query into the database after the program checks the username availability on blur using ajax to check if the username is available for register or not. After it checks the username availability, it always insert some empty queries in my database.
Here is the sample output for more details:
But the problem is when it displays username available it will automatically inserts an empty query into the database.
This will insert into the database after it checks the availability of the user:
I want the insert query to be inserted when the user submits or when he/she clicks the register button. The availability of the username is for checking only. Is there a problem with my code?
Here is the code:
Sample.php FILE
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<input type="text" placeholder="Username" id="username" name="username" class="form-control" >
<span id="availability" style="color:green;"></span>
<input class="form-control" placeholder="First Name" name="firstname" type="text" >
<input type="submit" id="signup" name="signupsubmit" class="btn btn-info form-control" value="Register">
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
//Check Username availability
$(document).ready(function()
{
$('#username').blur(function()
{
var username = $(this).val();
$.ajax({
url:"SampleProcess.php",
method:"POST",
data:{username:username},
dataType:"text",
success:function(html)
{
$('#availability').html(html);
}
})
});
});
</script>
</html>
I use ajax for checking the username availability inside the script here:
<script>
//Check Username availability
$(document).ready(function()
{
$('#username').blur(function()
{
var username = $(this).val();
$.ajax({
url:"SampleProcess.php",
method:"POST",
data:{username:username},
dataType:"text",
success:function(html)
{
$('#availability').html(html);
}
})
});
});
</script>
The process file for checking username and inserting a query.
SampleProcess.php FILE
<?php
//This is an external file DBController for creating a connection to DB
require_once("DBController.php");
//DBHandler handles the DBController class
$DBHandler = new DBController();
//Call the function mainConnect()
$connect = $DBHandler->mainConnect();
//Check Username Availability
if(isset($_POST["username"]))
{
$sql = "SELECT * FROM tablereminders WHERE username ='".$_POST["username"]."'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0 )
{
echo"<span class=\"text-danger\">Username not available</span>";
echo'<script>document.getElementById("username").focus();</script>';
}
else
{
//In this else condition the query will be inserted in the
//database after the user clicks the register button, but it will insert right
//after the program check the availability
echo"<span class=\"text-success\">Username available</span>";
//Problem inserting my query here
$Username = isset($_POST['username']);
$FirstName = isset($_POST['firstname']);
//Query Insert into tablereminders
$query = mysqli_query($connect, "INSERT INTO `tablereminders`(`username` , `firstname`)
VALUES ('$Username' , '$FirstName')");
if($connect->query($query) == TRUE)
{
echo "<script type='text/javascript'>alert('New record created successfully');</script> ";
echo "<script>setTimeout(\"location.href = 'LoginReminder.php'\", 0)</script>";
}
}
}
?>
In the else condition after checking mysqli_num_rows I put my insert query there to perform when the user clicks the register buton. Is there a problem with my if-else condition or is it about the AJAX function inside the Sample.php file, Should I use GET or POST method? Either way I tried it but it doesn't correct my problem here. Please help.
Try this ;)
There are two things
Check username availability.
Submit the form and create a record.
1. Check username availability.
For this, you have done all the code you need to modify code like this:
<?php
//This is an external file DBController for creating a connection to DB
require_once("DBController.php");
//DBHandler handles the DBController class
$DBHandler = new DBController();
//Call the function mainConnect()
$connect = $DBHandler->mainConnect();
//Check Username Availability
if(isset($_POST["username"])){
$sql = "SELECT * FROM tablereminders WHERE username ='" . $_POST["username"] . "'";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
echo '<span class="text-danger">Username not available</span>';
echo '<script>document.getElementById("username").focus();</script>';
}else{
echo '<span class="text-success">Username available</span>';
}
}
2. Submit the form and create a record.
Now create new ajax call to some other file to insert record which submits form data on some button click event.
This you can do same you done in case of username availability.
Code sample to insert record:
$Username = isset($_POST['username']);
$FirstName = isset($_POST['firstname']);
//Query Insert into tablereminders
$query = mysqli_query($connect, "INSERT INTO `tablereminders`(`username` , `firstname`)
VALUES ('$Username' , '$FirstName')");
if($connect->query($query) == TRUE){
echo '<script type="text/javascript">alert("New record created successfully");</script>';
echo '<script>setTimeout(function(){ location.href = "LoginReminder.php"}, 0);</script>';
}
Remember 2 things before inserting new record in database:
Validate user data.
Escape user data may be with this function mysqli_real_escape_string OR you can use prepared statement and bind params.
I'm inserting radio checked data values into mysql db with php/jquery and ajax while inserting values i'm getting internal server 500 error...
Any help is appreciated Thanks!
Html Code
<div>
<input class="radio_div_clicked" value="<?php echo $row['name'];?> name="radio_section" id="<?php echo $row['id'];?>"/>
<p><?php echo $row['name'];?></p>
<button id="add_feed">Add</button>
</div>
JQUERY CODE
<script type="text/javascript">
$('body').delegate('#add_feed','click',function(){
var radio_div_clicked = $('input:radio[name=radio_section]:checked').val();
$.ajax({
type:"POST",
url:"index.php",
cache: false,
data:{
insert_section:1,
radio_div_clicked:radio_div_clicked
},
success:function(data)
{
alert('Successfully Inserted Into Table');
}
});
}
});
</script>
PHP code
<?php
$con = #mysql_connect('localhost','root','') or die('failed to connect server');
$db = mysql_select_db('demo',$con) or die('failed to select db');
if(isset($_POST['insert_section']))
{
$radio_div_clicked = mysql_real_escape_string($_POST['radio_div_clicked']);
$sql = mysql_query("insert into test(name) values($radio_div_clicked)";
if($sql)
{
echo "Successfully Inserted Into Table";
}
else
{
echo "Failed To Insert Value Into Table"
}
}
?>
<?php
mysql_close ($con);
?>
Mysql query values($radio_div_clicked)"; did't closed properly, should be
$sql = mysql_query("insert into test(name) values('".$radio_div_clicked."')");
If you're using chrome, click on network tab, and click the requested link. Then, again click on preview or response header. Usually the details errors showing up there.
I have the following scripts. The user will pass a numerical value e.g. 123 as a parameter in the URL, and the app will load/fetch that value from MySQL and show it in the textarea.
E.g., entering, "example.com/index.php?id=123" in the URL will pull the 123rd record from the database and show it in the textarea. Everything seems to be working, but I want to show the last row/id of the "source" table when the form is submitted. So, instead of showing "Saved!" in the pop-up, it should show something like "124" (or, the last updated row/number).
index.php:
<?php
include('connect-db.php');
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT content FROM source WHERE id=$id") or die(mysqli_error());
$row = mysql_fetch_array($result);
if($row)
{
$submit_date = date("Ymd");
$content = $row['content'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
//
// show the last id here!
//
function(data){ alert("Saved!"); }
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
//
// Show the variable (last_id) value in the JavaScript above!
//
$last_id = mysql_insert_id();
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
connect-db:
<?php
$server = 'localhost';
$user = 'domdom';
$pass = 'password#123';
$db = 'domdom';
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
?>
Please note that I do not need any advice on PDO or MySQLi, that is not important at this time. However, any suggestions on improving the security/SQL query etc. are welcome. Thanks.
I will try to answer in 2 parts:
[1] PHP side: in the "isset($_GET['id'])" section, just return the content of the text area you want to fill out. Say, in your DB, 123 -> 'Friday'. Just return the String 'Friday'.
[2] Client side: Do not "submit" the form. Call a JS function, and in there, create an XmlHttpRequest, and send the request to the server as an AJAX request. When you get the return value, examine it and populate your HTML textarea.
If you think this method is suitable for you and you need more details, let me know. I do this in many of my sites.
I have the following code. The $last_id is always showing zero. I do have a column in the "source" table that has auto-increment id. What is the problem with this code?
index.php:
<?php
// connect to the database
include('connect-db.php');
$last_id = mysql_insert_id($connection);
$content = "Please type your content here!";
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
function(data){
alert("Your ID: <?php echo $last_id;?>");
}
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
connect-db:
<?php
$server = 'localhost';
$user = 'mumbo';
$pass = 'mumbo123';
$db = 'jumbo';
$connection = mysql_connect($server, $user, $pass)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());
?>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
try this as submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
echo mysql_insert_id();
}
?>
and in the javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
function(data){
alert("Your ID: " + data);
}
);
return false;
});
});
</script>
This line is computed when the original page loads:
alert("Your ID: <?php echo $last_id;?>");
So it's effectively:
alert("Your ID: 0");
Since all you've done at that point is connect, there is no insert id. I'm not familiar with jquery, but presumably the data parameter to your callback should contain data about the response from submit.php. You need to make submit.php return the ID, then get that data through whatever means in jquery, and display it.
Edit: actually, it looks like what you're doing can't really do what I said, anyhow.
http://api.jquery.com/submit/
You're setting up a handler which is run whenever the form is submitted - however, this is before the submit actually happens, so you can't actually get the ID there. Your options are to use something like XmlHttpRequest to make an asynchronous call, or have this popup on the submit.php page.
First of all do not use mysql, use mysqli or pdo, mysql is a deprecated system and should not be used. It is not secure and can be hacked easily.
Second, mysql_insert_id only works if you call it directly after the insert...
AKA
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
$last_id = mysql_insert_id();
echo $last_id
mysql_close($connection);
then your jquery must say
alert("Your ID: "+data);
The function data that is returned is whatever you echo from your script. Jquery retrieves it in whatever callback variable you set (data) and then you can use it.
I have a php file which connects to a MySql db and read the last entry from a specific table. What I am trying to do, is to display(echo) the last entry from the table using a JavaScript popup box into the external html file
Below I have the code for the PHP file (which is working fine) and the html one but unfortunately I can't figure out how to pass the PHP variable to JavaScript function.
Many thanks in advance.
The php file would be this one:
<?php
// 1. Create a database connection
$connection = mysql_connect("localhost","root","password");
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
// 2. Select database to use
$db_select = mysql_select_db("manage_projects",$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
// 3. Perform database query
$result = mysql_query("SELECT survey_desc FROM subjects ORDER BY id DESC LIMIT 0,1", $connection);
if (!$result) {
die("Database query failed: " . mysql_error());
}
// 4. Use returned data
while ($row = mysql_fetch_array($result)) {
echo $row["survey_desc"]."<br />";
}
// 4.1 Alternative way to use returned data
/* $row = mysql_fetch_array($result);
echo $row["survey_desc"]."<br />";
*/
// 5. Close connection
mysql_close($connection);
?>
The html file:
<html>
<head>
<script type="text/javascript src="myscript.php"">
//if clicked Yes open new page if Cancel stay on the page
function popup(){
var r=confirm("echo the php query here");
if (r==true)
{
window.location = "http://example.com";
}
}
</script>
</head>
<body onload ="popup()">
</body>
</html>
You can echo into JavaScript:
var r=confirm("<?php echo $relevant_variable; ?>");
Also it's not recommended to use die() in a production environment.
<head>
<script type="text/javascript">
function popup(){
var xhr=null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
if(xhr.readyState == 4){ alert_ajax(xhr); }
}
xhr.open("GET", "myscript.php", true);
xhr.send(null);
}
function alert_ajax(xhr){
var docAjax= xhr.responseText;
r=confirm(docAjax);
if (r==true)
{
window.location = "http://example.com";
}
}
</script>
</head>
Use PHP's json_encode()-function:
var r = confirm(<?php echo json_encode("the php query here"); ?>);
It escapes for you and always produces valid JavaScript, since JSON is a subset of the JavaScript syntax.
<?php
// Your php code;
$myVar="your value that you want to pass to js";
?>
<html>
<head>
<script>
//if clicked Yes open new page if Cancel stay on the page
function popup(){
var mvar = '<?php echo $myVar ;?>';
var r=confirm(mvar);
if (r==true)
{
window.location = "http://example.com";
}
}
</script>
</head>
<body onload ="popup()">
</body>
</html>
Just combine your both files in one php file.