getting all html in the console trying ajax call with autocomplete - php

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en-us">
<title>PHP MySQL Typeahead Autocomplete</title>
<meta charset="utf-8">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
/*$( "#skills" ).autocomplete({
source: 'singleton.php'
});*/
$("#skills").keyup(function(){
$.ajax({
type: 'post',
url: 'singleton.php/',
data: 'term='+$(this).val(),
success: function(success){
$("#suggesstion-box").html(data);
},
error: function(error){
console.log("error");
}
})
})
});
</script>
</script>
<?php
/*include_once('connection.php');
$conn = new Database();*/
$hostname = "localhost";
$username = "root";
$password = "";
$databasae = "employee";
if(isset($_POST['term'])){
$query = $_POST['term'];
$db = new mysqli($hostname,$username,$password,$databasae);
//get search term
$searchTerm = $_POST['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM city WHERE name LIKE '%".$searchTerm."%' ORDER BY name ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
}
?>
<div class="ui-widget">
Enter City Name:
<input type="text" name="city" class="city" id="skills" placeholder="Enter City Name" id="city">
<div id="suggesstion-box"></div>
</div>
</body>
</html>
I'm getting correct value in the network but it does not populating data in suggestion-box div.
I can't figure out where i'm mistaking.

Is it possible that you accidentally replaced 'data' with 'success' in the 'success' callback?
$("#skills").keyup(function(){
$.ajax({
type: 'post',
url: 'singleton.php/',
data: 'term='+$(this).val(),
success: function(success){
$("#suggesstion-box").html(data);
},
error: function(error){
console.log("error");
}
})
})
Should't it be
success: function(data) {
$("#suggesstion-box").html(data);
}
?

Related

AJAX load to another div with variable

Hey Im trying to load another div with passing variable.
Im in the div#main , I want a after click #modifybtn button pass the btn value and load it with another div#modify and working with some query.
im noob for jQuery and ajax, I search in web but cant get solution for this.
please check relevant code and tell me about issue.
here is the div#main #modifybtn button and div#modify
<div id=main>
<button id="modifybtn" value="some_value" >Modify</button>
</div>
<div id="modify">
<?php
$resultmodi=$conn->query("SELECT * FROM vacancy WHERE vc_id='{$_GET['id']}' LIMIT 1 ");
?>
</div>
dashcompany.php inside
<div class="contentcm" >
//contentcm.php page load content here
</div>
this is my jQuery, after clicking button alert showing but not redirect to the #modify div
$(document).ready(function(){
$('.contentcm').load('contentcm.php #main');
$('a').click(function(){ //main and modify division in contentcm.php
var clickedLink1 = $(this).attr('id');
$('.contentcm').load('contentcm.php #' + clickedLink1);
});
});
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
alert(id);
event.preventDefault();
$.ajax({
url: 'dashcompany.php',
type: 'get',
data: {'id' : id},
success: function(response) {
$('#modify').html(response);
}
});
});
This will be initial.html file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src = "FILE_NAME.js"></script>
</head>
<body>
<div id=main>
<button id="modifybtn" value="some_value" >Modify</button>
<div id="modify"></div>
</div>
</body>
</html>
Your code in FILE_NAME.js should be like
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
alert(id);
event.preventDefault();
$.ajax({
url: 'dashcompany.php',
type: 'get',
data: {'id' : id},
success: function(response) {
$('#modify').html(response);
}
});
Your js file will load the data from dashcompany.php and load in #modify which is in initial.html file
dashcompany.php
<?php
include_once('connection.php');
$id = $_GET['id'];
$resultmodi=$conn->query("SELECT * FROM vacancy WHERE vc_id='$id' LIMIT 1 ");
$row = $resultmodi->fetch_assoc();
echo "Name: " . $row["name"];
''' print data whatever you need '''
$conn->close();
?>
REASON:
May be you forgot to print data in dashcompany.php file that's why you are getting blank response from ajax request.
And don't forget to include #modify div in the same html file where #main#modify div exists
You can use as follow code, and I suggest you to use post method
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<button type='button' id="modifybtn" class='btn btn-info' value="some_value">click here</button>
<div class="" id="modify"></div>
<script type="text/javascript">
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
//alert(id);
$.ajax({
url: 'dashcompany.php',
type: 'post',
data: {'id' : id},
dataType: 'json',
success: function(response) {
//now you can call with column name of data table
$('#modify').html("<P>"+response.column_one_name+"</p><br><P>"+response.column_two_name+"</p>");
}
});
});
</script>
And your dashcompany.php page should like this,
<?php
// $localhost = "127.0.0.1";
// $username = "root";
// $password = "";
// $dbname = "db_304";
//
// $connect = new mysqli($localhost, $username, $password, $dbname);
// // check connection
// if ($connect->connect_error) {
// die("Connection Failed : " . $connect->connect_error);
// }
$id = $_POST['id'];
$sql = "SELECT * FROM vacancy WHERE vc_id = '$id' LIMIT 1 ";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array();
} // if num_rows
$connect->close();
echo json_encode($row);
Hope this will help you.

