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";
?>
Related
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 )
I am trying to import a json array from a php script in JavaScript but every time the request fails and the xhr.responseText return the html code of the template of the html template associated to it. I am using xampp.
php code:
<?php
// This script is meant to display the data from Insight sensors DB
include('includes/motebymote.html');
if ($_SERVER['REQUEST_METHOD'] == 'POST'){//Use the post method as a request method to the server
require('mysqli_connect.php');//Give information on which database to use
if(!empty($_COOKIE["mote_ID"]) || !empty($_COOKIE["std"]) || !empty($_COOKIE["end"])){
//Setting variables
$moteID=$_COOKIE["mote_ID"];
$start=$_COOKIE["std"];
$end=$_COOKIE["end"];
if(preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $start) || preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $end)) {
if(isset($moteID) && isset($start) && isset($end)){
//Building the query
$q="SELECT date_time, modality, value FROM sensor_data WHERE mote_id = $moteID and date_time BETWEEN '$start' and '$end'";
$r = #mysqli_query ($dbc, $q);//Doing the request
$numRow = mysqli_num_rows($r);
if ($r && $numRow>0){
//echo "<p>There are $numRow data points associated to mote$moteID</p><br>";
//echo"<table align ='center' width ='70%' cellpadding='4'><tr><th>Date&Time</th><th> Sensor Type</th><th> Value</th></tr>";
$moteArray = array();
while($data = mysqli_fetch_array($r, MYSQLI_BOTH)){
//echo "<tr align ='center'><td>" .$data['date_time']. "</td><td>" .$data['modality']. "</td><td>" .$data['value']. "</td></tr>";
$moteArray[] = $data;
}
//echo"</table>";
$JSONMoteArray = json_encode($moteArray);
echo $JSONMoteArray;
}
else if ($numRow==0){
echo "<h1>Sorry there are no data available</h1>
<p>There are no data available for mote$moteID</p>";
}
else{//Give an error message if the query fails
echo '<h1>System Error</h1>
<p class="error">We could not record your order due to a system error. We apologize for any inconvenience.</p>';
}
}
}
else {
echo "<h1> Wrong date format</h1>
<p>Please input the starting date in a yyyy-mm-dd format</p>";
}
}
else{
echo "<h1> Wrong input</h1>
<p> Please make sure that the mote is properly selected and that the start and end dates are entered in yyyy-mm-dd format</p>";
}
mysqli_close($dbc); //close the database
}
exit(); //exits the script
?>
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
<title> Motes Data</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/mote.js" async></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body><br>
<form action="motebymote.php" method="post">
<p>Please input a mote number: <input type="text" name="moteNo" id="moteNo"></p>
<p> Please input a starting date (yyyy-mm-dd):<input type="text" name="stDate" id="stDate"></p>
<p> Please input an end date (yyyy-mm-dd):<input type="text" name="endDate" id="endDate"></p>
<p><input type="submit" name="submit" value="submit" id="submit"/></p>
<p><input type="submit" name="display" value="display" id="display"/></p>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
</form>
</body>
</html>
var but = document.getElementById("submit"); //Looking for the submit button
if(but){ //if the button is clicked activate the event listener
but.addEventListener("click", moteIDDate);
}
//This function goes to fetch the different values and store them with cookies //to allow motebymote.php to use them
function moteIDDate(){
var moteID = $('#moteNo').val();
document.cookie="mote_ID = " + moteID + ";time()+3600";
var start = $("#stDate").val();
document.cookie = "std="+start+";time() 3600";
var end = $("#endDate").val();
document.cookie= "end="+ end+";time() 3600";
};
var jsonData = $.ajax({
url: "http://localhost/Insight/mote2/motebymote.php",
type:"GET",
cache: false,
dataType: "json",
success: function(xhr){
console.log(xhr.responseText);
},
error: function(xhr){
console.log(xhr.responseText);
}
});
The php code has "if...== POST"
your javascript ajax call is sending a "GET"
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;
}
}
I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
html() in your function replacing current html with your comment html, thats why u see only new comment. Change your method to append().
$("#comment_part").append(html);
Change this line
$("#comment_part").html(html);
to this
$("#comment_part").html('<div class="comment" >' + $('#userInput').val() + '</div>' + $("#comment_part").html()).promise().done(function(){$('#userInput').val('')});
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.