How to prevent Ajax from loading the unnecessary elements repeatedly? - javascript

I want Ajax to apply only in the div (#usersDiv)
When selector is changed into 'body' it loads the whole page repeatedly. (Cannot type in the box)
but when selector changed as #userDiv, it shows the search box twice in the page. In the first box can be typed, but again second box loads over and over.
PHP file is as follows (test.php)
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function users($connection){
if(!empty($_POST)){
$country = $_POST['userCountry'];
$sql = "SELECT * FROM users WHERE country = '$country' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userName = $row['username'];
$city = $row['city'];
echo '<div><h4>'. $userName. " ". $city. '</h4></div>';
}
} else {
echo "Use search box!";
}
} else {
echo "Use Search Box!";
}
}
?>
<html>
<head><script src = "jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON("http://freegeoip.net/json/", function(data) {
var country = data.country_name;
$.ajax({
method:"POST",
url:"test.php",
data:{userCountry:country},
success:function(result){
$('#usersDiv').html(result);
}
});
});
});
</script>
</head>
<body>
<form name = "searchForm" action = "search.php" method = "POST">
<input type = "text" name = "searchPlace" required />
<input type = "submit" value = "Search"/>
</form>
<div id = "usersDiv"> <?php users($connection); ?> </div>
</body>
<html/>

I have altered your code to wrap your PHP function within an if($_POST) to prevent the entire page loading
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
if($_POST){ // Check if form has been submitted
$country = $_POST['userCountry'];
$sql = "SELECT * FROM users WHERE country = '$country' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userName = $row['username'];
$city = $row['city'];
echo '<div><h4>'. $userName. " ". $city. '</h4></div>';
}
} else {
echo "Use search box!";
}
}else{ // If it hasn't then show the search form
?>
<html>
<head><script src = "jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#searchForm").on("submit",function(e){ // Check for form submission
$.getJSON("http://freegeoip.net/json/", function(data) {
var country = data.country_name;
$.ajax({
method:"POST",
url:"test.php",
data:{userCountry:country},
success:function(result){
$('#usersDiv').html(result);
}
});
});
});
});
</script>
</head>
<body>
<form name = "searchForm" action = "search.php" method = "POST" id="searchForm">
<input type = "text" name = "searchPlace" required />
<input type = "submit" value = "Search"/>
</form>
<div id = "usersDiv"></div>
</body>
<html/>
<?php } ?>
As Alexander suggests, read up on SQL Injection
How can I prevent SQL injection

Related

PHP AJAX Delete Record - deletion only works 1 time

I am deleting records with ajax and php. When I click the button it erases the record but when I click to delete another record it does nothing. What am I doing wrong?
HTML
<form id="prop_remove">
<input type="hidden" name="id" id="last_id" value="<?php echo $id; ?>">
<input type="hidden" name="user" id="last_user" value="<?php echo $user; ?>">
<input type="button" name="submit" id="last_prop" class="button fullwidth margin-top-5" value="Delete">
</form>
AJAX
<script>
$(document).ready(function() {
$('#last_prop').click(function() {
var id = $('#last_id').val();
var user = $('#last_user').val();
$.ajax({
url: "delete.php",
method: "POST",
data: {
ilan_id: id,
ilan_user: user
},
success: function(response) {
if (response == 1) {
$('#last_prop').closest('tr').css('background', 'tomato');
$('#last_prop').closest('tr').fadeOut(800, function() {
$(this).remove();
});
} else {
alert('Invalid id');
}
}
});
});
});
</script>
PHP
<?php
require_once 'config.php';
$id = $_POST['ilan_id'];
$user = $_POST['ilan_user'];
$checkRecord = "SELECT * FROM last_tbl WHERE id = '$id' AND user = '$user'";
$check_result = mysqli_query($conn, $checkRecord);
$totalrows = mysqli_num_rows($check_result);
if($totalrows > 0){
$delete_sql = "DELETE FROM last_tbl WHERE id = '$id' AND user = '$user';";
$delete_result = mysqli_query($conn, $delete_sql);
echo 1;
exit;
}
?>
Your problem is that you're overwriting the HTML element IDs. You can remove your forms and use a single button instead, and pass data through the data attribute of the buttons.
Replace your form by a single button
<button class="button fullwidth margin-top-5 last_prop" data-last-id="<?= $id; ?>" data-last-user="<?= $user; ?>">Delete</button>
Then adapt your jQuery to use the class last_prop instead of the ID, and fetch the values from the data attributes we set above.
<script>
$(document).ready(function () {
$('.last_prop').click(function () {
var id = $(this).data('last-id');
var user = $(this).data('last-user');
$.ajax({
url:"delete.php",
method: "POST",
data: {ilan_id: id, ilan_user: user},
success:function(response){
if (response == 1 ){
$('#last_prop').closest('tr').css('background','tomato');
$('#last_prop').closest('tr').fadeOut(800,function(){
$(this).remove();
});
} else {
alert('Invalid id');
}
}
});
});
});
</script>
Also, your query can be reduced to one (you don't need that SELECT), and should be with a prepared statement.
<?php
require_once 'config.php';
$id = $_POST['ilan_id'];
$user = $_POST['ilan_user'];
$sql = "DELETE FROM last_tbl WHERE id = ? AND user = ?;";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $id, $user);
$stmt->execute();
if ($stmt->affected_rows) {
// rows were deleted
echo 1;
}
$stmt->close();

