Magento insert data into database through ajax - javascript

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

Related

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

dropzone.js edit (add/delete) pre-exisitng image files in Magento

below is my code for deleting images when clicked on "remove file" CTA on the dropzonejs box. However, when the "remove file" is clicked, only the thumbnail image is deleted, and not the actual file.
By calling the delete function in Magento through Ajax when the "removedfile" is called, it should delete the thumbnail as well as the file, but it does not seem to work as the server still keeps the pre-loaded image file.
this.on("removedfile", function(file) {
alert("here");
jQuery.ajax({
url: "<?php echo Mage::getUrl("*/*/deleteimage"); ?>",
type: "POST",
dataType: "json",
data: {'pid': "<?php echo $loadpro->getId(); ?>",'file':file.name},
success: function (data) {
Success = true;//doesnt goes here
},
error: function (textStatus, errorThrown) {
jQuery("#vals").text('');
var det = checkfile('<?php echo $loadpro->getId(); ?>');
if(det != null)
{
maxcount = 1;
}
else {
maxcount = null;
}
}
});
Below is the code for the Magento controller that is called in the function above that listens for the "removedfile."
public function deleteimageAction()
{
$id= $this->getRequest()->getParam('pid');
$imagename= $this->getRequest()->getParam('file');
$product = Mage::getModel('catalog/product')->load($id);
$productMediaConfig = Mage::getModel('catalog/product_media_config');
$mediaGallery = $product->getMediaGalleryImages();
foreach($mediaGallery as $mediagg){
$file = $mediagg->getUrl();
$fileName = basename($file);
if($fileName == $imagename){
$filepath = $mediagg->getFile();
}
}
try{
$storeId=Mage::app()->getStore()->getStoreId();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$newimage = '';
$data= $this->getRequest()->getParams();
//error_log(print_r($data, TRUE));
$_product = Mage::getModel('catalog/product')->load($data['pid'])->getMediaGalleryImages();
$main = explode('/',$filepath);
foreach($_product as $_image) {
$arr = explode('/',$_image['path']);
if(array_pop($arr) != array_pop($main)){
$newimage = $_image['file'];
$id = $_image['value_id'];
break;
}
}
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$mediaApi->remove($data['pid'],$filepath);
if($newimage){
$objprod=Mage::getModel('catalog/product')->load($data['pid']);
$objprod->setSmallImage($newimage);
$objprod->setImage($newimage);
$objprod->setThumbnail($newimage);
$objprod->save();
}
Mage::app()->setCurrentStore($storeId);
} catch (Exception $e) {
$this->getResponse()->setHeader('Content-type', 'text/html');
$this->getResponse()->setBody('');
}
}
I have tried most of the methods that are in google, as well as stackoverflow, but could not find an answer that works in this case.
If you know a solution to this problem, please let me know.

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

JqueryAjax and php logic

Hey guys im with a problem getting a value from php. I know we have a lot of problems with this kind of issues, but i need help.
This is my javascript
$( document ).ready(function() {
$(".loading_bg").hide();
});
$( document ).ajaxStart(function() {
$(".loading_bg").fadeIn("slow");
});
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = 'function=validate_user' + '&username=' + username + '&password=' + password;
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php',
data: datastring,
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
and this is my php
<?php
require_once('../#configs/db_connect.php');
//Lets send our data back to index
if(isset($_POST['function'])) {
$user = $_POST['username'];
$password = $_POST['password'];
echo login::validate_user($user, $password);
}
class login {
static function validate_user($username, $password) {
//Call a new default connection
$db = db::connect();
//Prepare our sql
$stmt = $db->prepare("SELECT * FROM Accounts WHERE username = :username AND password = :password");
//Bind our values to the SQL statement
$stmt->bindValue(':username', $username, PDO::PARAM_STR);
$stmt->bindValue(':password', $password, PDO::PARAM_STR);
$stmt->execute();
//Get number of affected rows
$results = $stmt->rowCount();
//If to check if we can find any row with username and password
if($results === 1) {
//return json_encode("valid account");
} else {
return json_encode($username);
}
}
}
?>
When i do the request im getting a undifned error from my var, i dont know how to fix it, can someone help me, if possible.
I think its something with my $_POST.. because if run the php with login::validate_user("teste","teste); i can get the json result..
Everything else is fine, you are not passing data correctly to ajax call. You are making query string but you have to pass JSON object if you want to capture it in $_POST in php and can append to url if you want to capture in $_GET array. I have corrected your function in both ways below:
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = { 'function': 'validate_user', 'username': username, 'password': password }
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php',
data: datastring,
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
When you want to capture data in $_GET at server side
function validate_user() {
//We get data input
var username = $('.username').val();
var password = $('.password').val();
//We create a datastring ex: functions.php?function=validate_user&username=username&password=password
var datastring = 'function=validate_user' + '&username=' + username + '&password=' + password;
//The json Ajax Request
$.ajax({
type: 'POST',
dataType: 'json',
url: '#loginAPI/functions.php?' + datastring,
data: {},
success: function(result) {
console.log(result);
$(".loading_bg").fadeOut("slow");
},
error: function(xhr, status){
console.log(status);
}
});
return false;
}
Here is PHP Code
<?php
require_once('../#configs/db_connect.php');
//Lets send our data back to index
if(isset($_GET['function'])) {
$user = $_GET['username'];
$password = $_GET['password'];
echo login::validate_user($user, $password);
}
.... // Remaining Class will come here
Im sorry to bother all of you, the real problem its my form input feilds.. i forgot to set a class... Thank you all, and once again, im sorry to make you lose time with such a silly problem.

jQuery AJAX with PHP to upload contents to MYSQL DB

I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>

Categories

Resources