PHP running AJAX script works only once - javascript

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}

Related

Dropdown post live search ,add onclick redirect to post (php page)

Hi,
i am coding a homepage to learn php and javascript. I decided to use a livesearch using jQuery and php.
It is working well ,but i wonder how i can integrate to the found titles an onclick function that will redirect to the viewpost.php so it opens the clicked title and opens the post.
My HTML search part on index page:
<!-- Search Widget -->
<div class="card my-4">
<div class="card bg-success">
<h5 class="card-header">Search</h5>
<div class="card-body">
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search country..." />
<div class="result"></div>
</div>
</div>
</div>
</div>
jQuery part for livesearch that redirect to php page(backend-search.php)
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
PHP backend-search.php
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
require_once "pdoconfig.php";
// Attempt search query execution
try{
if(isset($_REQUEST["term"])){
// create prepared statement
$sql = "SELECT * FROM articles WHERE title LIKE :term";
$stmt = $db->prepare($sql);
$term = $_REQUEST["term"] . '%';
// bind parameters to statement
$stmt->bindParam(":term", $term);
// execute the prepared statement
$stmt->execute();
if($stmt->rowCount() > 0){
while($row = $stmt->fetch()){
echo "<p>" . $row["title"] . "</p>";
}
} else{
echo "<p>No matches found</p>";
}
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close statement
unset($stmt);
// Close connection
unset($db);
?>
That is my table structure called articles:
id title content categorie_id pubdate views short_details
And finally my viewpost.php
<?php
$stmt = $db->prepare('SELECT id, title, text, pubdate FROM articles WHERE id = :id');
$stmt->execute(array(':id' => $_GET['id']));
$row = $stmt->fetch();
//if post does not exists redirect user.
if($row['id'] == ''){
header('Location: ./');
exit;
}
echo "<br>";
echo "<div class='card mb-4'>" . "<div class='card-body'>";
echo "<h2 class='card-title'>";
echo $row['title'] . "</h2>";
echo "<div class='card-footer text-muted'>";
echo $row['pubdate'];
echo "</h2>";
echo "<p class='card-text'>";
echo $row['text'];
echo "</p>";
echo '</div>';
?>
Do i need to get the articles id with the jQuery and somehow post it onclick to viewpost.php ?
I do appreciate all help ..
You Need To Change This PHP "backend-search.php" File :
This Code To
if($stmt->rowCount() > 0)
{
while($row = $stmt->fetch())
{
echo "<p>" . $row["title"] . "</p>";
}
}
else
{
echo "<p>No matches found</p>";
}
This Code
if($stmt->rowCount() > 0)
{
while($row = $stmt->fetch())
{
echo "<p>". $row["title"] . "</p>";
}
}
else
{
echo "<p>No matches found</p>";
}

How to prevent refreshing page after AJAX call

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?

Live Search Box Using PHP, MySQL and AJAX

I am trying to make an search box which to display the "Address" from MYSQL/PHP
I have used ajax to refresh page without leaving page, but when I run in browser, it always give me an error. when I used console, the return result of echo $_POST['name'] = ( html code of header.php + "What I need" + html code of footer.php )
<?php
include 'header.php';
include 'Connect.php';
if( isset($_POST['ajax']) && isset($_POST['name']) ){
echo $_POST['name'];
exit;
}
?>
<form method="POST">
<label>Username</label>
<input type="text" name="name" required="required" id='name'>
<div id='response'></div>
</form>
<script>
$(document).ready(function(){
$('#name').keyup(function(){
var name = $('#name').val();
$.ajax({
type: 'post',
url: index.php,
data: {ajax: 1,name: name},
success: function(response){
$('#response').text(response);
}
});
});
});
</script>
<?php
if(isset($_POST['name'])){
$username = $_POST['name'];
$stmt = $con->prepare("SELECT Username, FullName, Adresse, Email, Phone FROM dbo.users WHERE Username= ?");
$stmt->execute(array($username));
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$Username = $row["Username"];
$FullName = $row["FullName"];
$Adresse = $row["Adresse"];
$Email = $row["Email"];
$Phone = $row["Phone"];
echo "<tr>
<div>
<td>".$Username."</td>
<td>".$FullName."</td>
<td>".$sEID."</td>
<td>".$Email."</td>
<td>".$Phone."</td>
</div>
</tr>";
}
echo "</table>
</div>";
} else echo '<div class="alert alert-danger"> This Name <strong>is not exit</strong></div>';
include $tpl.'footer.php';
}
?>
Your question isn't very clear... if i understand correctly... this is broken by design, you're calling the page itself and update #name with the content of the entire page, thats why you see html + "what you need" (the response): the response is the whole page.
The right way to do this would be to move the second part of PHP code (where you perform the query ecc.) on a separate script and then call that new script by putting its name as the url parameter in the ajax call.
thank you for your respanse, i want to use the value returned by ajax to use with MYSQL/PHP to echo $row['Address'];
if i move the second part of PHP code the result is
echo $_POST['name'] = ( "What I need" + html code of footer.php )

how should i put data fetched from ajax call in hidden div box

i am working on a project and come across a module.
page1
user have to search from search bar which will take him to page 2.
page2
On page 2 all fetched results will get displayed to user in div's. Each result has a checkbox associated with it.
when i click on add to compare check box ,ajax call is executed and fetched selected result should appear in hidden div.
my problem is it is only shows first result in hidden div and not working with another result.
My code of page 2
<script type="text/javascript">
$(document).ready(function()
{
var check = $('#compare').val();
$("#compare").change(function() {
if(this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').html(data);
}
});
$("#compare_box").show();
}
else
{
$("#compare_box").hide();
}
});
});
</script>
</head>
<body>
<?php
$query = $_GET['search_bar'];
$query = "call fetch_data('$query')"or die(mysqli_error($conn));
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result))
{
$id = $row['course_id'];
$title = $row['course_title'];
$description = $row['course_description'];
$course_url = $row['course_url'];
$video_url = $row['course_video_url'];
$fee = $row['course_fee'];
$duration = $row['course_duration'];
$start_date = $row['course_start_date'];
$university = $row['university_name'];
$course_provider = $row['course_provider_name'];
$instructor = $row['instructor_name'];
$_SESSION['result'][$id] = Array('id'=> $id,'course_title' => $title,'course_description'=> $description,'course_url' => $course_url,'video_url' => $video_url,'fee' => $fee,'course_duration'=>$duration,'start_date'=>$start_date,'university' => $university,'course_provider'=>$course_provider,'instructor'=>$instructor);
?>
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
<?php
}
?>
page3 compare.php
<?php
session_start();
include 'includes/dbconfig.php';
$check = $_POST['value'];
$sql = "SELECT * from course_info_table where course_id = '$check' " or die(mysqli_error($conn));
$result = mysqli_query($conn,$sql);
$index = 0;
while($row = mysqli_fetch_array($result))
{
$title = $row['course_title'];
?>
<?php
}
echo json_encode($title);
?>
You can change
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">
to
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">
^you can only have one unique 'id' value in your html doc, which means your first id="compare" will work fine and others with id="compare" will be ignored by the DOM tree
Reference:
http://www.w3schools.com/tags/att_global_id.asp

AJAX passing value confusion

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

Categories

Resources