autocomplete using php and html

I want to do text autocomplete using php and html..
i have tried the below code
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj = array_unique($dna);
print_r(array_values($jj));
?>
result is
my html
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/
themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4
/jquery-ui.js">
</script>
</head>
<body>
<form name="vinform" method="get"> <input type="text" name="editor" autocomplete="on"> <input type="submit" value="Show" id="display"> </form>
<div id="div1"></div>
<script type="text/javascript">
$(function() {
$('#div1').autocomplete({
source: "auto.php"
});
});
</script>
</body>
it doesn't show the words from mysql when i type some word in the text field ..i have to show the related words from mysql based on the text field input,when i type a character in the text field..can anyone help me to solve the issue in my code?
tried with Ajax
var se = null;
$(function () {
var minlength = 1;
$("#editor").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (se != null)
se.abort();
se = $.ajax({
type: "GET",
url: "auto.php",
data: value,
dataType: "text",
success: function(msg){
if (value==$(that).val()) {
}
}
});
}
});
});
php
<?php
if(isset($_GET['editor']))
{
$con=mysqli_connect("localhost","root","admin321","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql = "select value from fin where value LIKE '%".$name."'";
$result = mysqli_query($connection, $sql) or
die("Error " . mysqli_error($connection));
$dna = array();
while($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj=array_unique($dna);
print_r ( $jj);
}
?>
no autocomplete action
With option 1 (Jquery UI autocomplete) and try something like that
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
echo json_encode($dna);
?>
Jquery UI autocomplete state about source option
String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.
You can use AJAX and Jquery..in html code call the function on keyup event and send data using ajax request after that get data from database using LIKE query and display it..
in input add id="editor"
<input type="text" id="editor" name="editor" autocomplete="on">

How to pass a value to the same page when a form submitted? Using Ajax

Basically, the form has to send data to my database and my database informations should be shown at the same page when user submit the form without refreshing the page. I did something wrong and couldn't find how to fix this. And looked at all the questions but couldn't figure it out. Thanks for the help.
<div id="tweetSpace">
<form id="formTweet" method="post" >
<textarea id="areaTweet" name="message" rows="2" cols="120" placeholder="Write your tweet here..."></textarea>
<br>
<input id="sendTweet" type="submit" value="Send">
</form>
</div>
<div id="txtHint"></div>
<script>
$("#sendTweet").on("submit", function(e){
var tweet = $('areaTweet').val();
var update = $('#txtHint');
$.ajax({
type: 'POST',
url: 'tweet2.php',
data: , tweet,
success:function(html){
update.html(html);
}
});
});
</script>
tweet2.php file
<?php
include 'connect.php';
session_start();
$tweet=$_POST['tweet'];
$email =$_SESSION['login_user'];
$sqlr = "INSERT INTO tweets(tweet,member_email) VALUES ('$tweet','$email')";
$rqu = mysqli_query($conn,$sqlr);
$x=0;
$arrayName = array();
$sql= "SELECT tweet FROM tweets WHERE member_email= '$email' "
$rq = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($rq)) {
$arrayName[$x] = $row["tweet"];
$x=$x+1;
}
<?php for($k = 0; $k < $x; $k++) {?>
<p><?php echo $arrayName[$k]; ?></p>
<?php } ?
?>
Here is the working code...Note all changes did in 2 files..
HTML
<html>
<head>
<title>Tweets</title>
</head>
<body>
<div id="tweetSpace">
<form id="formTweet" method="post" >
<textarea id="areaTweet" name="message" rows="2" cols="120" placeholder="Write your tweet here..."></textarea>
<br>
<input id="sendTweet" type="button" value="Send">
</form>
</div>
<div id="txtHint"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
$("#sendTweet").click(function(e){
var tweet = $('#areaTweet').val();
var update = $('#txtHint');
$.ajax({
type: 'POST',
data: {'tweet':tweet},
url: 'tweet2.php',
success:function(html){
update.html(html);
}
});
});
</script>
</body>
</html>
tweet2.php
<?php
session_start();
include 'connect.php';
/*
$servername = "localhost";
$username = "root";
$password = "";
$db = "sflow";
$conn = mysqli_connect($servername, $username, $password, $db);
*/
$tweet = $_POST['tweet'];
$email = /*"sample#s.com";//*/$_SESSION['login_user'];
$sqlr = "INSERT INTO tweets(tweet,member_email) VALUES ('$tweet','$email')";
$rqu = mysqli_query($conn,$sqlr);
$x=0;
$arrayName = array();
$sql= "SELECT tweet FROM tweets WHERE member_email= '$email'";
$rq = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($rq)) {
$arrayName[$x] = $row["tweet"];
$x=$x+1;
}
for($k = 0; $k < $x; $k++)
echo '<p>'.$arrayName[$k].'</p>';
?>
Sample Table
CREATE TABLE IF NOT EXISTS `tweets` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`tweet` varchar(255) NOT NULL,
`member_email` varchar(255) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `sid_2` (`tweet`),
KEY `sid` (`tweet`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `tweets`
--
INSERT INTO `tweets` (`ID`, `tweet`, `member_email`) VALUES
(1, 'sasa', 's#g.com'),
(2, 'fgfg', 'sample#s.com');
is that an extra comma in your ajax before tweet? data: , tweet,
if so it wont work. should be data: tweet,
You don't want to refresh page ,so must use preventDefault but its only work with form id .So need to change submit button id with form id .Second thing is your data format function must like json {key : value}
$("#formTweet").on("submit", function(e){
e.preventDefault(); //prevent refresh page
var tweet = $('#areaTweet').val();
var update = $('#txtHint');
$.ajax({
type: 'POST',
url: 'tweet2.php',
data: {tweet:tweet},
success:function(html){
update.html(html);
}
});
});
I think you need to modify your tweet2.php
<?php
include 'connect.php';
session_start();
$tweet=$_POST['tweet'];
$email =$_SESSION['login_user'];
$sqlr = "INSERT INTO tweets(tweet,member_email) VALUES ('$tweet','$email')";
$rqu = mysqli_query($conn,$sqlr);
$sql= "SELECT tweet FROM tweets WHERE member_email= '$email' ";
$rq = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc($rq)) {
echo "<p>".$row["tweet"]."</p>";
}
?>
Make sure to set exit(); at the end of tweet2.php file. Then only you will able to get response back. Moreover, You should define data in the form of data: {tweet:tweet} format. tweet Variable will go with the ajax to your php file.
$("#sendTweet").on("submit", function(e){
var tweet = $('areaTweet').val();
var update = $('#txtHint');
$.ajax({
type: 'POST',
url: 'tweet2.php',
data: {tweet:tweet},
success:function(html){
update.html(html);
}
});
});
UPDATED
Instead of this
var tweet = $('areaTweet').val();
use
var tweet = $('#areaTweet').val();

