I have this php page with javascript ajax which calls another php file. But every time it calls, it refreshes the page.
I tried these two codes but still it keeps refreshing after calling the `php file:
e.preventDefault();
//and
return false;
But still it keeps redirecting/refreshing to the same page. I don't even have redirecting headers in php file I'm calling.
This is my HTML
<div class="col-md-3 col-sm-6 col-6 ad-image">
<label for="file1">
<img id="blah1" src="http://placehold.it/500" alt="..." class="img-thumbnail">
<input type="button" value="Remove Photo" style="margin-top: 5px;" class="btn btn-danger btn-sm" id="image-remove-btn-1">
<small id="textCount" class="form-text text-center bold">Thumbnail</small>
</label>
</div>
Here's my javascript
$("#image-remove-btn-1").click(function (e) {
e.preventDefault(); //doesn't work still page keeps refreshing
$('#blah1').attr('src', 'http://placehold.it/500');
var userId =<?php echo $userId ?>;
var adId =<?php echo $adId ?>;
deletePhoto('blah1', userId, adId); //this is the function with ajax
$(this).hide();
return false; //doesn't work still page keeps refreshing
});
Here's the deletePhoto() function:
function deletePhoto(imgeName, userid, adId) {
$(document).ready(function () {
$.ajax({
url: 'includes/remove-ad-image-inc.php',
dataType: 'text', // what to expect back from the PHP script, if anything
data: {
userId: userid,
adId: adId,
imgeName: imgeName
},
type: 'post',
success: function (php_script_response) {
alert(php_script_response); // display response from the PHP script, if any
}
});
});
}
This is my php remove-ad-image-inc.php I am calling through above ajax
<?php
include_once './dbConnection.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$userId = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "userId"));
$adId = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "adId"));
$imgeName = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "imgeName"));
if (isset($userId) && isset($adId) && isset($imgeName)) {
$sql = "SELECT * FROM adimage WHERE adimageno=? AND adid=? AND userid=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "error!";
} else {
mysqli_stmt_bind_param($stmt, "sii", $imgeName, $adId, $userId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
$ImageId = $row['adimageid'];
}
$fileName = "../uploads/ad/adImage-" . $ImageId . "-" . $adId . "-" . $userId . "*";
$fileInfo = glob($fileName);
$fileExt = explode(".", $fileInfo[0]);
$fileActualExt = $fileExt[1];
$file = "../uploads/ad/adImage-" . $ImageId . "-" . $adId . "-" . $userId . "." . $fileActualExt;
array_map('unlink', glob($fileName));
$sql = "UPDATE adimage SET adimagestatus=1 WHERE adimageid='$ImageId';";
mysqli_query($conn, $sql);
exit();
}
}
Can someone please help me with a solution?
Related
I have this strange issue, happening to my PHP script, On page load the AJAX script runs and also after the second time the AJAX script runs it works and sends data to PHP, but i seem to not understand why the PHP script doesn't process the incoming POST request the second time it is sent in when i clean the input text box and type again, i get a blank response.My code for more expatiation.
index.php :
<input type="text" onkeyup="searchmedia(this)" placeholder="Search for seller with UNIQUE ID or Name.">
<div id="resut" style="margin-top:-24px!important;">
//where the ajax result is returned
</div>
<div style="margin-top:-24px!important;" id="normal">
//bla bla data here
</div>
<div id="hui" style="display:none;"><img src="../ajax5.gif">
</div>
<script>
function searchmedia(e) {
var tuq = $(e).val();
if (tuq == "") {
$('#resut').hide();
$('#normal').show();
$('#hui').hide();
} else {
$('#normal').hide();
$('#hui').show();
$.ajax({
type: 'POST',
url: 'sellersmessageajax.php',
data: {tuq: tuq},
timeout: 5000,
cache: false,
success: function (r) {
//console.log(r);
$('#resut').html(r);
$('#normal').hide();
$('#hui').hide();
},
error: function () {
alert("Could not search, reload the page and try again.");
$('#normal').show();
$('#hui').hide();
}
});
}
}
</script>
sellersmessageajax.php :
<?php include('../connect.php'); ?>
<?php
if (isset($_POST['tuq']))
{
$term = $_POST['tuq'];
$term = mysqli_real_escape_string($con,
$term); //WHEN I ALERT HERE THE SECOND TIME I SEE THE INPUT TEXT DATA THAT CAME IN BUT PLEASE CHECK AFTER THE **FOREACH**
$condition = '';
$query = explode(" ", $term);
foreach ($query as $text)
{
$condition .= "name LIKE '%" . mysqli_real_escape_string($con,
$text) . "%' OR reign_uniqeer LIKE '%" . mysqli_real_escape_string($con, $text) . "%' OR ";
}
//WHEN I ALERT HERE I GET NOTHING
$condition = substr($condition, 0, -4);
$zobo = "ORDER BY name";
$sql_query = "SELECT * FROM sellers_login WHERE " . $condition . $zobo;
$result = mysqli_query($con, $sql_query);
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$v_ida = $row['id'];
$v_namea = $row['name'];
$v_reign_uniqeera = $row['reign_uniqeer'];
?>
<div style="border-bottom:0.1px solid #eee;padding-bottom:20px;margin-top:20px;">
<a class="zuka" title="<?php echo $v_ida ?>" id="<?php echo $v_ida ?>"
style="color:#666;text-decoration:none;outline:none!important;cursor:pointer;">
<b style="color:blue;"><?php echo $v_namea ?></b>
<br/>
<div style="height:auto;max-height:30px;">
<b>UNIQUE ID :</b> <b style="color:red;"><?php echo $v_reign_uniqeera ?></b>
</div>
</a>
</div>
<?php
}
}
else
{
?>
<h1 class="zuka" style="text-align:center;margin-top:20%;"> No result found.</h1>
<?php
}
}
?>
Second time after clearing the data result set to hide. second time data is returning but it's hide
Add this line in ajax success block
$('#resut').show(); // Add this line
you are sending the var tuq wrongfully. Try this:
data : {"tuq": tuq}
What is wrong here?
My PHP/HTML (The only part that matters):
if(isset($_POST['submit']))
{
$date = date('Y-m-d', strtotime(str_replace("-","/",$_POST['dateOfEntry'])));
$username = $_POST['user'];
$query = 'SELECT `ID`, `Date`, `Description`, `TypeOfDowntime`, `Machine#` FROM `machineissuesreport` WHERE `Date`="'.$date.'" AND `UpdatedBy` = "'.$username.'" ORDER BY `ID` DESC';
$conn = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($conn))
{
echo '<tr>';
echo '<td style="text-align: center" width="5px"><input type="button" name="edit" value="Edit"></td>';
echo '<td style="text-align: center" width="5px">Delete</td>';
echo '<td style="display: none;"><input type="hidden" value='.$row['ID'].'></td>';
echo '<td>'.$row['Date'].'</td>';
echo '<td>'.$row['Description'].'</td>';
echo '<td>'.$row['TypeOfDowntime'].'</td>';
echo '<td>'.$row['Machine#'].'</td>';
echo '</tr>';
}
}
?>
My Ajax/Javascript:
$(document).ready(function()
{
$('.delete').click(function()
{
if(confirm("Are you sure you want to delete this row?"))
{
var del_id = $(this).attr('id');
var $ele = $(this).parent().parent();
$.ajax({
type: 'POST',
url: 'machineEntryLogEdit.php',
data: {'del_id':'del_id'},
success: function(data)
{
$ele.fadeOut().remove();
},
error: function (xhr, status, error)
{
alert(this);
}
});
}
});
});
My PHP (on an external script: machineEntryLogEdit.php):
include('connServer.php');
$deleteID = $_POST['del_id'];
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_connect($connection, $query);
if(isset($result))
{
echo "YES";
}
else
{
echo "NO";
}
?>
I have searched around and around for solutions but no avail. The only things it does is delete the record from the HTML table, but not from the database, causing the supposed-to-be-deleted row to reappear after refresh. I am still very new to AJAX (in fact I just learned it myself today) and still reading the documentations and forums. Thanks.
This should be data: {'del_id': del_id} remove quotes so it react as a variable, not just a single string. And one more thing, your delete query does not execute cause you're using :
$result = mysqli_connect($connection, $query);
Should be mysqli_query like the one you did on selecting data's part:
$query = 'DELETE FROM `machineissuesreport` WHERE `ID` ="'.$deleteID.'"';
$result = mysqli_query($connection, $query);
It looks to me like you didn't pass the submit variable in your data. If you want to include a form you need to pass the data, right now the server is receiving only one parameter, del_id
I was looking for a way to submit data through a button so that the data will be saved or updated in database, without reloading. Now updating and inserting of data works. But I have used dataString a javaScript variable. I thought through this dataString variable post data are passed. But when I removed that variable from my code data insert or update was still working. So how the passing of data working here.
How post method gets the data from my ajax call here.
<html>
<title>Registration</title>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "nopass";
$dbname = "registration_project";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<div style="width:350px">
<div style="float:left;width:40%">
Id:<br/><br/>
First Name:<br/><br/>
Last Name:<br/><br/>
Age:<br/><br/>
</div>
<div style="float:left;width:60%">
<form action="" method="post">
<input type="number" id="id_id" name="id" value=<?php
if (isset($_POST['id']))
echo $_POST['id'];
?>><br /><br />
<input type="text" id="id_fname" name="fname" value=<?php
if (isset($_POST['fname']))
echo $_POST['fname'];
?>><br /><br />
<input type="text" id="id_lname" name="lname" value=<?php
if (isset($_POST['lname']))
echo $_POST['lname'];
?>><br /><br />
<input type="number" id="id_age" name="age" value=<?php
if (isset($_POST['age']))
echo $_POST['age'];
?>><br /><br />
<input type="submit" id="id_submit" name="submit">
</form>
</div>
</div>
<script src="js/jquery-1.11.3.js"></script>
</body>
</html>
<?php
if (isset($_POST['id']))
echo $_POST['id'] . "<br/><br/>";
if (isset($_POST['fname']))
echo $_POST['fname'] . "<br/><br/>";
if (isset($_POST['lname']))
echo $_POST['lname'] . "<br/><br/>";
if (isset($_POST['age']))
echo $_POST['age'] . "<br/><br/>";
?>
<?php
if (isset($_POST['submit'])) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$sql = "select max(id) from registration";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$id = $row["max(id)"];
}
} else {
echo "0 results";
}
if ($id==$_POST['id']) {
$id = $_POST['id'];
$sql = "update registration set firstName='$fname', lastName='$lname', age=$age where id=$id";
mysqli_query($conn, $sql);
} else {
$id=$_POST['id'];
$sql = "Insert into registration(id,firstName,lastName,age) values($id,'$fname','$lname',$age)";
mysqli_query($conn, $sql);
}
}
mysqli_close($conn);
?>
<script>
$("#id_submit").click(function(e) {
var id = $("#id_id").val();
var fname = $("#id_fname").val();
var lname = $("#id_lname").val();
var age = $("#id_age").val();
var dataString = "id="+id+ '&fname='+fname+'&lname='+lname+'&age='+age;
//console.log(dataString);
$.ajax({
type:'POST',
data:dataString,
url:'Registration.php',
success:function(data) {
}
});
});
</script>
Your click handler doesn't have e.preventDefault() in it. So after the AJAX call is sent, the form is also submitted normally. So even if you don't fill in dataString, the database will be updated from the form.
To make it only use AJAX, you should call e.preventDefault(). You also need to submit a value for the submit parameter, because the PHP code uses if(isset($_POST['submit'])) to know if it should process the form parameters.
$("#id_submit").click(function(e) {
e.preventDefault();
var id = $("#id_id").val();
var fname = $("#id_fname").val();
var lname = $("#id_lname").val();
var age = $("#id_age").val();
var dataString = "submit=submit&id="+id+ '&fname='+fname+'&lname='+lname+'&age='+age;
//console.log(dataString);
$.ajax({
type:'POST',
data:dataString,
url:'Registration.php',
success:function(data) {
}
});
});
In your case, values aren't getting passed. More over, the way you're trying to do ( ?id=...&fname=... etc) would be for passing it with $_GET.
You have to make something similar to :
$.ajax({
type:'POST',
data: { id : $("#id_id").val(),
fname : $("#id_fname").val(),
lname : $("#id_lname").val(),
age : $("#id_age").val()
},
url:'Registration.php',
success:function(data) {
// code
}
});
But when I removed that variable from my code data insert or update was still working. So how the passing of data working here.
Answer
When you remove var dataString all the fields having name attribute are automatically submitted along with form
I have a problem with my like system an user can give more than 1 like but the system register on the db just one, i think is a problem related to AJAX.
This is the button:
<a class="btn btn-xs btn-white" name="btn" onclick="usercountcomments(<?php echo $value['user_id'].",".$value['personal_closest_id'].",".$value['id']; ?>)"><i class="fa fa-star"></i><span id="countVal1_<?php echo $value['id']; ?>"><?php echo $value['countcomments']; ?></span> Cool </a>
And this one is the jscript AJAX script:
function usercountcomments(user_id,postId,id){
var a = $("#countVal1_"+id).text();
var display = document.getElementById("countVal1_"+id);
var count = a;
var user_comments="cool";
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>social/commentcool/" +user_id+"/"+postId+"/"+user_comments,
data:{ user_comments : user_comments},
success: function(data) {
count++;
display.innerHTML = count;
// alert(a++);
}
});
}
What can I do to prevent the user giving more than one like ?
you can use cookie
<?php
$id =$_GET['id'];
if(isset($_COOKIE['like'.$id])) {
echo "error";
exit;
}else {
$sql = "UPDATE post SET likecount=likecount+1 WHERE id=$id";
$conn->query($sql);
$sql = "SELECT likecount from post where id=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
echo $row['likecount'];
setcookie('like'.$id,true, time() + (86400 * 30), "/");
}
}
I'm not sure how to get the post title into the jquery .ajax call. I am able to create and display my blog posts, now I'm trying to add functionality to delete and edit. I'm starting with delete since it's obviously the easier of the two. How do I get the blog title from the post array into my functions.js file so that I can delete the matching record in my Database? Also... Thanks!
HTML
<?php
include 'scripts/db_connect.php';
include 'scripts/functions.php';
sec_session_start();
$sql = "SELECT * FROM blog";
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result))
{
echo'<div class="blog"><h3 class="blog">' . $row['Title'] . "</h3><h3>" . $row['Date'] . "</h3><h3>" . $row['Tag'] . "</h3><hr>";
echo'<p class="blog">' . $row['Body'] . '</p><button id="editPost" type="button">Edit</button><button id="deletePost" type="button">Delete</button><button id="commentPost" type="button">Comment</button></div>';
}
?>
Functions.php
$function= $_POST['function'];
$title = $_POST['title'];
if($function == "deletePost")
deletePost($title)
function deletePost($title){
$sql = "DELETE FROM blog WHERE Title = '$title';";
mysqli_query($mysqli, $sql);
}
Functions.js
$(document).ready(function(){
$('#deletePost').on('click', function(){
$.ajax({
url: 'functions.php',
data:{function: "deletePost", title: "how do I get the blog title here"}
success: function(data){
//confirmation of deletion
}
});
});
});
Since you are expecting a POST request, you'll need to specify that while making the AJAX request.
$.ajax({
url: 'functions.php',
type: 'POST', // specify request method as POST
...
});
That should do it.
Try This
<?php
include 'scripts/db_connect.php';
include 'scripts/functions.php';
sec_session_start();
$sql = "SELECT * FROM blog";
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result))
{
echo'<div class="blog"><h3 class="blog">' . $row['Title'] . "</h3><h3>" . $row['Date'] . "</h3><h3>" . $row['Tag'] . "</h3><hr>";
echo'<p class="blog">' . $row['Body'] . '</p><button id="editPost" type="button">Edit</button><a class="deletePost" rel="'. $row['Title'] .'" href="#" >Delete</a><button id="commentPost" type="button">Comment</button></div>';
}
?>
$(document).ready(function(){
$(".deletePost").on('click', function(){
$.ajax({
url: 'functions.php',
type: 'POST',
data:{function: "deletePost", title: $(this).attr('rel')}
success: function(data){
//confirmation of deletion
}
});
});
});