I have a faulty Ajax call apparently - javascript

I have a project where a user can have his own VirtualDiary online. He/She registers logs in and all that and is brought to a entry page with the date and a text area. The idea is that they will be able to click on two buttons on the top of the page titled NextPage and PreviousPage. These will call a jquery ajax function which will in turn change the value of EntryID + 1 or EntryID -1. This should change the value of pretty much everything on the page. But nothing happens even though the ajax call logs success. I am very new to ajax so I have probably Done something really stupid. Thanks in advance
PHP
<?php
session_start();
//error_reporting(E_ERROR|E_WARNING);
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
$JoinDateQuery = mysql_query("SELECT * FROM users WHERE UID = '".$_SESSION['UID']."' ");
if($JoinDateQuery === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($JoinDateQuery))
{
$JoinDate = $row[4];
}
$TodayDate = date("Y/m/d");
$today = strtotime($TodayDate);
$joinTime = strtotime($JoinDate);
$datediff = $today - $joinTime;
$_SESSION["EntryID"] = floor($datediff/(60*60*24));
$EntryID = $_SESSION["EntryID"];
$_SESSION['EntryDate'] = date('Y-m-d', strtotime($JoinDate. ' + '.$EntryID .'days'));
$EntryDate = $_SESSION['EntryDate'];
$id = $_SESSION["UID"] ;
if (isset($_POST["entry"])){
$entry = $_POST["entry"];
$deletion = "DELETE FROM entries WHERE UserID = '".$_SESSION['UID']."' and EntryID = '".$EntryID."' ";
mysql_query($deletion);
$submission = "INSERT INTO `virtualdiary`.`entries` (`Entry`, `UserID`,`EntryID`) VALUES ('". $entry . "', '".$_SESSION['UID']."', '".$EntryID."')";
mysql_query($submission);
}
$ThePost = 'SELECT * FROM entries WHERE UserID = "'. $_SESSION['UID'] .'" and EntryID = "'.$EntryID.'"';
$result = mysql_query($ThePost);
if($result === FALSE) {
die(mysql_error());
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Entry.css"/>
<title>Home</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
$('#NextDay').click(function(){
$.ajax({
type: "GET",
url: "Home.php",
data: "$EntryID = $EntryID + 1",
success: console.log("success")
}); //ajax call
});//on click next day
});//document ready</script>
</head>
<body>
<section>
<button id="previousDay" class="day">Previous Day</button>
<button class = "day" id = "date">Joined: <?php echo $JoinDate; ?></br>
Entry Number: <?php echo $EntryID + 1; ?></br>
EntryDate: <?php echo $EntryDate ; ?>
</button>
<button class="day" id = "NextDay">Next Day</button>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="80">
<?php
while($row = mysql_fetch_array($result))
{
echo $row['Entry'];
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<button id="calender" class = "day"><h1>Calender</h1></button>
<button id="LogOut">Log Out</button>
</section>
</body>
</html>
By the way EntryID returns result of 4 (or the default for the user on this day) so its pretty obvious the problem has something to do with the Data: part of the ajax or that I am not using ajax in the right context to achieve what I want.
EDIT: I have just been made aware that $EntryID = $EntryID + 1 has to be defined somewhere but where and I can't just plonk it down somewhere cause that would change the first instance of entry id I think.

First of all, I think you should be making an AJAX "POST" request, not a "GET" request. (Just industry standard, since you're sending a value through to a server).
Second, I'm not sure, where you got the syntax to create a data value for that GET request (really weird) however!, in the ajax call where I edited your code, there should now be the correct way of creating & sending de-serializable data.
EDIT
Forgot to mention, that the values sent from the AJAX, can be retrieved using $_REQUEST['xyx'] or $_POST['xyz'].. If you are using get, you can use $_GET['xyz']
UNTESTED
//error_reporting(E_ERROR|E_WARNING);
mysql_connect("localhost", "root", "") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
$JoinDateQuery = mysql_query("SELECT * FROM users WHERE UID = '" . $_SESSION['UID'] . "' ");
if ($JoinDateQuery === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while ($row = mysql_fetch_array($JoinDateQuery)) {
$JoinDate = $row[4];
}
$TodayDate = date("Y/m/d");
$today = strtotime($TodayDate);
$joinTime = strtotime($JoinDate);
$datediff = $today - $joinTime;
$_SESSION["EntryID"] = floor($datediff / (60 * 60 * 24));
$EntryID = $_POST["EntryID"];
$_SESSION['EntryDate'] = date('Y-m-d', strtotime($JoinDate . ' + ' . $EntryID . 'days'));
$EntryDate = $_SESSION['EntryDate'];
$id = $_SESSION["UID"];
if (isset($_POST["entry"])) {
$entry = $_POST["entry"];
$deletion = "DELETE FROM entries WHERE UserID = '" . $_SESSION['UID'] . "' and EntryID = '" . $EntryID . "' ";
mysql_query($deletion);
$submission = "INSERT INTO `virtualdiary`.`entries` (`Entry`, `UserID`,`EntryID`) VALUES ('" . $entry . "', '" . $_SESSION['UID'] . "', '" . $EntryID . "')";
mysql_query($submission);
}
$ThePost = 'SELECT * FROM entries WHERE UserID = "' . $_SESSION['UID'] . '" and EntryID = "' . $EntryID . '"';
$result = mysql_query($ThePost);
if ($result === FALSE) {
die(mysql_error());
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Entry.css"/>
<title>Home</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function () {
$('#NextDay').click(function () {
$.ajax({
type: "POST",
url: "Home.php",
data: {
EntryID: '1' //not sure (this is quite conditional I guess)
},
success: console.log("success")
}); //ajax call
});//on click next day
});//document ready</script>
</head>
<body>
<section>
<button id="previousDay" class="day">Previous Day</button>
<button class="day" id="date">Joined: <?php echo $JoinDate; ?></br>
Entry Number: <?php echo $EntryID + 1; ?></br>
EntryDate: <?php echo $EntryDate; ?>
</button>
<button class="day" id="NextDay">Next Day</button>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="80">
<?php
while ($row = mysql_fetch_array($result)) {
echo $row['Entry'];
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<a href="Calender.php">
<button id="calender" class="day"><h1>Calender</h1></button>
</a>
<button id="LogOut">Log Out</button>
</section>
</body>
</html>

From http://api.jquery.com/jquery.ajax/
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
You're trying to happened "$EntryID = EntryID + 1" to "home.php"
"home.php$EntryID = EntryID + 1" doesn't seem like a correct url ?
You should try with the error callback set if you want more informations on the request status.

Related

How to submit data using ajax and display result without refreshing

EDIT:
SOLVED. Thank you all for help. :)
EDIT:
Your suggestions worked. The problem now is that after the first find and displaying the found result, the found set stays the same no matter what i try to find next. Even after restarting the browser. Is it possible that the found data stays somewhere in server cache and is displayed as a result?
I'm trying to send data from the form using jquery to php file process it there and then display the result from it.
After pressing the submit nothing happens. There are no errors in the console.
Everything worked before i added jquery but after that i don't see any result.
My HTML:
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<form id="my_form">
Imie: <br/> <input name="name" id="firstname" type="text" /><br />
<input id="submit_form" type="submit" value="Submit">
</form>
<div id="update_div"></div>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var var_name = $('firstname').val();
var update_div = $('#update_div');
console.log('zmienna var_name ' + var_name);
console.log('zmienna update_div ' + update_div);
$.ajax({
type: 'GET',
url: 'test.php',
data: var_name,
success: function(response){
update_div.html(response);
}
});
});
</script>
</body>
</html>
My PHP:
<?php
require 'db_handler.php';
$criterion_name = $_GET['name'];
$query = $fm->newFindCommand("OFERTY tabela");
$query->addFindCriterion('kontrahent_opiekun', "=" . $criterion_name);
$result = $query->execute();
if(FileMaker::isError($result)){
echo($result->getMessage());
return;
}
$i = 0;
// Get array of found records
$records = $result->getRecords();
foreach ($records as $record) {
echo $record->getField('_kp_oferta') . " - ";
echo $record->getField('kontrahent_Skrot') . " - ";
echo $record->getField('kontrahent_opiekun') . '</br>';
$i++;
}
echo $i . " Pozycje";
?>

PHP running AJAX script works only once

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}

