I have troubles with JQuery and Ajax forms. I'm new in Ajax and Jquery. I'm creating a webapp with a search form. The data I'm fetching from MYSQL Database. So I have a request page with a form, then the mysql processing file, a javascript to return the requested data and a html file, where the results are displayed. So, my problem is, that I can't display the results under index.html. Therefore I tried to action directly to landmarks.php and there I can see the reuslts in array like this
([{"id":"1","name":"Big Ben","latitude":"51.500600000000","longitude":"-0.124610000000"}]);
The request.html file
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<form method="post" action="landmarks.php">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
<label for="l_name"><b>Name</b></label>
<input type="text" name="l_name" id="l_name" value="" />
<input class="submit" type="submit" value="Submit" />
</fieldset>
</div>
</form>
</body>
Then this file for mysql
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "test";
$password = "test132";
$database = "landmarks";
$l_name = $_POST["l_name"];
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT id, l_name AS name, l_lat AS latitude, l_long AS longitude FROM landmarks WHERE l_name like '".$l_name."' ORDER BY l_name";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
my json callback looks like this
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'landmarks.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.name+'</h1>'
+ '<p>'+item.latitude+'<br>'
+ item.longitude+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.')
}
});
});
and finally my final page, where the results should be displayed
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Updated - loading external data into a PhoneGap app using jQuery 1.5</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="js/load-json.js"></script>
</head>
<body>
<div id="output"></div>
</body>
</html>
Related
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"
This is my page and I want to pass my php variable witch is number from my sql database to html script function. If i replace values with anything it ruin everything. If I fetch data from input it works fine. Sql part work and I can display data through php echo but i cant pass it to html script function.
I use template chart to display my data from mysql on my webpage. All i need to do is pass my php values (that part works) to .myfunc on the bottom. In other words I need to change myValues, and myValues2 with my php values (that part i didnt figure up)
<?php
$db_host = 'localhost'; // Server Name
$db_user = 'root'; // Username
$db_pass = ''; // Password
$db_name = 'esp8266_baza'; // Database Name
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$conn) {
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
$sql = 'SELECT vrijeme_unosa, temp, hum from temp_hum where p_key = (SELECT MAX(`p_key`) FROM `temp_hum`)';
$query = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($query);
$ptemp = $row['temp'];
$phum = $row['hum'];
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<html>
<head>
<link href="css/meter.css" rel="stylesheet" type="text/css" />
</head>
<body>
<br>
<?php echo $ptemp;
echo $phum; ?>
<br>
<input id="myValues" />
<br>
<input id="myValues2" />
</body>
<script src="js/jquery.js"></script>
<script src="js/temp.js"></script>
<script type="text/javascript">
$("#myValues").myfunc({divFact:2,eventListenerType:'keyup'});
$("#myValues2").myfunc({divFact:2,eventListenerType:'keyup'});
</script>
</html>
Why not do everything in php echo? That way you can use all variables.
echo "
<script>
$jsvar = $row[varhere]
</script>
";
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 am trying to autocomplete using bootstrap typeahead but its not fetching results.
i tried many times using jquery,ajax
index.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="typeahead.js"></script>
<script>
$(function() {
$('#typeahead').typeahead({
source:function(typeahead,query)
{
$.ajax({
url :'mysql.php',
type :'POST',
data :'query=' + query,
dataType :'json',
async :false,
success:function(data)
{
typeahead.process(data);
}
});
}
});
});
</script>
</head>
<body>
<input type="text" name="term" id="typeahead" class="form-control" size="50" placeholder="Search" >
</body>
</html>
mysql.php
<?php
$conn = mysqli_connect('localhost', 'root','','mydb');
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$searchTerm = $_POST['query'];
$query = mysqli_query($conn,"SELECT * FROM content_ref_table WHERE title LIKE '%{$searchTerm}%' ORDER BY title ASC");
while ($row = mysqli_fetch_assoc($query)) {
$data[] = $row['title'];
}
echo json_encode($data);
?>
i am using typeahead along with ajax call,but its not giving results
I believe you are using bootstrap3-typeahead / or another bootstrap 2.x typeahead deriviation? If so, you have messed up the arguments for the source method - it should be process, query where process is the async callback. Your code could be reduced to
$('#typeahead').typeahead({
source: function(query, process) {
var url = 'mysql.php?query=' + query
return $.get(url, {}, function(data) {
return process(data)
})
}
})
Im trying to read data from mysql database and pass it to my javascript file.
I have search alot on internet and have found examples that doesnt work in my case.
.html file
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>Display Page</title>
</head>
<body>
<button type='button' id='getdata'>Get Data.</button>
<div id='result_table'>
</div>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$('#getdata').click(function(){
alert("hello");
$.ajax({
url: 'db.php',
type:'POST',
dataType: 'json',
success: function(output_string){
alert(output_string);
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
});
});
</script>
</body>
</html>
and .php file
<?php
echo 'hello';
$user = 'root';
$pass = '123';
$host = 'localhost';
$db = 'internetProgrammeringProj';
$connect = mysql_connect($host,$user,$pass);
$select = mysql_select_db($db,$connect);
$query = $_POST['query'];
$mysql_query = mysql_query("SELECT * FROM ratt ");
$temp = "";
$i = 0;
while($row = mysql_fletch_assoc($mysql_query)){
$temp = $row['id'];
$temp .= $row['namn'];
$temp .= $row['typ'];
$temp .= $row['url'];
$temp .= $row['forberedelse'];
$array[i] = $temp;
$i++;
}
echo json_encode($array);
?>
alert(xhr.statusText); gives parsererror
and
alert(thrownError); gives SyntaxError: JSON.parse: unexpected character
firebug doesnt display any error in console.
QUESTION: How do i get my program to get the content from the database and pass it with json to display it with alert in ajax?
I just successfully ran this code.
All I had to do is remove the echo "hello" at the beginning which messes up your JSON.
Some more tips you can use for future development:
Don't use alert('message'). Use console.log('message'). You can view the output of console.log in "Developer's Area". In chrome you simply press F12. I think that in FF you need to install firebug or something.
output_string in function success is actually an object.
The "Developer's Area" in chrome also lets you see the response from backend. If you have used it you could have seen your output is hello{ "key":"value"} and immediately notice the nasty hello in the beginning. Read more about it at http://wiki.mograbi.info/developers-tools-for-web-development