var onSuccess=function(data)
{
alert(data);
obj=JSON.parse(data);
var response=obj.response;
}
the above is my javascript file and next is the how i am sending the response
$hash=$this->db->query($query);
if ($hash->num_rows() > 0)
$valid['response']= 0;
else
$valid['response']= 1;
return($valid_user);
the alert box is showing "disallowed key characters" and even i had checked config file in codeigniter .... everything is correct as mentioned everywhere
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
Related
I’m working on a WordPress site requirement to redirect a user when they’re in a certain country to their country specific homepage.
(I’ve had to do this via WP Ajax because full page caching prevents it working directly on live hosting environment - I was previously doing it quite simply in functions.php hooked into 'init').
This works when I call it at the start of the header template, but only after the current page content is shown. It would be great if I could hook it in to happen before the page is displayed e.g. like using hooks such as: 'wp_loaded', ‘template_redirect’ but jQuery needs to be available...
Here is my code. It needs tidying some more but appreciate any suggestions as how to make a redirect happen before page contents displayed?
function invoke_county_redirection() {
ob_start();
?>
<script type="text/javascript">
var ajax_url = "<?= admin_url( 'admin-ajax.php' ); ?>";
jQuery.post(ajax_url, {
'action': 'country_redirection',
}, function (response) {
// Set the cookie to say we're performing the redirect - this will flag it not to happen again
createCookie('redirected', 'true');
if (response != '') {
window.location.replace(response);
}
function createCookie(name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
</script>
<?php
echo ob_get_clean();
return;
}
function country_redirection() {
$redirect_url = '';
if ( $_COOKIE['redirected'] !== 'true' ) {
/* declare empty result url */
$result['url'] = '';
/* Call on geoip plugin to get the country from their IP address */
$userInfo = geoip_detect2_get_info_from_current_ip();
$country_code = $userInfo->country->isoCode;
/* if we've retreived the country code for the current user */
if ( $country_code ) {
/* GET THE CORRECT REDIRECT URL IF APPLICABLE TO THE USER COUNTRY */
$redirect_url = get_country_url($country_code);
}
}
echo $redirect_url;
wp_die();
}
add_action( 'wp_ajax_nopriv_country_redirection', 'country_redirection' );
add_action( 'wp_ajax_country_redirection', 'country_redirection' );
Quick update in case anyone else can be helped by this.
I hooked the hooked the function invoke_county_redirection() into the wp_head hook as follows...
add_action('wp_head', "invoke_county_redirection");
This means that jQuery would be loaded and the country detect/redirect process runs.
However, it doesn't make the request syncronous and in this particular scenario with wanting to redirect before the page loads, I have given up on this. There is a minefield of issues trying to get around full page caching trying to store a cookie and do a redirect before the page loads. I should have just insisted that caching remained off where this needs to run, so this is our conclusion. We are instead optimsing the site as best we can with GTMetrix and loader.io and we will cross the bridge of scalability as and when we need to.
Setup:
html file on local machine in parent dir
js file in sub dir
image files in sub dir "Fotos"
Following code in js file:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (true/*this.readyState == 4 && this.status == 200*/) {
alert(this.responseText);
}
};
xhttp.open("GET", "/Fotos", true);
xhttp.send();
This causes TWO alerts to pop up with completely empty message box. I tried playing around with the directory path, but nothing changed, even with just "/". If I delete the true and replace it with the line in /* it doesn't yield a message box at all.
I was hoping to get some form of parsable list of image files from this.
I realize this has been solved with jQuery before, but I want to do this without, as it should be simple enough. Well, why isn't it?
It fails if the /Fotos folder does not exist (or does not have the correct permissions).
Additionally, for XMLHttpRequest to work, it needs the web page to be served by a web server. It must be accessed with http or https protocol (even if in localhost). E.g. http ://localhost/myfolder/pagewithcode.html Then, the Fotos folder must be a subfolder of "myfolder". The code would also work if the route is http: //localhost/pagewithcode.html (and Fotos is a subfolder of the one where pagewithcode.html is).
The code below (slightly modified from yours) gets the contents of the current folder (in which the html page with the JavaScript code is stored).
Notice that the responseText is HTML, with all the tags, not just the list of files, so that it could be shown in the browser.
<html>
<body>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// enter here only when success
console.log(this.readyState);
console.log(this.responseText);
}
else {
// enter here for all state changes except success
console.log(this.readyState);
console.log(this.responseText);
}
};
xhttp.open("GET", ".", true);
xhttp.send();
</script>
</body>
</html>
If Fotos is a subfolder of the one the html page is in, then you'd better remove the initial '/' of the path (otherwise, you are getting a Fotos folder in the root folder of the server):
xhttp.open("GET", "Fotos", true);
<script>
var xmlHttp =new XMLHttpRequest();
var url= "summary.txt";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var myArr = JSON.parse(xmlHttp.responseText);
myFunction(myArr);
}
xmlHttp.open("GET", url , true);
xmlHttp.send();
} function myFunction(arr)
var output="";
var i;
for(i=0;i<arr.length;i++){
output+='<p>'+arr[i].title+arr[i].image+arr[i].price+'</p>';
}
document.getElementById("proTab").innerHTML = output;
}
</script>
I stored all both the HTML and JSON in the htdocs folder, did xampp start and made sure Apache and mysql were running on the control panel. I then typed the link to the html using the "localhost/" to get to the html but the page was blank. Sorry for all the details.
Console says 304 Not modified. What should I do?
My guess is that you are using IE, which caches AJAX GET requests aggressively. I would suggest changing to using POST for the AJAX request.
Another alternative if you must use GET requests. You can add a unique querystring value to each GET request like this:
var url = 'summary.txt' + '?' + Math.random()*Math.random();
I used this for jQuery AJAX:
$.ajaxSetup({
// Disable caching of AJAX responses
cache: false
});
I think you can find how to use this for JS without jQuery. So the idea is to clear cache before sending the request, because server responds that nothing changed and sends 304 NOT MODIFIED instead of 200 OK. Namely, your summary.txt hasn't changed (not modified), so that's what server telling you.
Sorry if this is really obvious, not great at coding and new to cookies so stil trying to get my head round it. I am trying to create a website redirect for my Magento installation. In the index.php I have placed the following code which checks the users IP location, directs them to the correct website and sets a cookie. If a cookie is already set it takes the value from the cookie and directs to a website based on this.
if ((isset($_COOKIE['penstore']) )){
$_SERVER['MAGE_RUN_CODE'] = $_COOKIE['penstore'];
$_SERVER['MAGE_RUN_TYPE'] = "website";
}
else
{
include("geoip.inc");
$ip=$_SERVER['REMOTE_ADDR'];
$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);
$country_code = geoip_country_code_by_addr($gi, "$ip");
geoip_close($gi);
switch($country_code)
{ case "CA": case "US":
$_SERVER['MAGE_RUN_CODE'] = "usa";
$_SERVER['MAGE_RUN_TYPE'] = "website";
setcookie("penstore",'usa',time()+43200);
break;
case "GB":
$_SERVER['MAGE_RUN_CODE'] = "uk";
$_SERVER['MAGE_RUN_TYPE'] = "website";
setcookie("penstore",'uk',time()+43200);
break;
default:
$_SERVER['MAGE_RUN_CODE'] = "int";
$_SERVER['MAGE_RUN_TYPE'] = "website";
setcookie("penstore",'int',time()+43200);
}
}
This all appears to work okay, my problem is finding a way to allow customers to change websites by clicking an image in the header. I have tried several different methods based on code found on the web and this site but I can't get any of it to work. I currently have the following code in my header.phtml:
<script language="text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
location.reload();
}
</script>
<img src="http://mysite.com/images/INT.gif">
<img src="http://mysite.com/images/US.gif">
<img src="http://mysite.com/images/GB.gif">
The idea is that the customer clicks on the image which causes the cookie value to be updated and the current page to be reloaded, which based on the code in the index.php, would cause a different website to load. All that happens is the # gets added to the url?
Edit: To clarify, I'm trying to switch websites, not stores, so can't use Magento store switcher.
I have an <ul id="keuze_lijst"> , an input field with id #sykje and an button with class .search .
Now when i press the button i would like to clear the UL and repopulate it with data, for this i currently got this .js file.
$(document).ready(function() {
$(".search").click(function(){
var searchValue = $("#sykje").val();
$("#keuze_lijst").empty();
$.ajax({
url: 'http://www.autive.nl/frysk/simulator/sim.php?action=getSongs&search='+searchValue,
data: "",
dataType: 'json',
success: function(rows) {
for(var i in rows){
var row = rows[i];
var id = row[1];
var titel = row[2];
var artiest = row[9];
$("#keuze_lijst").append("<li class='mag_droppen'>"+
"<div class='song_left'>"+
"<div class='titel'>"+titel+"</div>"+
"<div class='artiest'>"+artiest+"</div>"+
"</div><!-- .song_left -->"+
"</li>");
}
}
});
});
});
When i remove the ajax command and put something like $("#keuze_lijst").html("hello"); it works fine. But the ajax command isn't working. Though the var searchValue does his work. (ajax uses the correct url). And when i enter that url the page echoes an fine json with multiple rows.
But in my page the ajax script isn't adding the <li>.
What am i doing wrong?
edit: added an jsfiddle -> http://jsfiddle.net/TVvKb/1/
.html() totally replaces the HTML. So at the end, your "#keuze_list will contain </li>.
Just execute one html() command after you build your html into a string var or something.
From a quick glance, I can say that the problem might be with your use of the html() function. This actually replaces the entire html content.
You might want to try using append() or prepend().
Possible Problems:
You are running into a Same Origin Problem. Per default you can only make Ajax-Requests to your own domain. If you need to make cross-domain calls use JSONP or CORS.
Use the html() only once, and hand over your complete string, otherwise you will override your previous html all the time.
You are not landing in the success handler due to an error (e.g. invalid JSON).
Not sure, but I think if you insert a string in the .append() and other jQuery methods, it parses to (valid) HTML first. That means that unclosed tags are closed, making your HTML invalid.
$('<div />'); // parses to <div></div>
So, I assume that your DOM ends up like this this:
$('ul').append('<li>').append('foo').append('</li>'); // <ul><li></li>foo</li></ul>
Please, just format your string first. You don't want jQuery to parse every input.
var str = '<li>';
str += 'foo';
str += '</li>';
$('ul').html(str);
For cross-domain AJAX requests (without JSONP):
proxy.php
header('Content-Type: application/json');
if(empty($_GET['search'])) exit;
$url = 'http://www.autive.nl/frysk/simulator/sim.php?action=getSongs&search=' . $_GET['search'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
curl_close($ch);
Javascript
$.getJSON({
url: 'proxy.php&search='+searchValue,
success: callback
});