Submitting Magento form on page load - php

I am working on an extension to integrate a third party API into Magento. The steps included are to fill out a form on our site. When the user clicks submit the API pre-fills a form on their site which the user then approves. A few get string variables are sent over to the page on our site, which trigger a second API call (behind the scenes) that retrieves a token. Once the token is created I am then saving the token to a second hidden form and submitting it via this function:
function submitAccount() {
var formId = 'form-payment-submit';
var myForm = new VarienForm(formId, true);
var postUrl = '<?php echo $this->getUrl('marketplacepayment/marketplaceaccount/paymentsetup/') ?>';
if (myForm.validator.validate()) {
new Ajax.Updater(
{ success:console.log("form success") }, postUrl, {
method:'post',
asynchronous:false,
evalScripts:false,
onComplete:function(request, json) {
//submitButtonOn();
alert('success!');
},
parameters: $(formId).serialize(true),
}
);
}
}
The function in my module then handles saving the values to the database:
public function paymentsetupAction(){
if(!(empty($_POST['access']))){
// save tokens to db
$collection = Mage::getModel('marketplace/userprofile')->getCollection();
$collection->addFieldToFilter('mageuserid',array('eq'=>$_POST['userid']));
foreach($collection as $row){
$id=$row->getAutoid();
}
$collectionload = Mage::getModel('marketplace/userprofile')->load($id);
$collectionload->setaccesstoken($_POST['access']);
$collectionload->setrefreshtoken($_POST['refresh']);
$collectionload->setstripekey($_POST['key']);
$collectionload->save();
Mage::getSingleton('core/session')->addSuccess( Mage::helper('marketplace')->__('Your payment information has been sucessfully saved.'));
$this->_redirect('marketplacepayment/marketplaceaccount/payment');
}
}
The problem is that the tokens are not being saved but no errors are appearing. I can't write any of the info to the page since the submit is via AJAX so I am at a loss as to how to debug. Do you see anything immediately wrong with the paymentsetupAction? Or is there an easier way for me to see why it is not working?

The problem was with the $collection section - I was using the wrong database column names:
$collectionload = Mage::getModel('marketplace/userprofile')->load($id);
$collectionload->setaccess_token($_POST['access']);
$collectionload->setrefresh_token($_POST['refresh']);
$collectionload->setstripe_key($_POST['key']);
$collectionload->save();
Sorry for the random non important question.

Related

Display notification only once - PHP - Codeigniter - JS

There is an ajax function, which displays a notification on the home page, however, every time I enter thehome page, or refresh the F5 page, the notification is displayed again.
How to fix this?
Is there any way to do this, using js jquery or PHP?
Below the code I have:
Controller
public function get_message()
{
$notification= array();
$notification['message'] = 'message test';
$notification['type'] = 1;
echo json_encode($notification);
}
Javascript
/*** variable ***/
var enum_toastr_type = {
success: 1,
info: 2,
warning: 3,
error: 4
}
/*** PageLoad start ***/
$(document).ready(function() {
toastr.options = {
closeButton: true,
positionClass: 'toast-bottom-right',
timeOut: '20000'
}
get_message_ajax();
});
/*** PageLoad end ***/
function show_message_toastr(mensagens) {
$(mensagens).each(function() {
switch (this.tipo) {
case enum_toastr_type.info:
toastr.info(this.message);
break;
case enum_toastr_type.success:
toastr.success(this.message);
break;
case enum_toastr_type.warning:
toastr.warning(this.message);
break;
case enum_toastr_type.error:
toastr.error(this.message);
break;
}
});
}
/*** Ajax start ***/
function get_message_ajax() {
$.ajax({
type: 'GET',
async: false,
contentType: 'application/json; charset=utf-8',
url: "helper/get_message",
success: (function(data) {
//console.log(data);
_obj = JSON.parse(data);
show_message_toastr(_obj);
}),
error: (function(erro) {
handle_ajax_error(erro);
})
});
}
/*** Ajax end ***/
For doing this you will need to set cookies in the browser to track if user has visited this page already. This would also prevent this on page reloads. You can use local storage to store any data in the browser.
// on page load check if user has not already visited this page
var visited = localStorage.getItem('visited');
if(!visited) {
// call your ajax function which displays message
get_message_ajax();
// lets set visited to true so when user loads page next time then get_message_ajax() does not gets called
localStorage.setItem('visited', true);
}
If you need something like; what if user logs out of the system, then you can clear the local storage on logout. Maybe you can add click listner on logout button and can clear local storage.
localStorage.clear(); // this will clear all website data in localStorage
// or you can update visited key;
localStorage.setItem('visited', false);
Or if you want something more advance like even user does not logs out and still you want to show message lets say if user visits after 1 day. Then you can store timestamp with key and parse it back when checking if user visited.
var object = {value: "value", timestamp: new Date().getTime()}
localStorage.setItem("key", JSON.stringify(object));
When accessing the key you can do something like this;
var object = JSON.parse(localStorage.getItem("key")),
dateString = object.timestamp,
now = new Date().getTime().toString();
// here you can compare two time strings and decide to show message.
For different implementation and ideas on how to manipulate time here is some help;
https://developer.mozilla.org/en-US/docs/Web/API/Storage
When do items in HTML5 local storage expire?

