I,m trying to access Magento session data outside Magento using Json.Json is working fine in IE but when i tried to access Magento session data using json then it does't work.
Code works in FF,Chrome,Opera .. but not in IE 7
Here is my server.php file
<?php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::app();
if(isset($_GET['cart_item'])){
Mage::getSingleton('core/session', array('name'=>'frontend'));
$_cartQty=0;
$_cartItem='My Bag is empty';
foreach (Mage::helper('checkout/cart')->getCart()->getItems() as $item){
$_cartQty+=$item->getQty();
}
if ($_cartQty>0)
$_cartItem='My Bag ('. $_cartQty.')';
echo $_GET['callback'] . '('.json_encode(array('response'=>$_cartItem)).');';
}
?>
here is my client.html file
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function change_cart_item(){
var cartItemUrl=jQuery('#cart_item_url').val();
jQuery.getJSON(cartItemUrl, function(json) {
var result=json.response;
alert(result);
//var cartItem = jQuery(result).find('#cart_item').html();
//jQuery("#show_cart span").html(result);
});
return false;
}
</script>
<input id="cart_item_url" name="cart_item_url" type="hidden" value="http://test.com/ie.php?callback=?&cart_item=cart_item" />
<input type="button" onclick="change_cart_item()" value="Change cart item" />
The above code always return "My Bag is empty" in IE.
I suggest checking why IE doesn't send the cookie headers to the /ie.php script. IE must somehow evaluate the cookie path value differently.
As a workaround try implementing a regular Magento action controller that simply returns the JSON, since that is bound to receive the cookie headers by IE (otherwise the whole store front of Magento would not work with IE).
To return JSON from a action controller use:
public function jsonAction()
{
$_cartItem = 'My Bag is empty';
$_cartQty = Mage::helper('checkout/cart')->getItemsQty();
if ($_cartQty > 0) {
$_cartItem = 'My Bag ('. $_cartQty.')';
}
$this->getResponse()->setBody(
$_GET['callback'] . '(' . Mage::helper('core')->jsonEncode(array('response'=>$_cartItem)).');'
);
}
There is a bug in IE's implementation of WinInet. If you have a cookie that has a path with a filename in it, IE will not make it available via the document.cookies property in Javascript. Such a cookie should be transmitted to the server though.
Related
Im building an app using PHoneGap as the compiler so using HTML5, CSS, JQuery, AJAX etc. Ive manage to get AJAX to GET all the rows from the Database perfectly well, as I have to use .HTML extension on my files I'm struggling to be able to link through to specific DB record. I can do this perfectly in PHP. Im struggling with the HTML part.
Here is my AJAX Loader to get all Rows from DB
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call ...
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MY-URL.COM/videos-mysql.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'POST', //Makes sense only if you passing data
success: function(answer) {
jQuery('#videos-modules').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
error: function() {
//unknown error occorupted
inProcessVideos = false;//Queue is free, guys ;)
}
});
}, 500 );
And here is the contents of the PHP File that renders all the Results from the Database. This part displays the content perfectly.
<?php
include ("../config/mysqli_connect.php");
$sql = ("SELECT * FROM videos");
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "
<a href='" . $row["id"]. "'>
<div class='video-module'>
<div class='video-thumb'><img src='https://MY-URL.COM/thumbs/" . $row["video_thumb"]. "'></div>
<div class='video-thumb-details'>
<div class='video-thumb-title'> " . $row["id"]. " - " . $row["video_title"]. "</div>
" . $row["publisher_name"]. "
</div>
</div></a>
";
}
} else {
echo "0 results";
}
?>
After the ECHO statement I would normally put something like video-Profile.php?id=$id and it would go to that page and pull in that record from the Database.
However now that I have to do it only in HTML, and im assuming AJAX, how to I achieve this.
Here is the PHP and the MYSQL Query to GET the specific record from the Database. Its currently in MYSQL, I will convert it to MYSQLi once I've got it working and got my head around it.
<?php
// Use the URL 'id' variable to set who we want to query info about
$id = ereg_replace("[^0-9]", "", $_GET['id']); // filter everything but numbers for security
if ($id == "") {
echo "Missing Data to Run";
exit();
}
//Connect to the database through our include
include_once "../config/connect_to_mysql.php";
// Query member data from the database and ready it for display
$sql = mysql_query("SELECT * FROM videos WHERE id='$id' LIMIT 1");
$count = mysql_num_rows($sql);
if ($count > 1) {
echo "There is no user with that id here.";
exit();
}
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$video_title = $row["video_title"];
$video_thumb = $row["video_thumb"];
$publisher_name = $row["publisher_name"];
$video_directory = $row["video_directory"];
$video_path = $row["video_path"];
$upload_date = $row["upload_date"];
$video_views = $row["video_views"];
}
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php echo ("$id");?> - <?php echo ("$video_thumb");?>
</body>
</html>
I know this works if I'm running PHP files, and my server is set to PHPv5.3., but before I make it live, it will be sorted to MYSQLi and run on PHP7???
Im looking for inspiration to get this to function via HTML only files.
thanks for your help everyone.
This is a pretty brutalistic way of doing this - typically you'd return JSON or similar from the PHP and then process this into the HTML elements within your JS. But for this case you can do this:
//within call
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id
}) // This allows you to search your child elements and pick them based on criteria
jQuery('#videos-modules').html(contents); // now assign the remaining elements into your html as before
},
I have Tried this but i cant seem to find out how to Run a Console Log as it is Run on iOS iPad at the moment. Can not get it to render in the Browser.
var inProcessVideos = false;//Just to make sure that the last ajax call is not in process
setTimeout( function () {
if (inProcessVideos) {
return false;//Another request is active, decline timer call
}
inProcessVideos = true;//make it burn ;)
jQuery.ajax({
url: 'https://MYURL.COM/appFiles/tablet/video-profile.php', //Define your script url here ...
data: '', //Pass some data if you need to
method: 'GET', //Makes sense only if you passing data
success: function(answer) {
var contents = jQuery(answer); // You have now converted the HTML into a jquery model
contents.filter(function(element){
return $(element).attr('id') === id;
});
jQuery('#videoProfile').html(answer);//update your div with new content, yey ....
inProcessVideos = false;//Queue is free, guys ;)
},
});
}, 500 );
Struggling with this, i've looked at all the JQuery, AJAX MySQL web sites i can find including W3Schools, Jquery.com and many others. Just can not get it to pass the ID to the PHP file to get the Record from the DB via AJAX.
My Links in the first JQuery AJAX Call are:
<a href='video-Profile.html' data='".$row["id"]."' value='".$row["id"]." '>Some HTML STUFF/Images/Text etc</a>
I can get the ID and the First AJAX Call to show ALL the rows in the DB Table. Now just need to show Record by ID. This is what i cant get my head around. And it must be in .HTML Page as its an App compiled via PhoneGap. I know im repeating my self, Just not to sure if im making my point clear. Thanks for the help in advance.
I'm trying to download a dynamically generated file from the server using a hidden form.
Below is the angular function that I'm using to submit the hidden form
$scope.downloadCsv = function() {
var dataset = JSON.stringify($scope.dataset);
var body = $('body');
var reportParamJson = angular.toJson($scope.dataset);
var hiddenForm = "<form action='/Reports/SaveTestCsv' method='POST' target='_blank'><input type='hidden' name='dataset' value='" + dataset + "'/ ><button id='submitCSV' type='submit'></button></form>";
body.append(hiddenForm);
$('#submitCSV').click();
}
Below is the .net mvc method to generate the response with the file
[HttpPost]
public ActionResult SaveTestCsv(string dataset)
{
var data = JsonConvert.DeserializeObject<MyObject>(dataset);
var binary = getTestCSV(data);
var file = File(binary, "text/csv", "test.csv");
return file;
}
Below is the relevant html code from the partial html page that I'm including in the view using ng-include
<div>Download CSV</div>
<div ng-grid="gridOptions"></div>
.
When I click on "Download CSV", Chrome, FF and IE10 prompts me to save the file without refreshing the page/view, but on IE8/9, the page is refreshed, so the content from the ng-include tag is gone, in particular the html I posted above is no longer present.
I'm wondering if this has something to do with the hashbang in the url from IE8/9 and is there any way to fix this?
Edit
I ended up removing routing from angular completely and just use .net MVC to do the routing for me, and then it's working on IE8
in my webpage, I have the following code:
<?php
echo "<td class=\"action\">
?>
<script>
function deleteline(a) {
var r=window.confirm("Voulez-vous vraiment supprimer le viager " + a +"?");
if (r)
{
<?php
$test="<script> document.write(a);</script>";
mysql_connect("localhost", "xxxxxx", "xxxxxx") or die (mysql_error ());
mysql_select_db("xxxxxx") or die(mysql_error());
$strSQL =("update viagers set statut='deleted' where id=????");
$rs = mysql_query($strSQL);
mysql_close();
?>;
}
}
</script>
In a php table, i have an small delete icon in each row. I want the user to be able to click on it so it deletes the record in the sql db. I can't find a way to retrieve the 'a' variable in the php code of my script function (replace by ????).
Could you please help?
thanks and regards
Harold
You can't mix javascript and PHP like that. Make another PHP file for deletion, and send the a by javascript to the file through AJAX.
PHP code inside javascript is not a good approach. As lqbal Fauzi mentioned, send a variable - row id by javascript to the php file through AJAX - or as I do below, by using JQUERY. In php file, you can do your database stuff and if wanted, send some result back to your application.
In your HTML file you have to have scripts with JQUERY library source files.. Download these 2 files from here:
https://mega.co.nz/#!IUAFCYZb!Cu0mQoAVAkJHzqvac40-RYA-n3TnhYGtoazw5k_PMv4
https://mega.co.nz/#!hABhFDiS!Q_L8rERVq8330zrOxXXen0uxmLCes7zYG6J6SCncz6M
and save/copy those files into the folder containing your html file.
Your html file should look something like this:
<html>
<head>
<meta charset="utf-8" />
<title>Your page Title</title>
<script src="jquery.mobile-1.3.2.min.js"></script>
<script src="jquery-1.9.1.min.js"></script>
<script>
function yourJavascriptfunction(sender){
var r=window.confirm("Voulez-vous vraiment supprimer le viager " + sender.name +"?");
if (r)
{
$.post("YourPHPPageToAccessDatabaseAndSendResult.php", {
UserID:sender.name
})
.success(function(data){
//some code on data return if you want
alert(data); //should pop up with message saying "Hello, this is the result data"
})
.fail(function(error){
alert("Unable to retrieve data from the server");
});
}
}
</script>
</head>
<body>
<button type="button" name="YourRowID" onclick="yourJavascriptfunction(this)" > your button text</button>
</body>
</html>
and in the php file named YourPHPPageToAccessDatabaseAndSendResult.php which has to be in this case in the same directory as your html file following code:
<?php
$connection = mysql_connect("localhost","USER","YOURPASSWORD") or die(mysql_error());
mysql_select_db("DatabaseName",$connection);
$UserID= $_POST['UserID'];
$strSQL =("update viagers set statut='deleted' where id=$UserID");
$rs = mysql_query($strSQL);
mysql_close();
//by printing with echo you sent some data that you want return to your html file
echo "Hello, this is the result data";
?>
The above code is not tested for functionality, there might be some typos, but the logic in there should work and help you in the future
Don't forget to substitute the YourRowID in button name in html file to whatever you need, and set correct USER, YOURPASSWORD and DatabaseName in the php file.
I am trying to access tabs and windows data inside a Google Chrome extension. I've apparently managed to get this info and loading it through localStorage but I don't know how to use the information, since I can't seem to parse the data back to arrays of objects through JSON parse.
Here's the code:
<html>
<head>
<script>
tabs = {};
tabIds = [];
focusedWindowId = undefined;
currentWindowId = undefined;
localStorage.windowsTabsArray = undefined;
function loadItUp() {
return arrays = chrome.windows.getAll({ populate: true }, function(windowList) {
tabs = {};
tabIds = [];
var groupsarr = new Array();
var tabsarr = new Array();
var groupstabs = new Array();
for (var i = 0; i < windowList.length; i++) {
windowList[i].current = (windowList[i].id == currentWindowId);
windowList[i].focused = (windowList[i].id == focusedWindowId);
groupsarr[windowList[i].id] = "Untitled"+i;
for (var j = 0; j < windowList[i].tabs.length; j++) {
tabsarr[windowList[i].tabs[j].id] = windowList[i].tabs[j];
groupstabs[windowList[i].id] = windowList[i].tabs;
}
}
localStorage.groupsArray = JSON.stringify(groupsarr);
localStorage.tabsArray = JSON.stringify(tabsarr);
localStorage.groupsTabsArray = JSON.stringify(groupstabs);
});
}
function addGroup() {
var name = prompt("NEW_GROUP_NAME");
var groupsarr = JSON.parse(localStorage.groupsArray);
groupsarr.push(name);
localStorage.groupsArray = JSON.stringify(groupsarr);
}
</script>
</head>
<body onload="loadItUp()">
WINDOW_QTY:
<script type="text/javascript">
var wArray = JSON.parse(localStorage.groupsArray);
document.write(wArray);
</script>
<br/>
TABS_QTY:
<script type="text/javascript">
var tArray = JSON.parse(localStorage.tabsArray)
document.write(tArray);
</script>
<br/>
WINDOWS_TABS_QTY:
<script type="text/javascript">
document.write(JSON.parse(localStorage.groupsTabsArray));
</script>
<br/>
</body>
</html>
1)
The page shows bunch of [object Object].
That's expected, objects are implicitly converted to string when you call document.write(tArray);; custom object without a custom toString implementation are converted to "[object Object]". It doesn't mean they're not "parsed".
To inspect the object you can use the Developer Tools. You can open the inspector for a background page from the Extensions page and if you get your page to open in a tab (e.g. if you use chrome_url_overrides) you can inspect it as you would inspect a regular web page.
If you replace the document.write calls with console.log(), you'll be able to inspect the objects in the Developer Tools' console.
2)
Do you realize that the document.write calls in tags run before loadItUp()?
Had no idea that the page code was being executed before loadItUp().
Scripts are executed at the moment they are inserted in the DOM by the parser (unless they are deferred or async) - see MDC documentation on <script>, - while various load events, in particular <body onload=...>, are executed after the page is finished parsing.
So right now your document.write calls print the values that were saved to localStorage the previous time the page was loaded, it's probably not what you wanted.
Instead of using document.write() from inline scripts, you should use element.innerHTML or element.textContent to update the page's text. There are many ways to get a reference to the element you need, document.getElementById() is one.
3)
Last, note that not every object can be saved to and then loaded from localStorage. For example, methods will not survive the round-trip, and the identity of the object is not preserved, meaning that the object you got from a Chrome API will not be the same object after you store it in localStorage and load it back.
You have not explained why you think you need localStorage - it's used when you want to preserve some data after the page is closed and reloaded - so maybe you don't really need it?
I'm trying to test out html5 localStorage feature. For some reason, whenever I try to retrieve a value from storage after refreshing the page, I only get null values returned. (If I try retrieving the values in the same function that I set them in, then I can properly retrieve them).
One thing: the html/javascript that I'm loading is being requested from the local disk (for example, I'm using the string: "file:///C:/testLocalStore.html" to browse to the file, instead of requesting it from a web server. Would this cause the localStore problems that I'm seeing?
(I'd like to post the full code example, but I'm having some problems with the formatting. I'll post it shortly).
<html> <head> <title>test local storage</title>
<base href="http://docs.jquery.com" />
<script src="http://code.jquery.com/jquery-1.3.js"></script>
<script type="text/javascript">
function savestuff()
{
var existingData = localStorage.getItem("existingData");
if( existingData === undefined || existingData === null )
{
// first time saving a map.
existingData = $("#mapName").val();
}
else
{
existingData = existingData + "," + $("#mapName").val();
}
localStorage.setItem("existingData", existingData);
// test is non-null here, it was properly retrieved.
var test = localStorage.getItem("existingData");
}
$(document).ready( function init()
{
// existing data is always null.
var existingData = localStorage.getItem("existingData");
if( existingData !== null )
{
var existingDataListHtml = existingData.split(",");
existingDataListHtml = $.each(existingData, function(data) {
return "<li>" + data + "<\/li>";
});
$("#existingData").html("<ul>" + existingDataListHtml + "<\/ul>");
}
} );
</script>
</head> <body>
<form id="loadFromUser" onsubmit="savestuff();">
<input id="mapName" type="text">
<input type="submit" value="save">
</form>
<div id="existingData"> </div>
</body> </html>
Yes, loading the file locally means that it doesn't have an origin. Since localStorage is uses the same-origin policy to determine access to stored data, it is undefined what happens when you use it with local files, and likely that it won't be persisted.
You will need to host your file on a web server in order to have a proper origin; you can just run Apache or any other server locally and access it via localhost.