Ajax request working but no output - javascript

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;
}
}

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 SQL JAVASCRIPT SEARCH NOT WORKING

I am working on a company website where a search bar is used to search the database of customers and employees by there name.
I have the output of the below code (output 1)
but it only searches the firstname and last name individually like this in the output (output 4)i want to make it join together for searching both firstname and lastname.
I want to make a search like this (output 3)
I have this code so far...
index.php
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>INDEX PAGE</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container all">
<br />
<h2 align="center">COMPANY NAME</h2><br />
<div class="form-group">
<div class="input-group">
<input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
</div>
</div>
<div id="result"></div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search.length>=2){
if(search != '')
{
load_data(search);
}
}
else
{
load_data();
}
});
});
</script>
and 2nd file..
fetch.php
<?php
$connect = mysqli_connect("localhost", "root", "root", "users_db")or die("ERROR");
$output = '';
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM users_users
WHERE firstname LIKE '%".$search."%'
OR lastname LIKE '%".$search."%'
AND lastname LIKE '%".$search."%'
OR link LIKE '%".$search."%'
";
}
else
{
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<div class="otp">
</div>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<div class="oup">
<a href="
'.$row["link"].'
">
'.$row["firstname"].'
'.$row["lastname"].'
</a>
</div>
';
}
echo $output;
}
else
{
echo '';
}
?>
the above code has this output...(output 1)
output 1
and after typing the firstname when i press spacebar it blanksout like in (output 2)
output 2
i want to make the search continue after typing the firstname with spacebar in between..
something like this.. in the (output 3)
output 3
i am new at php javascript and sql so try to break it down for me.
thank you in advance.
can you guys give me some more tricks how to optimise more of this code.
Before i give my answer, I should say your code is open to SQL Injection. You should learn about Prepared Statements to solve this security issue.
Now to answer your question. For searching both firstname and lastname you should separate search term before searching. Something like this:
// --- Separate the search items
if ( !empty($search) ){
$searchWords = explode(' ', $search);
$searchTerms = array();
foreach ($searchWords as $word) {
$word = trim($word);
if (!empty($word)) {
$searchTerms[] = "(firstname LIKE '%$word%' OR lastname LIKE '%$word%')";
}
}
}
// --- Search each search items
$query = "SELECT * FROM users_users WHERE".implode(' AND ', $searchTerms);
Try this:
ALTER TABLE users_users ADD FULLTEXT(firstname, lastname, link);
$searchTerm = '+'.str_replace(' ','+',$search).'*';
$query = "SELECT * FROM users where MATCH(`firstname`,`lastname`,`link`) AGAINST (".searchTerm." IN BOOLEAN MODE)";

"$.get" for retrieving information