ajax textbox value no response auto suggestion

I'm trying to create an auto-suggestion AJAX box but there is no response from the server.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<head>
<title></title>
<?php
include 'search.php';
?>
<script>
$(document).ready(function() {
$("#textbox1").keyup(function() {
$.ajax({
type: "GET",
url: "search.php",
data: {textbox1: $(this).val()},
success: function (data) {
$("#main").html(data);
}
});
});
});
</script>
<form method="POST">
enter keyword to search<br>
<input type="text" name="textbox1" id="textbox1">
<br><br>
<div id="main"></div>
</form>
</head>
<body>
this is search.php
<?php
include 'connection.php';
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$search_value = $_POST['textbox1'];
$query = "SELECT username FROM users WHERE username LIKE '" . $search_value . "%'";
$conn_status = mysqli_query($conn, $query);
while($row = $conn_status->fetch_assoc())
{
echo $row['username'] . '<br>';
}
}
?>
You Missed Following
Ajax Request is Get And you use POST request in PHP
Second is not matter but it is good practice if you define action in
Change Code As follow
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<head>
<title></title>
<?php
include 'search.php';
?>
<script>
$(document).ready(function() {
$("#textbox1").keyup(function() {
$.ajax({
type: "POST",
url: "search.php",
data: {textbox1: $(this).val()},
success: function (data) {
$("#main").html(data);
}
});
});
});
</script>
<form method="POST" action="">
enter keyword to search<br>
<input type="text" name="textbox1" id="textbox1">
<br><br>
<div id="main"></div>
</form>
</head>
<body>

Select list first passes others do not

in www.mpoo.org/organizatori/drugi.php have 2 select list, first time work but other no. This is very similar to this.
Second time Debugger say:
TypeError: $(...) is null
drugi.php:37
var country_id = $("select#drop1 option:selected").attr('value');
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Списак организатора</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="style.css" type="text/css" />
<style type="text/css">
<!--
#import url("stil.css");
-->
</style>
</head>
<body>
<div id="body">
<div class="mhead"><h2>Списак организатора</h2></div>
<div id="dropdowns">
<div id="center" class="cascade">
<label>Одабери претрагу:
<select name="country" id = "drop1">
<option value=""> Одабери...</option>
<option value="Grad"> Град/Општина</option>
<option value="Zanimanje"> Занимање</option>
<option value="Struka"> Струка</option>
<option value="Organizator"> Организатор</option>
<option value="Svi"> Сви организатори</option>
</select>
</label>
</div>
<div class="cascade" id="state"></div>
</div>
<div id="city"> </div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("select#drop1").change(function(){
var country_id = $("select#drop1 option:selected").attr('value');
// alert(country_id);
$("#state").html( "" );
$("#city").html( "" );
if (country_id.length > 0 ) {
if (country_id=='Svi'){
$.ajax({
type: "POST",
url: "drugi4.php",
data: "country_id="+country_id,
cache: false,
beforeSend: function () {
$('#state').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
$("#state").html( html );
}
});
}
else {
$.ajax({
type: "POST",
url: "drugi2.php",
data: "country_id="+country_id,
cache: false,
beforeSend: function () {
$('#state').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
$("#state").html( html );
}
});
}
}
});
});
</script>
</body>
</html>
This is drugi2.php
<?php
include("connection.php");
//var_dump($_POST);
$state_id = trim(mysqli_escape_string($con, $_POST["country_id"]));
$sql="SELECT DISTINCT $state_id FROM jom_x1_organizatori ORDER BY $state_id";
$count = mysqli_num_rows( mysqli_query($con, $sql) );
if ($count > 0 ) {
mysqli_set_charset($con, "utf8");
$query = mysqli_query($con, $sql);
?>
<label>
<select name="city" id = "drop2">
<option value="">Одабери...</option>
<?php while ($rs = mysqli_fetch_array($query, MYSQLI_ASSOC)) { ?>
<option value="<?php echo $rs[$state_id]; ?>"><?php echo $rs[$state_id]; ?></option>
<?php } ?>
</select>
</label>
<?php
}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("select#drop2").change(function(){
var state_id = $("select#drop2 option:selected").attr('value')+";"+$("select#drop1 option:selected").attr('value');
// alert(state_id);
if (state_id.length > 0 ) {
$.ajax({
type: "POST",
url: "drugi3.php",
data: "state_id="+state_id,
cache: false,
beforeSend: function () {
$('#city').html('<img src="loader.gif" alt="" width="24" height="24">');
},
success: function(html) {
$("#city").html( html );
}
});
} else {
$("#city").html( "" );
}
});
});
</script>
I think after ajax loading its removing the selected option, therefore you should use:
var country_id = $("#drop1").val();
instead of
var country_id = $("select#drop1 option:selected").attr('value');

Enable Android App to Connect to the Internet