PHP to read DB value, JS to increment it, AJAX to save to DB, but why does it default to 0.0 before refreshing the page?

I am making a temperature target page where the form will read the current target, allow the user to +/- by 0.5 using Javascript buttons and then 'set' the target which takes the new value and saves it back to the database.
I have a working page which can read the DB value and set it, but then automatically reverts to '0.0' as the target. If the page is refreshed then it will display the target, but sometimes saves it at 0.0 in the DB.
I'm very confused as to why as I've spent far too long on this, but its bugging me! Any help is much appreciated, thanks.
Here is my code:
<?php
$conn = connect DB stuff here...
$queryTarget = "SELECT * FROM target;";
$result2 = $conn->query($queryTarget);
$conn->close();
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$target = $row['target'];
}
}
?>
<form id="input" method="post" action="">
Temp <input type="text" value="<?php echo $target; ?>" name="temp" id="temp" >
<input type="button" id="Up" value="up" / >
<input type="button" id="Down" value="down"/ >
<input type="submit" id="submit" value="submit " name="submit">
</form>
<?php
$conn = connect DB stuff here...
$temp = $_POST['temp'];
$updateTarget = "UPDATE target SET target = '";
$updateTarget = $updateTarget . $temp . "' WHERE id = 1;";
$result = $conn->query($updateTarget);
$conn->close();
?>
<script>
var min = 15,
max = 25;
$("#Up").click(function(){
if($("#temp").val() < 25 && $("#temp").val() >= 15)
$("#temp").val(Number($("#temp").val()) + 0.5);
});
$("#Down").click(function(){
if($("#temp").val() <= 25 && $("#temp").val() > 15)
$("#temp").val(Number($("#temp").val()) - 0.5);
});
</script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'form.php',
data: srt,
success: function(d) {
$("#input").html(d);
}
return false;
});
});
});
</script>
just echo this temp value
<?php
//$conn = connect DB stuff here...
$temp = $_POST['temp'];
or
print_r($_POST);
echo $temp;
die();
$updateTarget = "UPDATE target SET target = '";
$updateTarget = $updateTarget . $temp . "' WHERE id = 1;";
then check alert if alert show right data then
then use single query like this
$updateTarget = "UPDATE target SET target = '$temp' WHERE id = 1";
//i think it will help you to find issue
$result = $conn->query($updateTarget);
$conn->close();
?>
and your javascript function need to update
<script>
$(document).ready(function(){
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'form.php',
data: srt,
success: function(d) {
alert(d);
$("#input").html(d);
}
});
return false;
});
});
</script>
if you find right data then check your db structure that is it allow float etc. i think it will work
you can also check this
How to Search value from input by mysqli in database