Compare user value to database and show result through ajax jquery

Guys m working on my first live project and i am stuck at a point, where i need help with ajax jquery. i can do this with PHP but i wanna do this with ajax.
Here if user enter a product code ,so i want to compare this product code value into my database and show product name in my other form ,which will open after user input value:
Here in first field i want product name:
Here in my table you can see product code and product name:
ok so here is my html code in last option when user enter product code
Here is jquery i am sending user data to 8transectiondata.php to compare
And this is php file and i want $data['product_name']; to show
Here's a generic answer.
JS FILE:
$(document).ready(function () {
$('#myButtonId').on('click', function () {
var code = $('#myCodeInputId').val();
if (code !== '') { // checking if input is not empty
$.ajax({
url: './my/php/file.php', // php file that communicate with your DB
method: 'GET', // it could be 'POST' too
data: {code: code},
// code that will be used to find your product name
// you can call it in your php file by "$_GET['code']" if you specified GET method
dataType: 'json' // it could be 'text' too in this case
})
.done(function (response) { // on success
$('#myProductNameInput').val(response.product_name);
})
.fail(function (response) { // on error
// Handle error
});
}
});
});
PHP FILE:
// I assumed you use pdo method to communicate with your DB
try {
$dbh = new PDO('mysql:dbname=myDbName;host=myHost;charset=utf8', 'myLogin', 'myPassword');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
exit('ERROR: ' . $e->getMessage());
}
$sql = "SELECT `product_name` FROM `products` WHERE `product_code` = :code";
$result = $dbh->prepare($sql);
$result->bindValue('code', $_GET['code'], PDO::PARAM_INT);
$result->execute();
if($result->rowCount()) { // if you got a row from your DB
$row = $result->fetchObject();
echo json_encode($row, JSON_UNESCAPED_UNICODE); // as we use json method in ajax you've got to output your data this way
// if we use text method in ajax, we simply echo $row
}
else {
// handle no result case
}
I know what you want to do, but without specific code the best I can do is give you a generalized answer.
When a user fills out a field, you want to post that field to the server, look up a product and return some stuff.
The basics are going to look like this.
$(document).ready( function(){
//rolling timeout
var timeout;
$('#field').on('keyup', function(e){
if(timeout) clearTimeout(timeout);
timeout = setTimeout( function(){
var data = {
"field" : $('#field').val()
};
$.post( '{url}', data, function(response){
if(response.debug) console.log(response.debug);
if(response.success){
//open other form
$('{otherFormProductField}').val(response.product);
}
}); //end post
},450); //end timeout
});//end onKeyup
}); //end onReady
Then in PHP, you have to process the request. Pull the field from the $_POST array, look it up in the Database. Then build a response array and send it back to the client as JSON. I like to build responses in a structure something like this.
{
success : "message", //or error : "message"
debug : "",
item : ""
}
Then in PHP I will do this.
ob_start();
..code..
$response['debug'] = ob_get_clean();
header("Content-type:application/json");
echo json_encode($response);
This way, you can still print out debug info (in side the output buffer calls ) when developing it and don't have to worry about it messing up the Json or the header call.
-note- Use a timeout, that you reset on each key press (a rolling timeout). What it does is reset the previous timeout each time the key is released. That way it only sends the request once the user quits typing (instead of sending request on every keypress). I have found 450 milliseconds to be about the perfect value for this. Not too long not too short. Basically once they stop typing for 450ms it will trigger the $.post

Add data jQuery mobile back button

I have some pages that get information from the database.
But when pressing back on pages the fields are just empty (normal filled with values from database).
So is it possible to pass some data or form along with the back button with jQuery mobile so I can fetch the data again?
Thanks in advance
You can save all of your data with this neat plugin:
http://sisyphus-js.herokuapp.com/
Or you can take advantage of this JS function to send all of the data you need:
window.onbeforeunload = function()
{
// here's the data you will send
var my_data = {name: "Smith", password: "abc123"};
var xhr = new XMLHttpRequest();
// open the object to the required url
xhr.open("POST", "flash_form/save", true);
// encode and send the string
xhr.send(JSON.stringify(my_data));
};
From there, in your controller, save the data to your session with:
// No need to decode the JSON
$this->session->set_userdata('form_flash_data', file_get_contents('php://input'));
And when your page is loading, just make a check to see if there is any session data:
$form_data = $this->session->userdata('form_flash_data');
// check if there is any data available, if so print!
// you can also return another json if there is nothing
// eg: {msg: "no form data"}
echo ($form_data === false) ? '' : $form_data;

Can Galleria be used with ajax data?

