I have input with id aktForm_tiekejas and is jquery autocomplete code:
$('#aktForm_tiekejas').autocomplete({
serviceUrl: '_tiekejas.php',
width: 185,
deferRequestBy: 0,
noCache: true,
onSelect: function(suggestion) {alert('You selected:'+suggestion.value+','+suggestion.data);}
});
_tiekejas.php:
<?php
include("../Setup.php");
$query = ($_GET['query']);
$reply = array();
$reply['query'] = $query;
$reply['suggestions'] = array();
$reply['data'] = array();
$res = mysql_query("SELECT id,pavadinimas FROM sarasas_tiekejas WHERE pavadinimas LIKE '%$query%' ORDER BY pavadinimas ASC");
while ($row = mysql_fetch_array($res)) {
$reply['suggestions'][] = $row['pavadinimas'];
$reply['data'][] = $row['id'];
}
mysql_close();
echo json_encode($reply);
?>
If query is 'vac' php returns from server:
{"query":"vac","suggestions":["UAB Vivacitas"],"data":["866"]}
but
alert('You selected:'+suggestion.value+','+suggestion.data);
doesn't alert data (866)
why?...
Probably because suggestion.value doesn't exist. Looking at your JSON response code I can see the suggestion.data but no suggestion.value. Since JS will be looking for a value that doesn't exist it will throw an error. Also you're missing out the array for the second part of the return. Try this:
alert('You selected: '+suggestion.data[0]);
If you need to iterate through your data subsets do something like:
for(i in suggestion.data){
alert('You selected: '+suggestion.data[i]);
}
Related
My Alert is showing that updated successfully but data is not updating in database and not able to click ok button of alert. Here is my php code for upresult.php. Hope This will b helpful. Thank you in advance
my jquery
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url:"upresult.php",
type:"POST",
data:formData,
async:true,
success:function(data) {
alert(data);
},
cache:false,
contentType:false,
processData:false
});
});
});
upresult.php
<?php
include("connection.php");
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
$qry="update stud set stud_name='".$name."',mobile='".$mob."',dob='".$dob."',address='".$add."',gender='".$gen."',country='".$cn."',state='".$st."',city='".$ct."' where stud_no='".$no."'";
$data=mysqli_query($conn,$qry);
if($data)
{
echo '<script language="javascript">';
echo 'alert("Updated Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot update record")';
echo '</script>';
}
?>
You want to alert alert. Try with editing your flow control structure like this:
<?php
include("connection.php");
// you need to validate this data before sending it to update query
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
// this parameters should be binded to avoid SQL injection
$query = "
update stud
set
stud_name = '$name',
mobile = '$mob',
dob = '$dob',
address = '$add',
gender = '$gen',
country = '$cn',
state = '$st',
city = '$ct'
where stud_no = '$no';
";
/** This may be query for checking.
* Just execute it after first query and grab response from it.
* Depends of response you will return appropirate text message.
*/
$checkUpdateQuery = "
select if(count(*) = 1, true, false) as response
from stud
where stud_name = '$name',
and mobile = '$mob',
and dob = '$dob',
and address = '$add',
and gender = '$gen',
and country = '$cn',
and state = '$st',
and city = '$ct'
and stud_no = '$no';
";
/** mysqli_query will return false only if some error occurred.
* In other cases you will get true,
* so you need to check if data is updated by another query.
*/
$data = mysqli_query($conn, $query);
echo $data ? 'Updated Successfully' : 'Cannot update record';
Few things you should consider is do you have certain stud_no in database, mysqli_query returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
If you want we can change this query. Can you use PDO instead of mysqli?
Lets say I have this table mytable
id | name | x | y
I pull the the rows from mytable and create JavaScript objects with it like so:
PHP
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<script type="text/javascript">';
echo "new Object({$row["id"]}, '{$row["name"]}', {$row["desk_x"]}, {$row["desk_y"]});";
echo '</script>';
}
}
JS
function Object(id, name, x, y) {
var obj = {
id:id,
name:name,
x:x,
y:y
};
}
At the moment this is fine but lets say I want to add another column color to mytable
Basically I'm asking what do I write in PHP and JS to make this object dynamically, so you can have any columns and the Object object will just add a new property with the name of the column?
You can use AJAX to send data from serverside to clientside. Lets say you have a PHP file called script.php with your code:
if(isset($_GET['action']) && $_GET['action'] == 'testing'){
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo json_encode($result);
}
}
And lets say you have a JS file called script.js. Here you will do your AJAX call towards the PHP script file like this:
$.ajax({
type: 'GET',
url: 'script.php',
data: { action: 'testing' },
success: function(response){
console.log(response); //here you will have access to the object returned from the PHP script
}
})
I guess what you're looking for is how to do this without AJAX (which you don't really need here).
Put the objects in an array, then output your JS variable:
PHP:
$rows = [];
if ($result->num_rows)
while($row = $result->fetch_assoc()) $rows[] = $row; // append to array
echo "<script> var objArray = " . json_encode($rows) . "; </script>";
I have a table:
DB
city
-------
cityID
cityname
store
I have then a form HTML:
<input type="text" class="store">
GOAL:
I would like javascript, after I enter the store, (if the entered value is already in the DB) displays an alert like:
"Store is already entered for the following cities: New York (ID#), Boston(ID#), Springfield(ID#)"
I've tried with a Json file:
<?php include ('connectionlink.php');
$word = $_GET['word'];
$search = "SELECT
store as value,
cityID,
cityname,
FROM city
WHERE store LIKE '%".$word."%'";
$result = mysqli_query($connection, $search);
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['cityID']=$row['cityID'];
$row['cityname']=$row['cityname'];
$row_set[] = $row;
}
echo json_encode($row_set);
?>
And javascript
$(document).ready(function (){
$('.store').on('change', function(){
var storeValue = $('.store').val();
$.post('stores.php',{'word' : storeValue}, function(data) {
alert("Data: " + data);
});
});
});
I feel I'm almost there, because after typing the store I get an alert of Undefined index word error and then the alert displays all the data in my table with the Json format. It's like if it doesn't search just for my word, but just returns everything. Thanks for your help!
You are doing a post request, so read the parameter with $_POST
$word = $_POST['word']
Also make sure that you handle sql injection How can I prevent SQL injection in PHP?
<?php include ('connectionlink.php');
//as you are doing a post request...
$word = $_POST['word'];
$search = "SELECT
store as value,
cityID,
cityname,
FROM city
WHERE store LIKE '%".$word."%'";
$result = mysqli_query($connection, $search);
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC))
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['cityID']=$row['cityID'];
$row['cityname']=$row['cityname'];
$row_set[] = $row;
}
echo json_encode($row_set);
?>
I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}
I have a text field in which i am getting a string like that
say name / contact / address
and i get this value on button click function when i pass this value to php function via ajax. it returns nothing, i don't know what is wrong with my code.
here is the ajax function:
$("#load").click(function()
{
//alert("this comes in this");
var data1 = $("#country_id").val();
$.ajax({
alert("ajax start");
url: 'ajax_submit.php',
type: 'Post',
dataType: 'json',
data:{getRespondents:"getRespondents", data:data1},
success: function(e){
alert(e);
$("#rCategory").val(e.respondents[0]['category']);
$("#gender").val(e.respondents[0]['gender']);
$("#rAddress").val(e.respondents[0]['address']);
$("#rContact").val(e.respondents[0]['contact']);
alert("In this");
}
});
});
and in ajax_submit.php function is like that:
if($_POST["getRespondents"] == "getRespondents"){
$regionID= $_POST["data"];
$obj = new controller();
$result = $obj->getRespondents($regionID);
$json = array("respondents"=>$result);
echo json_encode($json);
exit();
}
In class function is written as:
function getRespondents($a){
$connection = mysql_connect("localhost", "root", ""); // Establishing Connection with Server..
$db = mysql_select_db("demon", $connection); // Selecting Database
list($number1, $number2, $number3) = explode('/', $a);
//$sql = "SELECT r.id, r.name, r.contact, r.address from respondent as r ORDER BY r.name";
$sql = "SELECT * FROM respondent as r WHERE r.name = '".$number1."' and r.contact = '".$number2."' and r.address = '".$number3."' "
$rsd = mysql_query($sql);
$row= array();
$i=0;
while($rs = mysql_fetch_array($rsd)) {
$row[$i]["id"] = $rs ['id'];
$row[$i]["name"] = $rs ['name'];
$row[$i]["contact"] = $rs ['contact'];
$row[$i]["address"] = $rs ['address'];
$row[$i]["category"] = $rs ['category'];
$row[$i]["gender"] = $rs ['gender'];
$i++;
}
return $row;
}
I want to populate those values in given select boxes when user selects something from autocomplete function.
what are possible soultions to this problem? thanks
First of all why you use alert at the beginning of ajax? remove that alert because it might give you JavaScript error.