So i have a php file, that prints data from a table encoded on JSON format.
This is the php file:
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo "success";
else
echo "error";
}
echo json_encode($data);
?>
This is the javascript script:
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
if (data == "success") {
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
});
} else if (data == "error") {
alert("error");
}
}
});
});
So basically i a have where i have all items from the database select (list_all.php), and then when i click on a single item, the ID of that item is passed on the URL, and i retrieve it on the otherside with javascript. I dont use GET because this is with phonegapp, so i use a .js file called getURI.js.
First, the function gets the ID that was passed. Then it posts to the PHP file, and the PHP file will get the ID, and make the query for that single item on the database. Is successed, i wanted to store all that data on variables. But for some reason, im getting an error on the console saying
POST http://192.168.1.241:3000/proxy/http%3A%2F%2Fpedrofidalgo.pt%2Fbilapoint%2Flistar_sitio_single.php 500 (Internal Server Error)
THe server is responding correctly because others scripts on the app are working.
In PHP
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo json_encode(array('status' => true, 'data' => $data));
else
echo json_encode(array('status' => false, 'data' => $data));
?>
In Jquery
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
data = JSON.parse(data);
if (data['status']) {
$.each(data['data'], function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
} else {
alert("error");
}
}
});
});
Related
I need a sanity check here. I'm posting data through an AJAX call but for some reason it comes through as null.
javascript:
var data = {};
data['pkStudyYears'] = id;
data['years'] = [];
data['years']['pkStudyYears'] = id;
data['years']['fkStudyID'] = $('#fkStudyID').val();
data['action'] = action;
data['years']['intStartYr'] = $('#startYearBox').val();
data['years']['intEndYr'] = $('#endYearBox').val();
console.log(data['years']);
var posturl = '<?php echo site_url('manage/climate_indicators/updateStudyYears');?>'
$.when($.ajax({
type: "POST",
url: posturl,
data: data,
dataType: 'json'
}))
.done(function(result) {
console.log(result.status);
if (result.status === 'failed') {
console.log(result.errors);
}
});
php (updateStudyYears)
$postData = $this->input->post(NULL, true);
$yearArray = $postData['years'];
if(empty($yearArray)) {
echo json_encode(array('status'=>'failed', 'errors'=>'Years are empty'));
exit();
}
I keep getting a failed result with the error "Years are empty". I can't figure out what I'm missing!
I am working with OT system.i have some problem regrading OT hours request program.this program send the department employee OT hours in to the admin panel notification and OT hours save in the database.my problem is when send OT request each person create the separate OT notification .I want send the single notification set of the department people.
$(document).on('click', '.overtime_send', function() {
temp = 0;
$('#employee_table tbody tr').each(function(row, tr) {
var emp_no = $(tr).find('td:eq(0)').text();
var ot_hours = $(tr).find('input').val();
//ot_array.push([emp_no,ot_hours]);
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_ot',emp_no : emp_no, ot_hours:ot_hours},
dataType:"json",
success:function(data)
{
if(data.success)
{
swal("Good job!", "OverTime Request Send Successfully!", "success");
temp = 1;
dataTable.ajax.reload();
}
}
});
});
alert(temp);//if data.success block execute but alert still get value as 0
if (temp == 1) {
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_comment'},
dataType:"json",
success:function(data)
{
if(data.success)
{
dataTable.ajax.reload();
}
}
});
}
i all ready got some solution .i get create the temp variable and OT request process successful it assign temp = 1 and after the each loop i try to insert notification data into the database.but if data.success success but alert(temp); not get value as 1 .how do i solve this question.
back end code
if($_POST["action"] == 'add_ot')
{
$today = date("Y-m-d");
$department = $_SESSION["dept_Id"];
$state = 5 ;
$emp_no = $_POST["emp_no"];
$ot_hours = $_POST["ot_hours"];
if($ot_hours != '00:00'){
$data = array(
':today' => $today,
':department' => $department,
':emp_no' => $emp_no,
':ot_hours' => $ot_hours,
':state' => $state
);
$query = "
INSERT INTO otresquest
(emp_id,date,ot_hour,dept_Id,overtime_status)
VALUES (:emp_no, :today, :ot_hours,:department,:state)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$output = array(
'success' => 'OT request has been Sent succesfully',
);
}
}
echo json_encode($output);
}
if($_POST["action"] == 'add_comment')
{
$today = date("Y-m-d");
$department = $_SESSION["dept_Id"];
$comment_status = 0 ;
$data = array(
':today' => $today,
':department' => $department,
':state' => $comment_status
);
$query = "
INSERT INTO comments
(dept_Id,date,comment_status)
VALUES (:department,:today,:state)
";
$statement = $connect->prepare($query);
$statement->execute($data);
}
**This might be solve your problem**
(document).on('click', '.overtime_send', function() {
temp = 0;
$('#employee_table tbody tr').each(function(row, tr) {
var emp_no = $(tr).find('td:eq(0)').text();
var ot_hours = $(tr).find('input').val();
//ot_array.push([emp_no,ot_hours]);
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_ot',emp_no : emp_no, ot_hours:ot_hours},
dataType:"json",
success:function(data)
{
swal("Good job!", "OverTime Request Send Successfully!", "success");
temp++;
dataTable.ajax.reload();
if (temp == 1) {
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_comment'},
dataType:"json",
success:function(data)
{
if(data.success)
{
dataTable.ajax.reload();
}
}
});
}
}
});
});
swal({title: "No data entering?",text: "Not set the overtime hours !",type: "warning"});
});
JS : Fixed by godot!
/* Data Delete Starts Here */
$(".delete-file").click(function()
{
var name = $(this).attr("name");
var file_id = $(this).attr("id");
var active_user = document.getElementById("username").value;
if(confirm('Sure to Delete ' +name+ '?'))
{
$.ajax({
url: 'suf-delete.php',
type: 'post',
async: false,
data: {'file_id':file_id ,'active_user':active_user},
success: function(response){
$("#file_table"+file_id).fadeOut('slow');
},
error: function(error){
console.log(error.responseText);
//you could debug your php code if some error raises
}
});
}
return false;
});
/* Data Delete Ends Here */
PHP: Working Fine (suf-delete.php)
elseif($_POST['file_id'] && $_POST['active_user'])
{
$file_id = $_POST['file_id'];
$active_user = $_POST['active_user'];
$crud->filesDelete($file_id,$active_user);
}
Im now having a problem with my class crud.
I think Its just my query. Im trying to make activity log, delete, select and unlink Item using my code provided below.
Please check this:
Class Crud
public function filesDelete($file_id,$active_user)
{
$stmtFiles = $this->conn->prepare('SELECT * FROM tbl_files WHERE file_id=:file_id');
$stmtFiles->execute(array(":file_id"=>$file_id));
$unFile=$stmtFiles->fetch(PDO::FETCH_ASSOC);
$userStmt = $this->conn->prepare('SELECT * FROM tbl_login WHERE username=:username');
$userStmt->execute(array(":username"=>$active_user));
$fetch = $userStmt->fetch(PDO::FETCH_ASSOC);
$activity = "Deleted the file ".$unFile['file_name'];
if($fetch['access_type']=="Design2K18ADMIN") {
$type = "Administrator";
}
elseif ($fetch['access_type']=="Design2K18MANAGER") {
$type = "Manager";
}
elseif ($fetch['access_type']=="Design2K18MODERATOR") {
$type = "Moderator";
}
elseif ($fetch['access_type']=="Design2K18SIMPLE") {
$type = "Simple";
}
$actLog = $this->conn->prepare("INSERT INTO activity_log(username, activity, type) VALUES(:username, :activity, :type)");
$actLog->execute(array(":username"=>$active_user, ":activity"=>$activity, ":type"=>$type));
$stmtSelFol = $this->conn->prepare('SELECT * FROM tbl_section WHERE sec_id=:sec_id');
$stmtSelFol->execute(array(":sec_id"=>$unFile['sec_id']));
$unFol=$stmtSelFol->fetch(PDO::FETCH_ASSOC);
unlink("../Files/".$unFol['sec_folder']."/".$unFile['file_name']);
$stmtDelFile = $this->conn->prepare('DELETE FROM tbl_files WHERE file_id=:file_id');
$stmtDelFile->execute(array(":file_id"=>$file_id));
return true;
}
I have confirm that My js and php works fine by saving the logs in error.php
I save the value of file_id and active_user in my error.txt file.
9Daren appears which is the value(id) of Item and the current session user is Daren.
Please help me check my public function why It does not do anything.
I would use ajax:
/* Data Delete Starts Here */
$(".delete-file").click(function()
{
var name = $(this).attr("name");
var file_id = $(this).attr("id");
var active_user = document.getElementById("username").value;
if(confirm('Sure to Delete ' +name+ '?'))
{
$.ajax({
url: 'suf-delete.php',
type: 'post',
async: false,
data: {'file_id':file_id ,'active_user':active_user},
success: function(response){
$("#file_table"+file_id).fadeOut('slow');
},
error: function(error){
console.log(error.responseText);
//you could debug your php code if some error raises
}
});
}
return false;
});
/* Data Delete Ends Here */
I'm new to ajax so I'm not sure if i'm approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far...
onInit: function() {
window.fcWidget.on('widget:loaded', function() {
window.fcWidget.user.get().then(function(resp) {
var status = resp && resp.status,
data = resp && resp.data;
if (status === 200) {
if (data.restoreId) {
// Update restoreId in database
$.ajax({
type: "POST",
url: "insert.php",
data: data.restoreId,
success: function(data) { alert("Success"); },
failure: function(data) { alert("Failure"); }
})
}
}
});
});
}
I have placed the file "insert.php" in the same folder but it seem like it doesn't get called at all...
This is what insert.php looks like
<?php
if(Mage::getSingleton('customer/session')->isLoggedIn()){
if(isset($_POST['data.restoreId']){
$restoreId =$_POST['data.restoreId'];
}
$first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
$last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();
$fullName = $first . "." . $last;
//get resource model
$resource = Mage::getSingleton('core/resource');
//retrieve write connection
$writeConnection = $resource->getConnection('core_write');
//read connection
$readConnection = $resource->getConnection('core_read');
$exId = $fullName;
$resId = $restoreId;
$testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";
$result = $readConnection->fetchAll($testQuery);
if(count($result) == '0'){
$query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
$writeConnection->query($query);
}else{
//echo "nope";
}
}
?>
I checked the network tab but insert.php doesn't seem to be called at all, what is wrong with my code?
//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.
url: "www.yourwebsite.com/insert.php",
I am using CI 3.0.1 was uploading and inserting image to db successfully before i used ajax, i guess trying to do it with ajax i'm missing something which isn't even sending data to upload maybe because we have to use multipart() in form while in ajax we are just sending data direct to controller, another thing i don't know how to receive the variable in response
my Ajax request function is:
<script type="text/javascript">
$(document).ready(function() {
alert("thirddddddddd");
$('#btnsubmit').click(function()
{
alert("i got submitted");
event.preventDefault();
var userfile = $("input#pfile").val();
alert("uploading");
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload', //how to receive var here ?
type: 'POST',
cache: false,
data: {userfile: userfile},
success: function(data) {
alert(data);
$('.img_pre').attr('src', "<?php echo base_url().'uploads/' ?>");
$('.dltbtn').hide();
},
error: function(data)
{
console.log("error");
console.log(data);
alert("Error :"+data);
}
});
});
});
And my controller Upload's function do_upload is:
public function do_upload()
{
$config['upload_path'] = './uploads/'; #$this->config->item('base_url').
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('layouts/header');
$this->load->view('home_page', $error);
$this->load->view('layouts/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$imagedata = $this->input->post('uerfile');
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$result = $this->model_edit->update_dp($id, $imagedata);
$image_name = $result->images;
$this->session->set_userdata('image', $image_name);
echo json_encode($name = array('image' => $image_name));
// $image_name = $this->upload->data('file_name');
// $data = array('upload_data' => $this->upload->data());
// redirect("account");
}
}
Now image is not even going to uploads folder, if any other file is needed tell me i'll post it here. Thanks
You cannot send file data using $("input#pfile").val();
var len = $("#pfile").files.length;
var file = new Array();
var formdata = new FormData();
for(i=0;i<len;i++)
{
file[i] = $("input#pfile").files[i];
formdata.append("file"+i, file[i]);
}
and send formdata as data from ajax
Hope it helps !
Try with the below ajax code
var formData = new FormData($('#formid'));
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload',
data: formData ,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
The file contents may not send through ajax as per your code. Try with the attributes mentioned in above code.