Ajax request working but no output

Hello I'm a beginner in Ajax and PHP so sorry if my question is useless or stupid. But I am trying to do a live search with ajax and I have looked over and over internet but nothing could help me... so here I am! :-) I have 4 files one for the html, one to connect to the database, one for jQuery and the last one for the script in php. I have looked on the console with chrome and I can see that the ajax works but there is no output and I have no idea why... I'll leave you the code below and an early thank you! Also there might be some French in the code but it's just the variables and I will secure my connection to the database later. Thank you again.
Html :
<html>
<head>
<meta charset="utf-8" />
<title>live search test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche">
</div>
<br>
<div class="resultat" id="resultat">
</div>
</body>
</html>
PHP to connect to the database:
<?php
$host="localhost";
$user="root";
$password="";
$db="smartphone";
$conn=mysqli_connect($host,$user,$password,$db);
?>
jQuery:
$(document).ready(function(){
$("#recherche").keyup(function(){
var recherche = $(this).val();
var data = 'motclef = ' + recherche;
if (recherche.length > 1) {
$.ajax({
type : "GET",
url : "fetch.php",
data : data,
success : function(server_response){
$("#resultat").html(server_response).show();
}
});
}
});
});
And the script in PHP:
include'connect.php';
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn ->prepare($sql);
$req -> execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req -> fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result ->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
?>
Remove whitespace from 'motclef = '
var data = 'motclef= ' + recherche;
Other wise put underscore $_GET['motclef_'] in your PHP code(if you don't remove space then)
if (isset($_GET['motclef_'])) {
$motclef = $_GET['motclef_'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn->prepare($sql);
$req->execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req->fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}

How to get PHP shuffle results to show up one at a time throughout shuffle

Say I have 10 items in my db that I am trying to shuffle, how could I alter my current code so that every time it pulls a name out of the db that it shows up one at a time, rather than all at once?
$con = mysqli_connect("XXX", "XXX", "XXX", "XXX");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
echo 'Normal results: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
$array[] = $row;
echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
?>
<form method="post">
<input type="submit" value="Shuffle" name="shuffle">
</form>
<?php
if (isset($_POST['shuffle'])) {
shuffle($array);
echo 'Shuffled results: <br>';
foreach ($array as $result) {
$shuffle_firstname = $result['firstname'];
$shuffle_lastname = $result['lastname'];
?>
<div id="shuffle_results">
<?php echo $shuffle_firstname . ' ' . $shuffle_lastname . '<br>';?>
</div>
<?php }
}
//What I added in and this is the spot I added it as well
$get_shuffle = array($array);
$shuffle_one = array_pop($get_shuffle);
print_r($get_shuffle);
?>
I want them all to stay put once they have shown.. I just want all of them to come out one at a time. Say, there is 10 pieces of paper in a bag and you are drawing one at a time and then put the pieces of paper on a table to show what was drawn, that is what I want.
As a follow up to my comment suggesting you use JavaScript instead of PHP for the animation, here is a basic way to do it. (This code assumes you have jQuery on the page).
Note: I haven't tested this code and there is likely a bug or two, but I hope you get the general idea.
Your HTML
<div id="shuffle_results"></div>
<form onsubmit="getData()">
<input type="submit" value="Shuffle" name="shuffle">
</form>
Your PHP
$con = mysqli_connect("localhost", "root", "", "db");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
array_push($array, $row);
}
header('Content-Type: application/json');
echo json_encode($array);
Your JavaScript
function getData() {
$.ajax({
url: 'url to PHP script',
dataType: 'json',
success: function(data) {
for(var i = 0, l = data.length; i < l; ++i) {
window.setTimeout(addResult, 2000, data[i].firstname, data[i].lastname);
}
},
error: function(jqXHR, textStatus, error) {
alert('Connection to script failed.\n\n' + textStatus + '\n\n' + error);
}
});
}
function addResult(firstname, lastname) {
$('#shuffle_results').append("<p>" + firstname + " " + lastname + "</p>");
}
The basic idea here is that you shouldn't use PHP to do DOM manipulation. PHP can load data into your webpage (and that data can be DOM elements, JSON data as I have shown, or other types of data), but once there JavaScript should be used to interact with it. Recall, PHP runs on your server, while JavaScript (traditionally) runs in the client's web browser.

Categories

Resources