post in my js wont work - javascript

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 */

Related

Issue transferring data from ajax to PHP

I'm trying to send an associative array of key-value pair from client(javascript) to server(php). The size of the array or the values are not fixed. Need to forward the user selected options from one page to another. Not using forms
Tried using ajax, but php does not receive the array correctly. Using php7, jquery 2.4.1, sql server, javascript
javascript/jquery
var contributeArr = {};
$(document).on("change", ".contribute_txt", function() {
// some other code
contributeArr[this.id] = this.value;
});
$('#contri_submit').click(function(e) {
e.preventDefault();
var error = false;
var contributeArray = JSON.stringify(contributeArr);
var url = 'chapter.php';
var formData = new FormData();
if (error == false) {
formData.append("contributeArray", contributeArray);
}
else {
console.log("Something went wrong. Check your code.");
}
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
$.ajax({
type: "POST",
url: url,
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(result) {
window.setTimeout(function() {
window.location.href = url;
}, 2000);
},error: function(xhr,request,error) {
alert(error);
}
});
return false;
});
php
foreach ($_POST['contributeArray'] as $key => $value) {
$_SESSION['contribution'][$key] = $value;
}
print_r($_SESSION['contribution']);
print_r($_POST);
Sample data from console log:
contributeArray, {"LECH":"10","MASC":"20","PMEM":"30","LVME":"50"}
note: not sure what // some other code is... assuming you have everything correct there for your purposes
and assuming you are validating your $_POST data...
var contributeArr = {};
$(document).on("change", ".contribute_txt", function() {
// some other code
contributeArr[this.id] = this.value;
});
$('#contri_submit').click(function(e) {
e.preventDefault();
var my_url_value = 'chapter.php';
var real_url_to_ajax_app = 'https://realdomain.com/realfile.php';
$.ajax({
type: "POST",
url: real_url_to_ajax_app,
data: contributeArr,
success: function(result) {
window.setTimeout(function() {
window.location.href = my_url_value;
}, 2000);
},error: function(error) {
console.log(error);
}
});
return false;
});
in your PHP:
// assuming you are initializing $_SESSION['contribution'] per your needs
foreach ($_POST as $key => $value) {
// validate key/value here
$_SESSION['contribution'][$key] = $value;
}
echo 'some helpful response';
exit; // required
Please use json_decode and include latest jQuery.
I can solve your code if you did not solved yet

Magento insert data into database through ajax

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",

Post to php file, and retrieve data with javascript

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");
}
}
});
});

Ajax PHP Follow Script - Nothing stored in the database

I recently discovered a treehouse blog on ajax for beginners http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php I've been looking for a follow script for a while and I've hit a dead end. Currently the follow button fades as it should do, yet no values are stored in the database as of yet.
Profile.php (follow button):
<div id="followbtncontainer" class="btncontainer">Follow</div>
Ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
type: 'post',
data: {'action': 'follow'},
success: function(data, status) {
if(data == "ok") {
$('#followbtncontainer').html('<p><em>Following!</em></p>');
var numfollowers = parseInt($('#followercnt').html()) + 1;
$('#followercnt').html(numfollowers);
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
$('body').on('click', '#morefllwrs', function(e){
e.preventDefault();
var container = $('#loadmorefollowers');
$(container).html('<img src="images/loader.gif">');
var newhtml = '';
$.ajax({
url: 'ajax-followers.php',
type: 'post',
data: {'page': $(this).attr('href')},
cache: false,
success: function(json) {
$.each(json, function(i, item) {
if(typeof item == 'object') {
newhtml += '<div class="user"> <img src="'+item.profile_pic+'" class="avi"> <h4>'+item.username+'</h4></div>';
}
else {
return false;
}
}) // end $.each() loop
if(json.nextpage != 'end') {
// if the nextpage is any other value other than end, we add the next page link
$(container).html('Load more followers');
} else {
$(container).html('<p></p>');
}
$('#followers').append(newhtml);
},
error: function(xhr, desc, err) {
console.log(xhr + "\n" + err);
}
}); // end ajax call
});
});
ajax.php
<?php require 'database.php' //<?php include 'session-check-index.php' ?>
<?php include 'authentication.php' ?>
<?php
session_start();
$follower=$_SESSION['id'];
$sql = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($database,$sql);
$rws = mysqli_fetch_array($result);
$following=$rws['id'];
/**
* this script will auto-follow the user and update their followers count
* check out your POST data with var_dump($_POST)
**/
if($_POST['action'] == "follow") {
$sql=" INSERT INTO `user_follow` (`follower`, `following`, `subscribed`) VALUES ('$follower', '$following', CURRENT_TIMESTAMP);"
/**
* we can pass any action like block, follow, unfollow, send PM....
* if we get a 'follow' action then we could take the user ID and create a SQL command
* but with no database, we can simply assume the follow action has been completed and return 'ok'
**/
mysqli_query($database,$sql) or die(mysqli_error($database));
}
?>
I'm not sure if the actual $following and $follower values are causing the problem, and just not passing any data. Any help would be much appreciated, thanks!
try to change in ajax.js
$(function(){
$('#followbtn').on('click', function(e){
e.preventDefault();
$('#followbtn').fadeOut(300);
$.ajax({
url: '../ajax-follow.php',
...
the url parameter to :
url: 'ajax-follow.php',
See if it will work that way

javascript alert in an if else statement not triggering

If the first part of the statement fails I am trying to send an alert. But I cannot figure out why the alert is not triggering. Yes, I have forced the statement to fail.
$("#btnSubmit").click(function (e)
{
if (<?php echo $browser; ?> >= 1)
{
var user = $("#ownerPost input").val();
var oid = <?php echo $Owner; ?>;
$.ajax(
{
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);
}
}
);
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}
else
{
alert("You must log in to follow");
}
}
);
Here is the output from view source:
The actual number is 56 and makes the statement true and that is correct. It is when the statement is false that it will not trigger the else and hence the alert.
If I place an alert right before the else it will show the alert because first part is true.
$("#btnSubmit").click(function (e)
{if (56 >= 1){
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data){
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);} });
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}else{alert("You must log in to follow");}});
I think you have a syntax error. I was going to suggest a try/catch, but that will not help with a syntax error. Please edit your question and put in the "view > page source" as the others have suggested. Also, can you use Firebug, or equivalent to view the console?
EDIT:
I do get the alert with this code. Note that I set browser to 0.
blah = function(e) {
if (0 >= 1) {
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type : 'POST',
url : 'follow.php',
data : "oid=" + oid,
dataType : 'json',
success : function(data) {
var id = data[0];
var name = data[1];
$('#output2')
.html("<b>id: </b>" + id + "<b> name: </b>" + name);
}
});
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
} else {
alert("You must log in to follow");
}
};
blah.call();

Categories

Resources