I have created a simple app using Phohegap to retrieve few records frm a remote database using the following index.html:
<!doctype html>
<html><head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="jquery.mobile-1.4.4.min.css">
<script src="jquery-1.11.1.min.js"></script>
<script src="jquery.mobile-1.4.4.min.js"></script>
<script charset="utf−8" type="text/javascript">
function connect(e)
{
var term= {button:e};
$.ajax({
url:'http://dubaisinan.host22.com/reply.php',
type:'POST',
data:term,
dataType:'json',
error:function(jqXHR,text_status,strError){
alert("No Connection");},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
</script>
</head>
<body>
<center><b>My Students</b></center>
<center><input onclick="connect(this.value)" type="button" value="showStudents" /></center>
<center><b>Results</b></center>
<ul data-role="listview" id="result"></ul>
</body>
</html>
And the following reply.php:
<?php
header('Content-Type: application/json');
$link = mysql_connect('host_name', 'user-name', 'password');
if (!$link)
{
$myStudents[] = "No";
die('Could not connect: ' . mysql_error());
}
mysql_select_db("a2808249_db1",$link);
$result = mysql_query("SELECT * FROM Students",$link);
while ($myrow = mysql_fetch_row($result))
{
$myStudents[] = $myrow[1];
}
print json_encode($myStudents);
?>
It works fine on my laptop but when I build it using Phonegap and download the apk file on my Note 3 device, I receive the message "No Connection". It seems that the app is not able to connect to the Internet. The device has Internet connection.
Any help please?
Sinan
Add these lines
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
Also you said you want to retrieve, so this should be a GET call , not POST.
Also use <!DOCTYPE html> (proper coding standard)
Edit : Example GET call
$.ajax({
url: "http://abcd.com",
headers: {
"X-API-KEY": "2b9asdedqedqxdqd7956e6f7a",
"Content-Type": "application/json"
},
type: "GET",
data: fromDatan,
dataType: "JSON",
success: function(fromData, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
});
EDIT : This is a sample code which can POST to a test server
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script language="javascript" type="text/javascript">
<!--
function greeter() {
var accx = 5;
var accy = 6;
var accz = 7;
var output = [];
output[0] = {
name: "Accel_X",
value: accx.toString(), // retrieve x
};
output[1] = {
name: "Accel_Y",
value: accy.toString(), // retrieve y
};
output[2] = {
name: "Accel_Z",
value: accz.toString() // retrieve z
};
var fromData = {};
fromData.output = output;
var fromDatan = JSON.stringify(fromData);
alert(fromDatan);
jQuery.ajax({
url: "http://posttestserver.com/post.php",
type: "POST",
data: fromDatan,
dataType: "JSON",
success: function(fromDatan, status, jqXHR) {
alert(JSON.stringify(fromData));
},
error: function(jqXHR, status) {
alert(JSON.stringify(jqXHR));
}
/*
error:function(jqXHR,text_status,strError){
alert("No Connection");},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}*/
});
return false;
}
//-->
</script>
</head>
<body>
<button onclick="greeter();">Click me</button>
</body>
</html>
I tried with your url, not working. However will let you know if I can

Autocomplete jQuery with mysql database's data

I created this jquery autocomplete but as a result it returns [].
In the users table there are 2 fields: "ID" (int autoincrement) and "Name (varchar)" and are populated.
auto_complete_jquery.html:
<html>
<head>
<title><!-- Insert your title here --></title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<script>
$(function() {
$("#tags").autocomplete({source: "name.php", dataType: 'json'});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
connection.php:
<?php
$hostname="localhost";
$username="root";
$password="";
$conn=mysql_connect($hostname,$username,$password);
$dbs = mysql_select_db("jquery_test",$conn);
if(!$conn)
{
echo("Error connection MySQL.");
exit();
}
?>
name.php:
<?php
$return_arr = array();
$term = $_GET["term"];
include "connection.php";
$result= mysql_query("SELECT * FROM users WHERE MATCH(Name) AGAINST('".$term."*')") or die (mysql_error());
?>
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$row_array['value'] = $row['tagName'];
array_push($return_arr,$row_array);
}
mysql_close($conn);
$json=json_encode($return_arr);
echo $json;
?>
Hope you looking for this,
$( "#PopulateData" ).autocomplete({
minLength:2,
delay: 50,
selectFirst: true,
open: function () {
$(this).data("autocomplete").menu.element.width(409);
},
source:function(request,response){
removeConflict.ajax({
url: 'remotefile.php?list='+$('#PopulateData').val(),
data: request,
dataType: null,
type: "GET",
success: function(data){
var listarray= jQuery.parseJSON(data);
response(
$.map(listarray, function(item) {
var text = item.jsonpropertyA;
var code = item.jsonpropertyb;
console.log(text )
return {
label: code,
value: text
}
})
)},
error:function(data){
console.log(data)
}
});
},
select: function( event, ui ) {
console.log('value:'+ ui.item.value + ',label:'+ui.item.label);
}
});
json object is returned from the server response, and the label and value is returned to the autocomplete text box.
Note: you've can do some modification which suites your. :)

Categories