Hello I have a textbox and when I type something in it should update the page with the mySQL data via AJAX.
So Im trying to get live updated database results whenever you type something in the textbox. The goal is to get a textbox that is getting data from the mySQL database.
I have written the code so far, hopefully someone can advise me in this mather, thank you.
$select = 'SELECT *';
$from = ' FROM overboekingen';
$where2 = ' WHERE naam_klant LIKE % . $val . % ';
$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
$val = (isset($_POST['txt']) ? $_POST['txt'] : FALSE);
if (is_array($opts) || $val) {
$where = ' WHERE FALSE';
if (in_array("naam_klant", $val)){
$where2.val;
}
}
else {
$where = false;
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
AJAX
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {text: val},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
You must define the PHP $val variable before.
The correct sytax:
$where2 = " WHERE naam_klant LIKE %$val% ";
Related
I wrote the following code snippet for Ajax connections, but unfortunately the return value is not displayed in the output, but it does not give a special warning to understand the meaning. Please help.
js
$("#search").on('keyup', function(){var value = $(this).val();
$.ajax('feed.php',{
type: 'POST',
dataType: 'json',
data: {
keyword: value
},
success: function(data){
$("#pre").html(data);
}
});
});
feed.php
<?php
require_once('main.php');
$db = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $db->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$out['html']= '';
foreach($records as $record){
$out['html'] .= $record['word'] . '<br>';
}
echo json_encode($out);
?>
js:
jQuery('#search').on('keyup', () => {
jQuery.ajax({
url: 'feed.php',
type: 'POST',
data: { keyword: jQuery(this).val() },
success: response => {
jQuery('#pre').html(response);
}
});
});
feed.php
<?php
require_once('main.php');
$database = Db::getInstance();
$keyword = $_POST['keyword'];
$records = $database->query("SELECT * FROM dic_word WHERE word LIKE '%$keyword%'");
$output = '';
foreach($records as $record){
$output .= $record['word'] . '<br />';
}
echo($output);
?>
PS: You don't need to use json output absolutly. But if there is coercion to using json output, the problem is 2 following items:
You don't set the output "Content-Type" to json: header('Content-Type: application/json');
You shouldn't pass the json object to html method in jQuery and should parsing it at first with JSON.parse(response) class, then with foreach, for or anything else process it
I am searching this and other sites for hours now, so I'm getting pretty desperate. No code from many questions with the same topic here works.
I need to insert data into the database and display a message after it is done. Also, I am using AJAX with jQuery so it would be asynchronous. It works just fine, the data gets inserted, but no response message shows.
I am a beginner at PHP and can't understend why this won't work. Relevant code below.
PHP function call:
if(isset($_POST["function"]) && !empty($_POST["function"]) && $_POST["function"] == "cl-add") {
$dbb->addMember("MyUsername", $_POST["name"]);
//$dbb is a DataBaseBroker instance
}
PHP function from the Broker:
function addMember($username, $ime) {
$query = "INSERT INTO clan";
$query.=" (username, ime) ";
$query.="VALUES ('".$username."','".$ime."');";
$result = $this->mysqli->query($query);
if ($result) {
echo("You added a member: ".$ime);
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: ".mysqli_error($connection);
echo $response;
}
}
JQuery function declarations:
var addMember = function(name, responseFn) {
if (name === "") {
alert("Please enter a name");
return;
}
$.ajax({
type : 'POST',
url: '../includes/layout/cl.php',
dataType : 'json',
data : {
'name' : name,
'function' : 'cl-add'
},
success : function(data) {
responseFn(data); //not working, should alert
}
});
}
var responseCallback = function(data) {
alert(data);
}
And inside $(document).ready():
$(document).on('click', '#cl-add', function(evt) {
var name = $("#cl_frm input").val();
addMember(name, responseCallback);
});
On your code:
dataType : 'json',
The Ajax request is waiting for a JSON response but you are giving a text response.
You should change the dataType: to text or html depending on your needs.
dataType : 'html',
or
dataType : 'text',
PHP changes:
<?php
function addMember($username, $ime)
{
$query = "INSERT INTO clan";
$query .= " (username, ime) ";
$query .= "VALUES ('" . $username . "','" . $ime . "');";
$result = $this->mysqli->query($query);
$response = null;
if ($result) {
$response = "You added a member: " . $ime;
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: " . mysqli_error($connection);
}
echo $response;
exit;
}
Change dataType parameter to 'text'. Also you can alert an object in JavaScript, actually you are not trying to alert an object but i just wanted to mention it.
I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.
Using a few answers on here I have got row being added to MySQL upon a button press but the data is blank and so I can only assume the variables are not being passed.
I really don't know what I am doing wrong, any help would be greatly appreciated.
PHP
<? $sql = "SELECT itemname FROM items ORDER BY itemname ASC";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo "<button onclick='javascript:ajaxCall(" . $row['id'] . ")'><span class='btn-text'>" . $row['itemname'] . "</span></button>";
}
?>
jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function ajaxCall(id){
$.ajax({
type: "POST",
url: "additem.php",
success: function(data){
// callback function
}
});
return false;
}
</script>
additem.php
// Connect database.
include("settings.php");
mysql_connect($db_host,$db_user,$db_pass);
mysql_select_db($db_name);
$id = $_POST['id'];
$itemsearch = mysql_query("SELECT itemname, itemcategory, price, qty FROM presales WHERE id='$id'");
$itemsearchrest = mysql_num_rows($itemsearch);
$itemname = $itemsearchrest['itemname'];
$itemcategory = $itemsearchrest['itemcategory'];
$price = $itemsearchrest['price'];
$qty = $itemsearchrest['qty'];
$sql = "INSERT INTO presales (itemname, itemcategory, price, qty) VALUES('$itemname', '$itemcategory', '$price', '0')";
if(mysql_query($sql)){
return "success!";
}
else {
return "failed!";
}
?>
mysql_num_rows returns the number of rows. It's not an array. Use fetch_assoc or similiar.
See sample in the PHP documentation!
Also your AJAX call is missing the data:
$.ajax({
type: "POST",
url: "additem.php",
data: {
id: id
}
});
Please switch to PDO or MySQLi. MySQLi will use the same function names but it is object orientated. PDO will name the functions slightly different but basically work the same way.
I am trying to retrieve a row from mysql db using ajax, code bellow:
jQuery.ajax({
type: 'POST',
url: 'Connection.php',
dataType: 'text',
data: {'query_id' : query_id},
success: function(response){
data = response;
alert(data['username']); //print undefined!!!
},
error: function(xhr, ajaxOptions, thrownError){
alert("thrownError");
}
});
Here is my mysql php code:
<?php
$con = mysql_connect('****','****','****');
mysql_select_db("eBay",$con);
$username = $_SESSION['username'];
$query_id = $_POST['query_id'];
$myquery = "SELECT * FROM `Output` WHERE `username` =" '$username';
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
}
$data = mysql_fetch_array($query);
echo ($data);
mysql_close($server);
?>
In the response I get, I have undefined array cell. Any idea?
to return just the username from php:
$data = mysql_fetch_assoc($query)['username'];
in your javascript you should be able to do alert(data) instead of searching for the username tuple in an array.
Ideally you should return your data back in json instead of text that way it can remain structured and easier to access in javascript. You will need to change your ajax option to dataType: 'json'
and the PHP code to :
$data = json_encode(mysql_fetch_assoc($query));
You are getting array in $data variable so you should use json_encode function to get all values from resulting row like this-
$myquery = "SELECT * FROM `Output` WHERE `username` ='".$username."'";
foreach ($myquery as $test)
{
$field1_value =$test->name_of_field1_in_db;
$field2_value =$test->name_of_field2_in_db;
$field3_value =$test->name_of_field3_in_db;
}
$all_values_in_array=array('field1'=>$field1_value,'field2'=>$field2_value,'field3'=>$field3_value,);
echo json_encode(echo json_encode($arr_provider);
and get all value on ajax suucess function like this--
success: function(response){
var pro = jQuery.parseJSON(response);
var field1_val=pro.field1; //var field1 contain value of field1 in db
var field2_val=pro.field2;
var field3_val=pro.field3;
},
hope it will help you.
Best of Luck