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;
Related
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
I want to send a Hindi message from my custom php page. For this I have used a ajax request.
How to encode it in JavaScript before sending in ajax and decode it in php function?
EDIT
Here is my code :
...
var message = ''; // here I am getting content from form field dynamically
var ajaxBlockUrl = '/my.php?action=custom&mobile=999999999&message='+message;
Ajax.Request(ajaxBlockUrl,
{
parameters: {isAjax: 'true', form_key: FORM_KEY},
onSuccess: function(response)
{
//
}
});
...
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.
How can I go about accomplishing the following behavior.
upon getting an input from a knockout.js form send the variable to a page to be handled. The page uses PHP
The PHP page receives the input from the knockout.js form and runs some calculations and then returns the result
The variable is then received back on the original page and is then displayed via knockout
For example, say I have the following
//knockout_form.js
self.addItem = function() {
var itemNum = self.newItem; //variable received from knockout form
var returnedVariable = ???? **send itemNum to processing.php which will then return it**
self.itemNumbers.push(new ItemEntry(retunredVariable, "$20.00")); //
}
I know that jQuery/Ajax can be used to post to processing.php, but how do I return the calculated data from processing.php back to the javascript page?
edit below. The data appears to be sent to processing.php (shows up in the network tab) but the alert isn't showing.
// Operations
self.addItem = function() {
var itemNum = self.newItem;
$.getJSON("processing.php?itemNum=" + itemNum),function(data) {
alert(data); //this does not appear
self.itemNumbers.push(new ItemEntry(data.result, "$20.00"));
}
}
Here's the php
//$result = $_GET['itemNum'];
$result = "test"; //set it just to be sure it's working
echo json_encode(array("result" => $result));
Knockout doesn't have any special way of doing ajax calls itself, typically you would use jQuery. See http://knockoutjs.com/documentation/json-data.html.
So something like:
self.addItem = function() {
var itemNum = self.newItem;
$.getJSON("processing.php?itemNum=" + itemNum,function(data) {
self.itemNumbers.push(new ItemEntry(data.result, "$20.00"));
});
}
This assume that your PHP script is outputting valid JSON. Something like:
<?php
$result = doCalculations($_GET['itemNum']);
echo json_encode(array("result" => $result));
?>
This is untested, but you get the idea.
I'm trying to send post data between pages with Post. Not a form - like I may be passing validation error between pages or something (using it in several places).
The cURL is executing fine, but it's just tacking on the new page at the bottom. How can I execute a cURL Post and load the following page?
So my goal is to send data between pages. I do not want to use GET or cookies as I do not want to rely on the user, and I'd prefer not to use $_SESSION as it is not so much directly about a session as sending private data between pages.
Thanks
$ch = curl_init($some_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'myvar=something');
curl_exec($ch);
curl_close($ch);
I doubt the code has any relevance, as it's about performing a task not code syntax (there may be one in this example but you'll have to trust me it's not the code that's buggy as it's retrieving fine).
You could separate your $_SESSION superglobal into arrays describing both the current user/session and any errors that your form has created. For instance,
$_SESSION = array(
'user' => array(), // user data goes here
'errors' => array() // validation data goes here
);
if (!$_POST['myvar'] == 'something') {
$_SESSION['errors']['myvar'] = 'You must specify a value for <code>myvar</code>';
}
You would then be able to output errors on subsequent pages using a call something like this:
if (isset($_SESSION['errors'])) {
foreach($_SESSION['errors'] as $error) {
echo '<li>' . $error . '</li>';
}
}
Why are you using cURL? Why not just use AJAX:
$(function() {
// Send data asynchronously
$.ajax({
url: '/path/to/your/script.php',
type: 'POST',
data: 'var1=value1&var2'=$('input.some_class').val(),
success: function(data) {
// Send the user to another page
window.location.href = '/to/infinity/and/beyond';
}
});
});
Using ajax for exec
$(function() {
/
data: 'var1=value1&/ Send data asynchronously
$.ajax({
url: '/path/to/your/script.php',
type: 'POST',var2'=$('input.some_class').val(),
success: function(data) {
// Send the user to another page
window.location.href = '/to/infinity/and/beyond';
}
});
});