Display name one by one using JSON and AJAX - php

How to display name one by one using ajax. It seem that my FOR looping is not working to push name one by one. Is there any step that i miss? Can someone point me to where/what i did wrong.
var names = [];
var profiles = {};
var restURL = "fetch.php";
function refresh() {
$.ajax({
method: 'GET',
url:restURL,
success: function (result, status, xhr) {
for (var k in result) {
var name = result[k].name;
if (!profiles.hasOwnProperty(name)) {
names.push(name);
profiles[name] = result[k];
}
}
}
});
}
var namei = -1;
function nextName() {
namei++;
if (namei > names.length - 1) {
namei = Math.max(1, names.length - 10) - 1;
}
console.log(namei + '/' + names.length);
$('.texts li:first', '.jumbotron #atname').text(profiles[names[namei]].name);
$('.texts li:first', '.jumbotron #atdiv').text(profiles[names[namei]].division);
$('.jumbotron .tlt').textillate('start');
setTimeout(function () {
$('.jumbotron .tlt').textillate('out');
}, 5000);
}
fecth.php
$i=1;
while ( $row = mysql_fetch_assoc($rs) ) {
$response['result'][] = array(
'staffno' => $row['g_idm'],
'name' => $row['g_name'],
'division' => $row['g_div']
);
$i++;
}
echo json_encode($response);

Related

AJAX/PHP Chat refresh

Used AJAX for this chat function, however, it needs to be refreshed to retrieve new chats. I tried using setIntervala and setTimeout. sorry, noob with this.
message.php
$(document).ready(function(){
$("#btn-submit").click(function(e){
e.preventDefault()
var msgg = $("#chat-msg").val();
var href = $('#btn-submit').attr('href');
var ssid = $("#s-id").val();
var rrid = $("#r-id").val();
$.ajax({
method: "POST",
url: "http://127.0.0.1/test/admin/dashboard/ajaxMessage/",
data: {
message: msgg
}
})
.done(function(msg) {
console.log(msg);
$("#chat-msg").val("");
var head;
if (rrid != ssid) {
head = '<br><br><br><h1 class="msg-show-right">';
} else {
head = '<br><br><br><h1 class="msg-show-left">';
}
var chatBubble = head + " " + msgg + "</h1>";
$( ".msg-show-right" ).each(function( index ) {
last_bubble = $(this);
});
last_bubble.after(chatBubble)
});
});
});
dashboard.php
public function ajaxMessage () {
$message = $this->input->post('message');
$s_id = $this->session->userdata('s_id');
$r_id = $this->session->userdata('r_id');
$data = array(
'msg' => $message,
'status' => '1',
's_id' => $s_id,
'r_id' => $r_id
);
$this->admin_model->form_insert($data);
echo "true";
}
there are some unnecessary codes also.

How to test returned json result?

I have an Ajax Request that is getting data from my database, specifically two columns from it, company_id and people_id,
I need to test the result that comes from the json result, I need to check if a specific people_id exists in the result,
Here is my Ajax Request
Ext.Ajax.request({
url: 'system/index.php',
method: 'POST',
params: {
class: 'CompanyPeople',
method: 'secget',
data: Ext.encode({
people_id: Ext.getCmp('peopleGrid').selectedRecord.data.people_id
})
},
success: function (response) {
},
failure: function () {
}
});
I thought I could do this following code in the success function but it didnt work
if (data == 0) {
Ext.MessageBox.alert('Status', 'Person is not attached to anything bud!.');
}
else {
Ext.MessageBox.alert('Status', 'Person already attached to another company.');
}
Also here is my php
class CompanyPeople extends Connect {
function __construct() {
parent::__construct();
}
public function secget($vars) {
$sql = "SELECT * FROM CompanyPeople where people_id={$vars->data->people_id}";
$data = array();
$total = 0;
if ($result = $vars->db->query($sql)) {
while ($row = $result->fetch_assoc()) {
$data[] = array("people_id" => intval($row["people_id"]));
$total++;
}
$result->free();
}
echo json_encode(array("success" => true, "total" => $total, "topics" => $data));
}
}
I think something like this should work:
success: function( response ){
if(response.success === true) {
var personExist = false;
for(var i = 0; i < response.topics.lenght; ++i) {
// Your specific people_id in myValue
if(response.topics[i]['people_id'] === myValue) {
personExist = true;
break;
}
}
}
},

avoiding duplicate mysql injection

