I have a javascript function which gets user info from database via ajax. It has following code.
var temp_id = new Object;
function checkRequests() {
$.ajax({
url: "bin/inc/classes/mechanism_class.php",
type: "POST",
data: {'checkrequest': '1'},
success: function(data1) {
for(var i=0; i<jQuery.parseJSON(data1).length; i++) {
$.ajax({
url:"bin/inc/classes/mechanism_class.php",
type: "POST",
data: {'checkrequest2': jQuery.parseJSON(data1)[i]},
success: function(data) {
requestPopper(data);
}
}).error(function() {
});
}
}
}).error(function() {
});
}
function requestPopper(data) {
var id = jQuery.parseJSON(data)[0];
var firstname = jQuery.parseJSON(data)[1];
var lastname = jQuery.parseJSON(data)[2];
var imagedir = jQuery.parseJSON(data)[3];
var imageext = jQuery.parseJSON(data)[4];
var imgsrc = 'uploads/'+imagedir+'/'+'thumbs/'+imagedir+'size2.'+imageext;
if($('#'+'requests_content_'+id).length == 0) {
if($('.requests_content').length == 0) {
$('#requests').after('<div id="dropdown_1"><div class="requests_content" id="requests_content_'+id+'"><a id="senders_name" href='+'profile.php?user='+id+'>'+firstname + ' ' +lastname+'</a><div id="acceptbutton">Accept</div><div id="rejectbutton">Reject</div></div></div>');
temp_id.id = id;
} else {
$('#'+'requests_content_'+temp_id.id).after('<div class="requests_content" id="requests_content_'+id+'"><a id="senders_name" href='+'profile.php?user='+id+'>'+firstname + ' ' +lastname+'</a><div id="acceptbutton">Accept</div><div id="rejectbutton">Reject</div></div>');
}
}
}
Also, the PHP class that handles ajax requests has the following code
class RequestsAndAlerts {
public function hasRequests() {
if(isset($_POST['checkrequest'])) {
$current_user = $_SESSION['cred_regiden'];
$query1 = "SELECT * FROM `requests` WHERE `ReqReceiver` = '$current_user' ORDER BY `sentdatetime` DESC";
$senders = array();
if($query_run1 = mysql_query($query1)) {
while($res = mysql_fetch_assoc($query_run1)) {
$sender = $res['ReqSender'];
array_push($senders, $sender);
}
}
echo json_encode($senders);
}
}
public function sendRequestInfo() {
if(isset($_POST['checkrequest2'])) {
$sender = $_POST['checkrequest2'];
$current_user = $_SESSION['cred_regiden'];
$info_request_senders = array();
$query1 = "SELECT * FROM `user_credentials` WHERE `cred_regiden` = '$sender'";
$query2 = "SELECT * FROM `prof_image` WHERE `cred_regiden` = '$sender'";
if($query_run1 = mysql_query($query1)) {
while($res = mysql_fetch_assoc($query_run1)) {
$info1 = $res['cred_regiden'];
$info2 = $res['cred_fname'];
$info3 = $res['cred_lname'];
array_push($info_request_senders, $info1);
array_push($info_request_senders, $info2);
array_push($info_request_senders, $info3);
}
}
if($query_run2 = mysql_query($query2)) {
while($res2 = mysql_fetch_assoc($query_run2)) {
$info4 = $res2['image_dir'];
$info5 = $res2['image_extension'];
array_push($info_request_senders, $info4);
array_push($info_request_senders, $info5);
}
}
echo json_encode($info_request_senders);
}
}
$RAA = new RequestsAndAlerts;
$RAA->hasRequests();
$RAA->sendRequestInfo();
Now, I want to extract the data of people who has sent current user a friend request. For testing purpose I sent the user1 two friend requests from user2 and user3 and log in from user1 account, when I press requests button, on first click user1's info div is at the top and user2's info div is at the bottom.. This is good up to here.. But when I click again, they swap places.. But they do it in irregular pattern. I don't want this to happen. I want the user1 to always be on the top and user2 to be on the bottom of him according to as whose request is sent first. But I did this in mysql.. I arranged the requests in DESC order in mysql.. It should have arranged the div as "user1 on top" and "user2 on bottom".. But this happens randomly.
I guess this is due to the fact that json_encode randomizes the indexes of array.. But I'm not sure.. Help me guys... Just point out where I'm wrong.
The problem is with your multiple ajax call.
Note that ajax is asynchronous HTTP request
For example you have user1 and user2, in the for loop first ajax call will be initialized for getting the user1 details, hence ajax is a asynchronous it will not wait for that requst. Tt will send next the ajax request immediately for getting the user2 results.
If request 2 completes before req1 .Then you will get the above error.
Solution:
1. Get the user details in the first ajax call itself.
Or
2 .Make the second ajax call as a synchronous.
I choose the first option.
Related
I am trying to update a php function using ajax.
I Have an array stored in localstorage.
The array contains values of clicked id's.
When I click the <tr>, the array gets updated and sent via ajax from a js file to the php file.
js file
function storeId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
if (ids.indexOf(id) === -1) {
ids.push(id);
localStorage.setItem('reportArray', JSON.stringify(ids));
}else{
//remove id from array
var index = ids.indexOf(id);
if (index > -1) {
ids.splice(index, 1);
}
localStorage.setItem('reportArray', JSON.stringify(ids));
}
return id;
}
//ajax function
$('table tr').click(function(){
var id = $(this).attr('id');
storeId(id);
var selected_lp = localStorage.getItem('reportArray');
console.log(selected_lp);
var query = 'selected_lp=' + selected_lp;
$.ajax({
type: "POST",
url: "../inc/updatelponadvdash.php",
data: { selected_lparr : selected_lp},
cache: false,
success: function(data) {
return true;
}
});
});
updatelponadvdash.php file
<?php
require_once 'inc.php';
$selected_lparr = json_decode($_POST['selected_lparr']);
foreach($selected_lparr as $value){
$dbData = $lploop->adv_lploops($value);
}
?>
Now, in the chrome network tab, when I click the and I dump_var($selected_lparr) the array is updated and I see the values like this:
For some reason I get a 500 error.
As well I dont understand why the var_dump(inside the function below) dosent work. I seems that the function adv_lploops dosent get the variables. but i dont understand why.
This is the fuction I call:
public function adv_lploops($value){
$sql = "SELECT * FROM `lptitels` WHERE titleidNo = '$value'";
$row = $sql->fetch(PDO::FETCH_ASSOC);
var_dump($row);
}
You aren't executing the sql query, try the following:
$sth = $db->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
note: you will need the $db object which is a connection to your database
This is the view page code in code Igniter.
I am able to populated the second drop down(worker Id) but the problem is, only first data is being fetched. As it has more than 50 worker, only 1 worker id is being fetched.
$(document).ready(function() {
$('#name_of').change(function() {
var Worker_id = $('#name_of').val();
$.ajax({
type:'POST',
data:{data:Worker_id},
dataType:'text',
url:"<?php echo base_url(); ?>supply_chain/get_filtered_names_for_time_card",
success:function(result) {
result = JSON.parse(result);
$('#Worker').empty();
for(i in result) {
$('#Worker').append("<option value='"+result[i]['Worker_id']+"'>"+result[i]['Worker_id']+" "+result[i]['Worker_name']+"</option>")
}
}
});
});
});
This is the Controller function for above View through which I am trying to get all workers related to that required company name.
public function get_filtered_names_for_time_card() {
$id = $this->input->post('data');
$companyName = $this->supply_model->get_all_names_for_time_card();
for($i = 0;$i < sizeof($companyName);$i++){
if($companyName[$i]['company_name'] == $id){
$data['companyNameOptions'] = [$companyName[$i]];
break;
}
}
echo json_encode($data['companyNameOptions']);
}
It would be a much better idea to make the query select only the row you want but your problem with the code you have written is you over writing the data each time round your loop
Also once you find a company_name you want you terminate the for loop with a break so you will only ever add one to the resulting $data array
public function get_filtered_names_for_time_card()
{
$id = $this->input->post('data');
$companyName = $this->supply_model->get_all_names_for_time_card();
for($i = 0;$i < sizeof($companyName);$i++){
if($companyName[$i]['company_name'] == $id){
$data['companyNameOptions'][] = $companyName[$i];
// note here ^^
//break;
}
}
echo json_encode($data['companyNameOptions']);
}
Also the $data array does not need to have a sub array so above code can be written more simply and clearly as
public function get_filtered_names_for_time_card()
{
$id = $this->input->post('data');
$companyName = $this->supply_model->get_all_names_for_time_card();
for($i = 0;$i < sizeof($companyName);$i++){
if($companyName[$i]['company_name'] == $id){
$data[] = $companyName[$i];
}
}
echo json_encode($data);
}
And in your javascript, if you are returning JSON then tell the ajax call that you are doing that and you can forget about the JSON.parse()
$(document).ready(function(){
$('#name_of').change(function(){
var Worker_id = $('#name_of').val();
$.ajax({
type:'POST',
data:{data:Worker_id},
//dataType:'text',
dataType:'json',
url:"<?php echo base_url(); ?>supply_chain/get_filtered_names_for_time_card",
success:function(result)
{
//result = JSON.parse(result);
$('#Worker').empty();
for(i in result){
$('#Worker').append("<option value='"+result[i]['Worker_id']+"'>"+result[i]['Worker_id']+" "+result[i]['Worker_name']+"</option>")
}
}
});
});
});
I am using PHP function to display geofences. I want to pass javascript variable to php function in same file without page refresh.
function load(id,type){
if(type===2){
window.location.href="basic.php?idd=" + id; // i want to change code here
<?php
$cir = get_fence_by_type($_GET['idd']);
if($cir) {
foreach($cir as $row){
$fence_id = $row['geo_id'];
}
}
?>
PHP function is:
function get_fence_by_type($id){
$query = "Select * from geofence where geo_id=".$id;
$result = pg_exec($query);
$d = array();
while($myrow = pg_fetch_assoc($result)) {
$d[] = $myrow;
}
return $d; //returns result in array
}
javascript window.location.href passes javascript value to php function but it reloads page also.
If you're using jQuery, you can use $.ajax(). It allows you to send data to your server and do something with the response.
Eg:
$.ajax({
type: 'POST',
data: myvar
success: function(Response) { console.log(Response); }
});
will send myvar to your server (with a bit of tweaking of parameters of course) and log whatever the server sends back to your browser console.
Have a read of what you can do with jQuery.
You can do this using jQuery. Basically you don't refresh the page, you just do an async query to the server and you get the response. In the following example the response is showed in alert box.
Your "index" file:
function load(id,type)
{
$.post("basic.php", { idd: idd }, function(data){
alert(data);
});
}
and basic.php
<?php
function get_fence_by_type($id){
$query = "Select * from geofence where geo_id=".$id;
$result = pg_exec($query);
$d = array();
while($myrow = pg_fetch_assoc($rs)) {
$d[] = $myrow;
}
return $d;
}
$cir = get_fence_by_type($_GET['idd']);
if($cir) {
foreach($cir as $row){
$fence_id = $row['geo_id'];
}
}
?>
i wish to fetch the values to be edited, in the textbox, i.e. 1st the textboxes will be empty, then when user clicks on the edit link the values should be filled in the textbox. User can change the values, click on save button and the new values will be updated. following is the code:
html code:
Save
controller:
$scope.fetch = function(id) {
var elem = angular.element($element);
var dt = $(elem).serialize();
dt = dt+"&id="+id;
dt = dt+"&action=fetch";
alert(dt);
console.log($(elem).serialize());
$http({
method: 'POST',
url: 'php/products.php',
data: dt,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status) {
//~ $scope.status = status;
//~ $scope.data = data;
$scope.rs = data;
console.log($scope.rs); // Show result from server in our <pre></pre> element
}).error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
products.php:
if($action == 'fetch') {
$query = '
SELECT
*
FROM
product
WHERE
`product_id` ="' . $_POST['id'] . '"
';
$result = mysql_query($query) OR die(mysql_error());
$data = array();
$row = mysql_fetch_assoc($result);
echo json_encode($row);
//print_r($row);
}
this code is not working- when user clicks on edit link of any user, the textboxes get filled with the value- Object object. If ti print the value then it gets printed but when i try to assign it to the textbox, it gets filled with Object object.
where am i getting wrong? how do i solve this?
Don't use jQuery to get/set fields anymore if you're using Angular.
<input type="text" ng-model="field1">
Controller:
//set
$scope.field1 = obj.field1;
//get
var f1 = $scope.field1;
You forgot to use the angular.fromJson function when receiving the response
.success(function(json, status) {
data=angular.fromJson(json);
//~ $scope.status = status;
//~ $scope.data = data;
$scope.rs = data;
console.log($scope.rs); // Show result from server in our <pre></pre> element
})
You might want to take a look into AngularPHP and save some time,
i have a login box...
when the user starts typing.. i want to check whether the LOGIN NAME entered exists in the database or not...
if the login name is exist i am going to set the login button active... if it doesnot exist i am going to set the login button deactive...
offcourse i am going to need AJAX to perform my mySQL via PHP tough i don't know how it will be done...
lets say this is my query
<?php
$result = mysql_query("SELECT * FROM accounts WHERE name='mytextboxvalue'");
?>
how to do it
keep it simple:
$(document).ready(function(){
var Form = $('#myForm');
var Input = $('input.username',Form)
Input.change(function(event){
Value = Input.val();
if(Value.length > 5)
{
$.getJSON('/path/to/username_check.php',{username:Value},function(response){
if(response.valid == true)
{
Form.find('input[type*=submit]').attr('disabled','false');
}else
{
Form.find('input[type*=submit]').attr('disabled','true');
}
});
}
});
});
and then PHP side..
<?php
//Load DB Connections etc.
if(!empty($_REQUEST['username']))
{
$username = mysql_real_escape_string($_REQUEST['username']);
if(isset($_SESSION['username_tmp'][$username]))
{
echo json_encode(array('valid' => (bool)$_SESSION['username_tmp'][$username]));
die();
}
//Check the database here... $num_rows being a validation var from mysql_result
$_SESSION['username_tmp'][$username] = ($num_rows == 0) ? true : false;
echo json_encode(array('valid' => (bool)$_SESSION['username_tmp'][$username]));
die();
}
?>
You can use JSON-RPC, here is implementation in php.
and in JQuery you can use this code.
var id = 1;
function check_login(){
var request = JSON.stringify({'jsonrpc': '2.0',
'method': 'login_check',
'params': [$('#login_box').val()],
'id': id++});
$.ajax({url: "json_rpc.php",
data: request,
success: function(data) {
if (data) {
$('#login_button').removeAttr('disabled');
} else {
$('#login_button').attr('disabled', true);
}
},
contentType: 'application/json',
dataType: 'json',
type:"POST"});
}
and in php
<?php
include 'jsonRPCServer.php';
//mysql_connect
//mysql_select_db
class Service {
public function login_check($login) {
$login = mysql_real_escape_string($login);
$id = mysql_query("SELECT * FROM accounts WHERE name='$login'");
return mysql_num_rows($id) != 0;
}
}
$service = new Service();
jsonRPCServer::handle($service);
?>
Look at jQuery AJAX and jQuery TypeWatch
But like #halfdan said, this is a potential security risk. I have never seen a site do this with a username, only with search results.
Your potentially giving away an end point (URL) on your web site which anyone could query to find out if a username is valid. Intranet or not, it is a risk.