My pdo ajax code for search is not working

What I want to do is: when a user types their email, my ajax code will run and show the user pass in the password inputbox.
The problem is that while my ajax code is sending the email to search.php, my search.php isn't giving the data to my ajax to show.
I think the problem is in my search.php because when i go to search.php after i type an email in my index the search.php is just blank no data is showing.
Index (Form):
email <input type="text" id="query" name="myemail" class="search_textbox" /><br />
Your Password <input type="text" id="mypass" name="mypass" readonly="readonly" /><br />
<script>
$(document).ready(function(){
$('.search_textbox').on('blur', function(){
$('#query').change(updateTextboxes);
updateTextboxes()
})
$('.search_textbox').on('keydown', function(){
$('#query').change(updateTextboxes);
updateTextboxes()
})
$('#query').change(updateTextboxes);
var $mypass = $('#mypass');
function updateTextboxes(){
$.ajax({
url:"search.php",
type:"GET",
data: { term : $('#query').val() },
dataType:"JSON",
success: function(result) {
var ii = 1;
for (var i = 0; i < result.length; i++) {
$mypass.val(result[i].value).show().trigger('input');
ii++;
}
}
});
};
});
</script>
search.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_GET['term'])) {
$q = $_GET['term'];
$sql = "SELECT password FROM students WHERE email = :term";
$query = $dbc->prepare($sql);
$query->bindParam(':term', $q);
$results = $query->execute();
$data = array();
while ($row = $results->fetch()) {
$data[] = array(
'value' => $row['password']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
I noticed header('Content-type: application/json');. I don't think it is necessary. Remove the line and try again. I am not sure but I think php header is needed for a new page. Since you have echo json_encode($data); and in your AJAX call, you are already processing the return data as json, the header(...) is not needed.
EDIT
$q = $_GET['term'];
$sql = "SELECT password FROM students WHERE email = :term";
$query = $dbc->prepare($sql);
$query->bindParam(':term', $q);
if($query->execute() && $query->rowCount()){
echo json_encode($query->fetch(PDO::FETCH_ASSOC));
}
SCRIPT
function updateTextboxes(){
$.ajax({
url:"search.php",
type:"GET",
data: { term : $('#query').val() },
dataType:"JSON",
success: function(result) {
//check here if you have a result, if yes than...
$("#mypass").val(result.password);
}
}

Troubles sending textarea data to a database

I'm trying to create a php form that sends textarea data to database. The database table uploads has 3 data items that are needed:
user_id
category
content
HTML:
<form id="myform" action="php/savetext.php" method="POST" enctype="multipart/form-data">
<p><strong>Add your story here.</strong></p>
<input type="hidden" name="fbid" id="fbid">
<input type="hidden" name="category" id="category">
<textarea cols="50" rows="10" name="usertext" id="storyArea"></textarea>
<input type="submit" name="submit" value="Saada" />
<script type="text/javascript">
$( "#fbid" ).val( "sdf88d99sd" );
$( "#category" ).val( "texts" );
</script>
</form>
savetext.php:
include_once('config.php');
if (isset($_POST['user_id']) && isset($_POST['category']) && isset($_POST['usertext'])) {
$user_id = mysql_real_escape_string($_POST['fbid']);
$category = mysql_real_escape_string($_POST['category']);
$content = mysql_real_escape_string($_POST['usertext']);
addUser($user_id, $category, $content);
}
else {
echo 'Upload failed! Try again.';
}
function addUser($user_id, $category, $content) {
$query = "SELECT id FROM uploads WHERE user_id = '$fbid' LIMIT 1";
$result = mysql_query($query);
$rows = mysql_num_rows($result);
if ($rows > 0) {
$query = "UPDATE uploads SET user_id = '$user_id', category = '$category' WHERE content = '$content'";
}
else {
$query = "INSERT INTO uploads (user_id, category, content) VALUES ('$user_id', '$category', '$content')";
}
mysql_query($query);
echo 'Upload was succesful. Thank you!';
}
But this doesn't work. Any ideas on how to correct this?
please review this code ,there is no field with name user_in in <form></form>
if (isset($_POST['fbid']) && isset($_POST['category']) && isset($_POST['usertext'])) {
$user_id = mysql_real_escape_string($_POST['fbid']);
$category = mysql_real_escape_string($_POST['category']);
$content = mysql_real_escape_string($_POST['usertext']);
addUser($user_id, $category, $content);
}

Categories