I created a controller and called the function for one time.But it call two times and inserted the value two times.I call the service upload_album in controller.Now value got inserted for two times.one with original value and another with dummy value
Controller
$scope.savealbum = function() {
$scope.album_pids = $routeParams.id;
$timeout(function () {
//console.log($scope.justapp);
for (tt in $scope.justapp) {
if ($scope.justapp[tt].id == $scope.album_pids) {
for (var i = 0; i < $rootScope.media_lib.length; i++) {
}
}
}
$scope.promise=AlbumServices.upload_album($scope.album_pids,$scope.images,$scope.videos);
$scope.promise.then(function(data) {
console.log(data);
alert('Photos Added to Album Successfully');
// $location.path('album_details/' + $routeParams.id);
}, function(reason) {
console.log(reason);
});
}, 1500, false);
};
Service
upload_album: function (alb,img,vid) {
var deferred = $q.defer();
var data = {};
data.pagename = "upload_album";
data.album = alb;
data.photo = img;
data.video = vid;
$http.post('js/data/album.php', data)
.success(function (data, status, headers, config)
{
console.log(status + ' - ' + data);
deferred.resolve(data);
})
.error(function (data, status, headers, config)
{
deferred.reject(data);
console.log('error');
});
return deferred.promise;
}
php
function upload_album ($prefix) {
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$sub_id=$request->album;
$val=$request->photo;
$photo = json_encode($val);
$video = json_encode($request->video);
$now = date('Y-m-d H:i:s');
$count_pho = sizeof($photo);
$count_vid = sizeof($video);
$test = '';
if($count_pho != '0' ) {
$test .= "('".$sub_id."','".$content_type."','".$photo."','".$website_id."','".$now."'),";
$demo = substr($test, 0, -1);
$sql="INSERT INTO `album_details` (SUB_ID,CONTENT_TYPE,CONTENT_VALUE,WEBSITE_ID,CreatedTime)VALUES".$demo;
$query = mysql_query($sql) or sqlerrorhandler("(".mysql_errno().") ".mysql_error(), $sql, __LINE__);
}
if ($query) {
echo $msg = true;
} else {
echo $msg = false;
}
}
Because we cannot se the whole code (including the HTML) my suggestions are these:
check your html and/or run method inside angular to be sure that your controller was not instanciated twice
create a unique key pair in your database (it could help not have double records)
create a debouncer when using timeout so that if the timeout is always launched once. something like this:
var t = null;
var mySaveFunction = function () {
if (t) {
clearTimeout(t);
}
t = setTimeout(function () {
/* do saving here */
}, 2000);
};

Flot.js with php and mysql not working with time

I have a system trying to display a graph of a count over time using flot js. The issue I am having is that the graph isnt actually rendering any lines. I have cast the time to UTC and multiplied by 1000 as suggested in other posts but to no avail. Does anyone have any idea what I am doing wrong?
PHP:
public function liveGraphAjax()
{
$query = "SELECT
time as time,
COUNT( id ) as count
FROM table
WHERE HOUR( TIME ) = HOUR( CURRENT_TIME ) -1
GROUP BY DATE_FORMAT(`time`, '%H:%i')";
$result = DB::select($query);
if(isset($result))
{
$temp = array();
foreach ($resultas $row )
{
$temp [] = array(
'time' =>strtotime($row->time) * 1000,
'count' =>(int) $row->count,
);
}
}
return Response::json($temp);
}
JS:
var options = {
colors : [$UpdatingChartColors],
xaxis: {
mode: "time",
timeformat:"%hh:%mm"
},
series: {
lines: { show: true },
points: { show: true }
},
};
$("button.dataUpdate").click(function ()
{
data = [];
$.plot("#updating-chart", data, options);
function fetchData()
{
function onDataReceived(series)
{
var res = [];
data = [series];
for (var i = 0; i < data[0].length; ++i)
{
res.push([data[0][i].time,data[0][i].count]);
}
console.log(res);
$.plot("#updating-chart", res, options);
}
$.ajax({
url: "liveGraphAjax",
type: "GET",
dataType: "json",
success: onDataReceived
});
}
});
The fetchData() function is never called so you never get data.
In your onDataReceived() function the res variable contains only one data series. You have to change your call to $.plot("#updating-chart", [res], options);

Display rows from database in html table using jQuery, Ajax, json

I need some help with the following code. I am trying to query my database using ajax and return the results within a table. The code is executing and I am not getting any errors - I'm just not getting a response. Any ideas? I have a feeling something is messed up with my jQuery function.
Thanks for any help you can give.
My function in my view:
$("#test").click(function() {
var form_data = {
Opportunity_Id: $('#Opportunity_Id').val(),
ajax: '1'
};
$.ajax({
url: "<?php echo site_url('schedule/get_classes'); ?>",
type: 'POST',
data: form_data,
cache: false,
success: function(server_response) {
var data = $.parseJSON(server_response);
for(var i = 0; i < data.length; i++){
week = data[i];
$("table.table").append("<tr><td>" + week.Class_Number + "</td><td>" + week.Class_Date + "</td></tr>");
};
},
error: function(thrownError) {
alert(thrownError);
}
});
return false;
})
My controller:
function get_classes() {
$Opportunity_Id = $this->input->post('Opportunity_Id');
$this->ion_auth_model->get_classes($Opportunity_Id);
foreach ($classes as $class):
$results[] = array(
"Class_Number" => $class->Class_Number,
"Class_Date" => $class->Class_Date,
"Start_Time" => $class->Start_Time,
"End_Time" => $class->End_Time
);
endforeach;
echo json_encode($results);
}
My model:
function get_classes($Opportunity_Id) {
$this->db->select('*')->from('Classes')->where('Opportunity_Id', $Opportunity_Id);
$q = $this->db->get();
if($q->num_rows() > 0) {
foreach($q->result() as $classes) {
$data[] = $classes;
}
return $data;
}
}
I think this maybe your problem, you are returning an array from get_classes($Opportunity_Id) but you have not captured that array when you call it :-
function get_classes() {
$Opportunity_Id = $this->input->post('Opportunity_Id');
$classes = $this->ion_auth_model->get_classes($Opportunity_Id); <--- changed here
foreach ($classes as $class):
$results[] = array(
"Class_Number" => $class->Class_Number,
"Class_Date" => $class->Class_Date,
"Start_Time" => $class->Start_Time,
"End_Time" => $class->End_Time
);
endforeach;
echo json_encode($results);
}

Categories