I am trying to make a user search system like facebook using ajax and php json. But i have one problem.
From the data users table have Marc Zuckerberg, Marc Zeyn, Marc Alp. I mean 3 user first name is same, so normaly when i write the Marc name then i should be get all Marc names from data. Like
<div class="ul">Marc Zuckerbert</div>
<div class="ul">Marc Zeyn</div>
<div class="ul">Marc Alp</div>
but i am not getting all Marc names just i am getting one marc result. Chrome developer console show me all Marc name but not show my within HTML. I think i need some code from ajax success.
JS
$('body').delegate('#searchkey','keyup', function(){
clearTimeout(timer);
timer = setTimeout(function(){
var box = $('#searchkey').val();
contentbox = $.trim(box);
var dataString = 'keys=' + contentbox;
if(contentbox !==''){
$.ajax({
type: "POST",
url: siteurl +"requests/search.php",
data: dataString,
dataType:"json",
cache: false,
beforeSend: function(){},
success: function(data){
$('.un').html(data.username);
$('.uf').html(data.fullname);
}
});
}
});
});
search.php
<?php
include_once 'inc.php';
if(isset($_POST['keys'])) {
$keys = mysqli_real_escape_string($db, $_POST['keys']);
$keyRestuls = $WidGet->SearchUser($keys);
if($keyRestuls) {
// If array is in data
foreach($keyRestuls as $datas) {
$dataUsername = $datas['username'];
$dataUserID = $datas['fullname'];
$data = array(
'username' => $dataUsername,
'fullname' => $dataUserID
);
echo json_encode( $data );
}
}
}
?>
SearchUser function is here
public function SearchUser($keys){
$keys = mysqli_real_escape_string($this->db, $keys);
$result = mysqli_query($this->db,"SELECT
username,
uid,
fullname FROM
users WHERE
username like '%{$keys}%' or fullname like '%{$keys}%'
ORDER BY uid LIMIT 10") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
}
Your PHP script is generating a malformed JSON
{"username":"marc1","fullname":"Marc Zuckerberg"}
{"username":"marc3","fullname":"Marc Zeyn"}
{"username":"marc2","fullname":"Marc Alp"}
It shoulds generate
[
{"username":"marc1","fullname":"Marc Zuckerberg"},
{"username":"marc3","fullname":"Marc Zeyn"},
{"username":"marc2","fullname":"Marc Alp"},
]
You can fix it by appending to an array instead of writting each row independamently
foreach($keyRestuls as $datas)
{
$dataUsername = $datas['username'];
$dataUserID = $datas['fullname'];
$data[] = array(
'username' => $dataUsername,
'fullname' => $dataUserID
);
}
echo json_encode( $data );
And then you'll have to loop over $data in your JS, I suggest you use $.each
function success(data) {
$.each(data, function(key, value) {
console.log(value.username + ": " + value.fullname);
})
}
Related
How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.
I'm looking to make an ajax call to a PHP script to get data from MySQL, create a json array and pass it back to the success function of the ajax call, where i will then use it as parameters for a JavaScript function.
This is my ajax call,
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr"); // Find the row
var $tenant_id = $row.find(".col-md-1 id").text(); // Find the tenants ID
var $landlord_id = "<?php echo $id; ?>"
$.ajax({
url : "./message.php",
type : "POST",
async : false,
data: {
landlord_id: $landlord_id,
tenant_id : $tenant_id
},
success: function(data){
console.log(data);
var messages = data;
insertChat(messages.sender_id, messages.body, messages.timestamp);
}
})
});
And this is my PHP file,
<?php
session_start();
require_once('../dbconnect.php');
// update tenants table to show deposit returned
if(isset($_POST['tenant_id'])){
$tenant_id = $_POST['tenant_id'];
$landlord_id = $_POST['landlord_id'];
$sql = "SELECT * from messages WHERE messages.sender_id OR messages.receiver_id = '$tenant_id' AND messages.sender_id OR messages.receiver_id = '$landlord_id'";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$messages = array();
while($row =mysqli_fetch_assoc($result))
{
$messages[] = $row;
}
echo json_encode($messages);
}
?>
If anybody has a link to a tutorial or the individual parts that would be fantastic. I don't even know if the process i have outlined above is correct.
If anybody could tell me the correct way to go about this that would be of great help!
Thanks
Just a few things to adjust your javascript side (I won't explain the php sql injection issue you have... but please research prepare, bind_param and execute):
Since you are returning an ARRAY of $messages from php (json_encoded), you need to loop on those in your success handler.
Add dataType: 'JSON' to your options, so it explicitly expects json returned from php.
And you were missing a couple semicolons ;)
Adjustments added to your code:
$('button[name="message"]').click(function() {
var $row = $(this).closest("tr");
var tenant_id = $row.find(".col-md-1 id").text();
var landlord_id = "<?php echo $id; ?>";
$.ajax({
url : "./message.php",
type : "POST",
data: {
landlord_id: landlord_id,
tenant_id : tenant_id
},
dataType: 'JSON',
success: function(data){
console.log(data);
if (typeof data !== undefined) {
for(var i = 0; i < data.length; i++) {
insertChat(data[i].sender_id, data[i].body, data[i].timestamp);
}
}
}
});
});
I'm using PHP and trying to get values from a MySQL database using jQuery/AJAX.
My mysql table has four columns: id, tail, cg and cw
My php code looks like this:
<?php
$inputvalue = $_POST;
$errors = false;
$result = false;
$mysqli = new mysqli('localhost', "root", "", "tp");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
foreach ($inputvalues as $key => $value) {
if(isset($value) && !empty($value)) {
$inputvalues[$key] = $mysqli->real_escape_string( $value );
} else {
$errors[$key] = 'The field '.$key.' is empty';
}
}
if( !$errors ) {
$addresult = "
SELECT *
FROM `air_cg`
WHERE `tail` = '" . $inputvalue['tail'] . "'
ORDER BY `id` DESC
";
if( $result = $mysqli->query($addresult) ) {
// collect results
while($row = $result->fetch_all())
{
$returnResult = $row;
}
}
}
mysqli_close($mysqli);
echo json_encode(['result' => $returnResult, 'errors' => $errors]);
exit;
?>
The resulting JSON has this format:
{"result":[["255","Lapdogie","1","2"],["254","Lapdogie","23","234"],["253","Lapdogie","132","454"]],"errors":false}
My javascript code that im using for the ajax function and to parse the resulting JSON looks like this:
function getcgdata(aa){
$.ajax({
type: "POST",
url: "drawchart.php",
data: {tailnumber:taildata},
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
var chartdata=(value);
var cgdata =(cg.value);
console.log(chartdata);
console.log(cgdata);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The console log for chartdata shows this:
["256", "Lapdogie", "232", "333"]
["239", "Lapdogie", "23", "12"]
["238", "Lapdogie", "1232", "1232"]
The console log for cgdata only shows one value many times:
232
232
232
I am not sure if the issue is with my PHP code or with the way im trying to parse the JSON.
i dont see that you define cg.value..
you use
var cgdata =(cg.value);
but cg is where defined?
it should be probably something like chartdata[3] .. ?
Rajdeep Paul's suggestion below worked for me for this particular situation:
Change
var cgdata =(cg.value);
to
var cgdata = value[2];
I'm aware that there are many issues with my code as pointed out by Ludovit Scholtz and Magnus Eriksson and I shall refine it at a later stage.
Thank you all!
this is my code for in php file from which i recall a refresh php again nd again its working fine but now i have $id which i get while performing some query now i want to send it refresh.php page where some query will be performed then i get result back as return
function repeatAjax(){
var arrPoints;
$.ajax({
url: 'refresh.php',
cache: false,
success: function(result) {
if(result){
var resultJson = $.parseJSON(result);
refresh_point(resultJson["latitude"],resultJson["longitude"]);
}
}
}); }
this is my refresh.php page
<?php
$hostname_localhost ="localhost";
$database_localhost ="map";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
//i want $id here so i can use it instead of 6
$query_search1 = "SELECT lat ,lng FROM van WHERE id =6";
$query_exec2 = mysql_query($query_search1) or die(mysql_error());
$row = mysql_fetch_assoc($query_exec2);
$row1= $row['lat'];
$row2= $row['lng'];
$advert = array(
'latitude' => $row['lat'],
'longitude' => $row['lng'],
);
echo json_encode($advert);
?>
code is working awesome if i don't want to send some thing to refresh php if i just type id 6 i get the return OK fine but i want to post some thing but how ??
function repeatAjax(){
var arrPoints;
var id = '6';
$.ajax({
url: 'refresh.php',
data: id,
cache: false,
success: function(result) {
if(result){
var resultJson = $.parseJSON(result);
refresh_point(resultJson["latitude"],resultJson["longitude"]);
}
}
});
}
In php file you can recive vairable like below
$id=$_POST['id'];
My PHP query is running fine(based on the response on firebug) but the result its giving me are [object Object] on my direct page. So I'm guessing that my problem lies on my javascript because on firebug under the response tab its retrieving all my data on my database
Here is my javascript
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.ajax({
url: "includes/getChat.php",
type: "GET",
data: data,
dataType: 'json',
success: function(result){
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}
});
}
The php script as requested is this
$sql7 = "SELECT message_content, username , message_time, recipient FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$message_query = $stmt7;
$json = array();
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
echo json_encode($json);
}
I'm not that familiar yet on JQUERY/AJAX/Javascript so I'm not actually sure if what I'm doing is correct I just based some of my codes on jquery's documentation and some
suggestions from our fellow members here
The way your constructing the json data is wrong,try this way
$json =array();
$i=0;
if($message_query->rowCount() > 0) {
while($message_array = $stmt7->fetchAll(PDO::FETCH_ASSOC)) {
$json[$i]= $message_array;
$i++;
}
echo json_encode($json);
}
Happy Coding :)
Change your success callback like below, you have an array of objects.
success: function(result){
var container = $("#clog");
$.each(result, function(i, message) {
$.each(message, function(key, value) {
container.append($('<div />').html(key + ':' + value));
});
});
}
Edit:
And you have to change fetchAll to fetch in you while loop.
while($message_array = $stmt7->fetch(PDO::FETCH_ASSOC)) {
$json[] = $message_array;
}
echo json_encode($json);
Or just use fetchAll without while loop:
$json = $stmt7->fetch(PDO::FETCH_ASSOC);
echo json_encode($json);