I have the following javascript,php (idf is an inputbox in html):
JS:
$(document).ready(function() {
// tell the autocomplete function to get its data from our php script
$('#idf').autocomplete({
source: "../php/testingauto.php"
});});
PHP:
<?php
include('connection.php');
session_start();
try{
$q =$conn->query("SELECT ID_farm FROM farm");
$result=$q->fetchAll(PDO::FETCH_ASSOC);
if(count($result)!=0) {
echo json_encode($result);
}
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
And I want to give my JSON result in the auto-complete list.
But I always get a null result on the output of the auto-complete function.
Am I doing something wrong ?
This is the JSON I get from echo: [{"ID_farm":"CYS1000004"},{"ID_farm":"CYS1021009"}]
Any help is appreciated. Thanks.
you need to render correct format from the resource response like the availabletags example, Hope it helps :)
Related
I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.
I have a simple AJAX function bound to a button that should execute a PostgreSQL query. However, when I click the button that I bound the ajax query to, all I get is the confirmation that the database connection was successful. Nothing seems to happen withe the ajax result (should be printing to console in the handleAjax() function. What am I doing wrong?
This is the javascript code (with jquery):
$(document).ready(function() {
function sendAjax() {
$.ajax({
url: "db/database.php",
success: function (result) {
handleAjax(result);
}
});
}
function handleAjax(result) {
console.log(result);
}
$("#submit-button").on("click", sendAjax);
});
And this it the contents of database.php:
<?php
function dbconn(){
ini_set('display_errors', 1); // Displays errors
//database login info
$host = 'localhost';
$port = 5432;
$dbname = 'sms';
$user = 'postgres';
$password = 'postgres';
// establish connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
}
}
$conn = dbconn();
$sql = "SELECT * FROM numbers;";
$result = pg_query( $sql ) or die('Query Failed: ' .pg_last_error());
$count = 0;
$text = 'error';
while( $row = pg_fetch_array( $result, null, PGSQL_ASSOC ) ) {
$text = $row['message'];
//echo $text;
}
pg_free_result( $result );
?>
The problem is in the database.php file, all you get is "Connected." because you don't print your result at the end. Ajax only receive the output of the php file.
So at the end of your php file you should add :
echo $text;
And you also should remove the echo "Connected.";
AJAX is not a magic wand that in magic way reads PHP code. Let's say AJAX is a user. So what does user do.
Open web page
Wait until PHP execute code and display data
Tells you what he sees
If you don't display anything, ajax can't tell you what he saw.
In thi's place is worth to say that the best way to communicate between PHP and AJAX is using JSON format.
Your code generally is good. All you have to do is to display your data. All your data is in your $text var. So let's convert your array ($text) to JSON.
header('Content-Type: application/json');
echo json_encode($text);
First you set content-type to json, so ajax knows that he reads json. Then you encode (convert) your PHP array to js-friendly format (JSON). Also delete unnecessary echoes like 'Conntected' because as I said, AJAX reads everything what he sees.
You should return $conn from dbconn()
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
return $conn;
}
I've create a code that check if a variable is empty or not.
If the variable is empty I execute a javascript alert, in particular:
if($verbo_name == NULL)
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
If I insert a message inside the echo, the message appears correctly, but I want show the alert in javascript. What's the error? Thanks..
UPDATE more details:
$results = $con->query("SELECT verbo, descrizione FROM verbo WHERE verbo = '$verbo'");
$verbo_name = NULL;
while($row = $results->fetch_array())
{
$verbo_name = $row['verbo'];
}
Check below codes are working fine for me.
<?php
$verbo_name = NULL;
if(is_null($verbo_name))
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
?>
Check this one
if(empty($verbo_name))
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
This should trigger an alert:
<html>
<body>
<?php
if($verbo_name == NULL)
{
$msg = enter code here'no record available in the database';
} else {
$msg = 'not set';
}
echo "
<script>
alert('". $msg ."');
</script>";
?>
</body>
</html>
If the message is not set the problem is just the variable.
This is Pravat Kumar Sahoo's answer,
This must work fine.
If you are testing on google chrome, you might have prevented the alert dialog message mistakenly. Please try clearing the cache/cookie or test on any other browser.
<?php
$verbo_name = NULL;
if(is_null($verbo_name))
{
echo "<script>alert('no record available in the database');</script>";
exit();
}
?>
Update:
Instead of alerting the message inside PHP, echo a message, like "NoData". And in the ajax calling Javascript, receive response "success".
echo "NoData"; // In PHP file.
In your Javascript, get the response,
success:function(response)
{
if(response == "NoData");
{
alert("No data in the Database");
}
}
I want to pass a variable in header .if the variable is exist than give an alert.
but its not working
login.php
<?php
include "db.php";
$user=$_POST['t1'];
$pass=$_POST['t2'];
$result=mysql_query("select * from registor where username='$user'")or die(mysql_error());
$row=mysql_fetch_row($result);
if($user=='' || $pass==''){
header("location:account.php?wrong");
}
?>
account.php
<?php
if(isset($_GET['wrong']))
{
?>
<script>alert(Please enter detials !!);</script>
<?php
}
if(isset($_GET['user']))
{
?>
<script>alert(Now, Login Please !!);</script><?php
}
?>
You need quotes around strings :
<script>alert("Now, Login Please !!");</script><?php
But you should have seen the error in the console. Whenever you have something not working client side, always look at the console first.
You're actually passing nothing in your header. Make it like this and it'll work:
header("location:account.php?wrong=wrong");
and use single or double qoutes in your alert message:
<?php
if(isset($_GET['wrong']))
{
?>
<script>alert('Please enter detials !!');</script>
<?php
}
if(isset($_GET['user']))
{
?>
<script>alert('Now, Login Please !!');</script><?php
}
?>
I want to make autocomplete on my form with jQuery. The source taken from json data from php, but i don't use database.
Here is my code :
facebookfriends.php
<?php
include('facebookdata.php');
$user_friend = $user_friends['data'];
$json_friends = json_encode($user_friend);
echo $json_friends;
?>
Script
$(function() {
$( "#search" ).autocomplete(
{
source:'facebookfriends.php',
});
});
JSON DATA
[{"name":"Indiarto Priadi","id":"502163984"},
{"name":"Agustin Kertawijaya","id":"511990261"},
{"name":"Jecklyne Christin L","id":"528197912"},
{"name":"Jazi Eko Istiyanto","id":"531149275"},
{"name":"Esritha Situmorang","id":"535864892"},
{"name":"Christy Margaretha Siregar","id":"543468540"},
{"name":"Daniel Oscar Baskoro","id":"549332828"},
........]
I just want to display the name in autocomplete to ensure that the autocomplete works well. But it doesn't. Please help. Thank you!
1.You have to parse json in php
2.make an array for dropdown list
Following steps to be followed:
$data ='[{"name":"Indiarto Priadi","id":"502163984"},
{"name":"Agustin Kertawijaya","id":"511990261"},
{"name":"Jecklyne Christin L","id":"528197912"},
{"name":"Jazi Eko Istiyanto","id":"531149275"},
{"name":"Esritha Situmorang","id":"535864892"},
{"name":"Christy Margaretha Siregar","id":"543468540"},
{"name":"Daniel Oscar Baskoro","id":"549332828"}]';
$user_friend = json_decode($data, true );
$data=array();
foreach($user_friend as $key=>$val)
$data[]=$val['name'];
$json_friends =json_encode($data);
echo $json_friends;
you need to pass label and value into you php file
For example
$data[] = array(
'label' => $row['city_name'].','.$state['state_name'].','.$c_name['country_name'],
'value' => $row['city_name'].','.$state['state_name'].','.$c_name['country_name']
);
echo json_encode($data);
flush();