I really need some help here!
I have a page with images in groups of 1, 2, or 3. I click on an image and the class gets sent to some jquery ajax stuff to get the id(mysql) then this gets sent to a php file to build the html for the images to display on a div in my page. This bit works OK, but I'm trying to use the galleria plugin to show the image that haave been sent, but it just act like galleria is not there! If I hardcode some images in the dive. galleria works as it should!
here is my project.js file
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.post('../inc/showprojects.php', {project: projectvalue}, function(data) {
$('#shownews').html(data);
});
});
This is my showproducts.php file
<?php
include 'connect.php';
// if no project was sent, display some error message
if(!isset($_POST['project'])) {
die('No project has been chosen');
}
// cast the project to integer (just a little bit of basic security)
$project = (int) $_POST['project'];
// this will be the string that you will return into the shownews div
$returnHtml = '';
$q = "SELECT * FROM projects WHERE id='$project'";
if($r = mysql_query($q)) {
// construct the html to return
while($row = mysql_fetch_array($r)) {
$returnHtml .= "<img src='{$row['filename']}' />";
$returnHtml .= "<img src='{$row['filename1']}' />";
$returnHtml .= "<img src='{$row['filename2']}' />";
}
}
// display the html (you actually return it this way)
echo $returnHtml;
?>
This is how I'm calling galleria on the div
// Load the classic theme
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
// Initialize Galleria
$('#shownews').galleria();
Can anyone help me out?
Thanks
try this one
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.ajax({url:'../inc/showprojects.php',
type:'POST' ,
method,async:false ,
data:{project: projectvalue},
success:function(data) {
$('#shownews').html(data);
}});
Galleria.run('#shownews');
});
I think, you need to call Galleria.run after recieve data from php
EDIT: ugly way - destroy gallery, if already running before inserting new images into div
if($('#shownews').data('galleria')){$('#shownews').data('galleria').destroy()} //destroy, if allready running
$.post('../inc/showprojects.php', {project: projectvalue}, function(data) {
$('#shownews').html(data);
Galleria.run('#shownews');
});
and remove $('#shownews').galleria();
EDIT 2: use Galleria's .load api to load new data
// whenever a link with category class is clicked
$('a.project').click(function(e) {
// first stop the link to go anywhere
e.preventDefault();
// you can get the text of the link by converting the clicked object to string
// you something like 'http://mysite/categories/1'
// there might be other methods to read the link value
var linkText = new String(this);
// the value after the last / is the category ID
var projectvalue = linkText.substring(linkText.lastIndexOf('/') + 1);
// send the category ID to the showprojects.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the shownews div
$.post('../inc/showprojects.php', {project: projectvalue},
function(data) {
$('#shownews').data('galleria').load(data);
},"json"
);
});
PHP
<?php
include 'connect.php';
// if no project was sent, display some error message
if(!isset($_POST['project'])) {
die('No project has been chosen');
}
// cast the project to integer (just a little bit of basic security)
$project = (int) $_POST['project'];
// this will be data array that you will return into galleria
$returnData = array();
$q = "SELECT * FROM projects WHERE id='$project'";
if($r = mysql_query($q)) {
// construct datat object to return
while($row = mysql_fetch_array($r)) {
$returnData[] = array('image'=>$row['filename']);
$returnData[] = array('image'=>$row['filename1']);
$returnData[] = array('image'=>$row['filename2']);
}
}
// return JSON
echo json_encode($returnData);
?>
Galleria init:
(Gallery will be empty until you will load data into it)
// Load the classic theme
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
// Initialize Galleria
Galleria.run('#shownews');
Try loading galleria after the ajax request has successfully completed. By doing this jquery waits until ShowNews has been rendered and then runs galleria.
$.ajax(
{
type: "POST",
url:'../inc/showprojects.php',
data:{project: projectvalue},
success: function(data)
{
$('#shownews').html(data);
},
complete: function()
{
Galleria.loadTheme('../galleria/themes/classic/galleria.classic.min.js');
$('#shownews').galleria();
}
});
I use this method whenever i gather the image data from a remote source. Hope this helps!
I tried this answer and other answers on the web and nothing worked. Then I moved galleria-1.3.5.min.js to the parent page and it worked. What an amazingly simple solution!

Google Map V3: Loading a route (JSON string) from a mysql database onto a map using php, javascript and ajax

I'm attempting to retrieve and load a series of waypoints from a mysql database onto a map using ajax, javascript and php. The route is stored in the database using a JSON string.
This is the javascript function that is called (the parameter is the id of the route to be loaded, as there are many routes in the database):
function fetchdata(id) {
var routeID = id;
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch&rid='+routeID);
jax.onreadystatechange = function(){
if(jax.readyState==4) {
try {
setroute(JSON.parse(jax.responseText));
}
catch(e){
alert(e);
}
}
}
The php file it calls contains this if statement to seperate save and fetch commands:
//Retrieving the route from the database.
if($_REQUEST['command']=='fetch') {
$query = "SELECT * FROM Route WHERE route_id='$id'";
if(!($res = mysql_query($query))) {
die(mysql_error());
}
else {
$rs = mysql_fetch_array($res,1);
die($rs['waypoints']);
}
}
The problem that I'm having is that when the value is passed back to ajax/javascript it is just reporting an "Object Error" and is not being parsed by the JSON.parse() method. I'm not if I'm passing the wrong type of object back to ajax, but I have tried converting it to a strong also.
Any help on solving this would be greatly appreciated!
Thanks

Categories