I'm trying to get a simple javascript popup script going anytime the database is updated in real-time. I'm not sure as to what to do next, because I'm still a newbie with jQuery and ajax, but the following code is what I have right now:
PHP MySQL query page:
<?php
$con = mysqli_connect('localhost','root','root','mydb');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"mydb");
$sql = "SELECT * FROM incoming_calls";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
//$callArray = array('phonenumber' => $row['phone_number'], 'id' => $row['phone_login_id']);
if(!empty($row)) {
$number = $row['phone_number'];
}
}
$sql="SELECT Username, Password FROM tblUsers WHERE PhoneHome='$number' OR PhoneCell='$number' OR PhoneWork='$number'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$userArray = array("username" => $row['Username'], "password" => $row['Password']);
//echo json_encode($userArray);
}
echo json_encode($userArray);
mysqli_close($con);
?>
HTML page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Phone calls</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
function getCall(){
$.get("phonecall.php", function(data){
var loginInfo = jQuery.parseJSON(data);
var user = loginInfo.username;
var pass = loginInfo.password;
$('#username').html(user);
$('#password').html(pass);
});
/*$.getJSON("phonecall.php", function(data){
for (var i=0, len=data.length; i < len; i++) {
$('#username').html(data);
}
});*/
}
setInterval(getCall,5000);
</script>
<div id="username"></div>
<div id="password"></div>
</body>
</html>
One of the problems I am having is that when there are 2 or more users with the same phone number for say like a house phone, depending on where the json_encode is, will either return the last entry in the table, or return nothing at all. If the json_encode is in the while loop, I can check the console, it says the information is being retrieved, but something must not be right with my "$.get" syntax to allow more than one entry to be displayed. Any ideas?
You're only ever saving one row of data:
while($row = mysqli_fetch_array($result)) {
$userArray = array("username" etc...
^^^^---here
If you have multiple rows of data, each row you fetch will overwrite the previous row in $userArray.
You probably want
$userArray[] = array("username" etc...
^^---- note these
so you're creating an array of results.
You'll also have to modify your JS code to accept an array of arrays, since right now you only handle one username/password.

jQuery json/jsonp does not fetch items on php server

I have a web service written in php but I could not fetch data with jquery getJSON().
It's my web service and works fine.
<?php
include 'config.php';
$sql = "select s.id, s.title, s.content, s.date, s.confirm " .
"from sap s";
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$sapList = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
header('Content-Type: application/json; charset=UTF8');
$data = array('items'=>$sapList);
echo json_encode($data,JSON_UNESCAPED_UNICODE);
//echo '{"items":'. json_encode($sapList,JSON_UNESCAPED_UNICODE) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
I am trying to develop a jQuery mobile app.and source codes:event.js I used for loop in event.js.because I want to pull data from multiple separate services.
var db=openDatabase('servicesDB','1.0','servcesdatabase', 2*1024*1024);
tablo();
var olaylar;
$('#eventListPage').bind('pageinit', function(event) {
console.log("geteventlist fonksiyon running");
getEventList();
});
function getEventList() {
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM services',[],function (tx,sonuc) {
var toplam=sonuc.rows.length;
var kayit="";
var id="";
var ad="";
var url="";
$('#olaylar li').remove();
for (var i=0;i < toplam; i++) {
kayit=sonuc.rows.item(i);
id=kayit.id;
ad=kayit.ad;
url=kayit.url;
$.getJSON(url+'?callback=?', function(data) {
olaylar = data.items;
$.each(olaylar, function(index, olay) {
/*var confirm="";
switch(olay.confirm){
case 0:
confirm="accept";
break;
case 1:
confirm="wait";
break;
case 2:
confirm="reject";
break;
}*/
$('#olaylar').append(
'<li><a href="eventDetails.html?id=' + olay.id + '">' +
'<img src="pics/mr.jpg"/>' +
'<h4>' + olay.title + '</h4>' +
'<p>' + olay.confirm + '</p>' +
'</a></li>');
});
$('#olaylar').listview('refresh');
alert("getjsondan cikti");
});
}
}, hata);
});
}
function tablo(){
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS services('
+'id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,'
+'ad VARCHAR(25) NOT NULL, url VARCHAR(100) NOT NULL)');
});
}
function hata(transaction, err){
alert("Hata oldu : "+err.message);
return false;
}
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Personel Listesi</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="css/styles.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.4.3.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.4.3.min.css" />
</head>
<body>
<div id="eventListPage" data-role="page">
<div data-role="header" data-position="fixed">
<h1>Event List</h1>
</div>
<div data-role="content">
<ul id="olaylar" data-role="listview" data-filter="true"></ul>
</div>
</div>
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/jquery.mobile-1.4.3.min.js"></script>
<script src="js/events.js"></script>
<script src="js/eventDetails.js"></script>
</body>
</html>
I tried $.getJSON(...){ alert("in getjson"); but that does not work. this alert.getjson function does not work. But it works very well before, now the getjson function returns blank as if no data has been retrieved.. I need your help,thanks!
I am little doubt about '{"items":'. json_encode($sapList,JSON_UNESCAPED_UNICODE) .'}'. I am not sure whether the above piece of code frame proper json.
The better way is create your JSON structure in PHP associate array itself and then generate the JSON in single stroke like as follows,
<?php
// Some code
$data = array('item'=>$sapList);
echo json_encode($sapList);
?>
Note: Since I haven't tested my code and it is GET request, you can test your code by directly type the URL in browsers address-bar. And copy and paste printed code in chrome's console and validate them in Javascript.
OR
Use online JSON validator like http://jsonlint.com/

I have a faulty Ajax call apparently

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.

Categories

Resources