I'm not a php-hero so, I try to hidden a section if the user not come from a specific country.
So I did this:
$.get("http://ipinfo.io", function (response) {
$("#country").html(response.country);
}, "jsonp");
<input hidden id="country" type="text" name="country" value="">
This work well and show me the country code (eg. IT).
Now I try to get this value and insert in a IF
$country = $_GET['country'];
$it = "IT";
<?php if ($country != $it): ?>
Code to hidden here...
<?php endif; ?>
What is it wrong here?
Change
$("#country").html(response.country);
to
$("#country").val(response.country);
Because php $_GET saves values.
Also I do not see a reason to do this:
$it = "IT";
<?php if ($country != $it): ?>
You can just do
<?php if ($country != "IT"): ?>
And last but not least you should not access $_GET directly. It is better to use function filter_input which in your case would be filter_input(INPUT_GET, 'country')
EDIT
I do not understand what is the hidden input for. But if you want to show or hide content depending on the country, and you get the country using ajax there is absolutely no need for this input.
Instead of making php condition (<?php if ($country != "IT")...) You can do it in js. Let's say that inside your condition there is a div with class content
Solution
Your html would look more or less like this
<div class="content">
<!-- Your content here -->
</div>
instead of php condition.
And in js you can do something like this
$.get("http://ipinfo.io", function (response) {
if (response.country == "IT") {
$(".content").hide();
}
}, "jsonp");
So what do we do here?
We check if country code equals "IT". If it is true we hide the content. And this is the same what you were doing in php (if country different than IT show content).
EDIT 2
Instead of hiding the div you can remove it
$(".content").remove();
Try hiding via javascript, ajax can run PHP scripts and bring it back into the DOM but you're better off using JS if you don't need a backendscript
$.get("http://ipinfo.io", function (response) {
var country = $("#country").html(response.country);
if(country != "IT"){ document.getElementByID("country").display = "none";
}, "jsonp");
<input hidden id="country" type="text" name="country" value="">
I use the ProcessWise cms, that have their own API. So this answer work only with the ProcessWise cms. ( the best one ;) )
<?PHP
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
$user_ip = getUserIP();
echo "ip: " . $user_ip . "<br />";
$http = new WireHttp();
$url = "http://ipinfo.io/{$user_ip}/country";
$response = $http->get($url, ['country' => '']);
echo "Country: " . $response . "<br />";
echo "Successful response: " . $sanitizer->entities($response) . "<br />";
?>
Related
I am trying to make an search box which to display the "Address" from MYSQL/PHP
I have used ajax to refresh page without leaving page, but when I run in browser, it always give me an error. when I used console, the return result of echo $_POST['name'] = ( html code of header.php + "What I need" + html code of footer.php )
<?php
include 'header.php';
include 'Connect.php';
if( isset($_POST['ajax']) && isset($_POST['name']) ){
echo $_POST['name'];
exit;
}
?>
<form method="POST">
<label>Username</label>
<input type="text" name="name" required="required" id='name'>
<div id='response'></div>
</form>
<script>
$(document).ready(function(){
$('#name').keyup(function(){
var name = $('#name').val();
$.ajax({
type: 'post',
url: index.php,
data: {ajax: 1,name: name},
success: function(response){
$('#response').text(response);
}
});
});
});
</script>
<?php
if(isset($_POST['name'])){
$username = $_POST['name'];
$stmt = $con->prepare("SELECT Username, FullName, Adresse, Email, Phone FROM dbo.users WHERE Username= ?");
$stmt->execute(array($username));
while($row=$stmt->fetch(PDO::FETCH_ASSOC))
{
$Username = $row["Username"];
$FullName = $row["FullName"];
$Adresse = $row["Adresse"];
$Email = $row["Email"];
$Phone = $row["Phone"];
echo "<tr>
<div>
<td>".$Username."</td>
<td>".$FullName."</td>
<td>".$sEID."</td>
<td>".$Email."</td>
<td>".$Phone."</td>
</div>
</tr>";
}
echo "</table>
</div>";
} else echo '<div class="alert alert-danger"> This Name <strong>is not exit</strong></div>';
include $tpl.'footer.php';
}
?>
Your question isn't very clear... if i understand correctly... this is broken by design, you're calling the page itself and update #name with the content of the entire page, thats why you see html + "what you need" (the response): the response is the whole page.
The right way to do this would be to move the second part of PHP code (where you perform the query ecc.) on a separate script and then call that new script by putting its name as the url parameter in the ajax call.
thank you for your respanse, i want to use the value returned by ajax to use with MYSQL/PHP to echo $row['Address'];
if i move the second part of PHP code the result is
echo $_POST['name'] = ( "What I need" + html code of footer.php )
I've tried researching, but I'm not even sure how to research this question as most of the answers relate to pure jQuery, PHP or HTML, but nobody seems to have the same problem - which probably means I'm missing something blatantly obvious...
I have a form with a select box. On change of the select box, I call a jQuery.post to a functions page with a php/mysql query and html. I pull that information back inside my form and it works beautifully. However, when I post the form, the variable $_POST['subcat'] is empty. Here is the code:
Form:
<li><h3><?php echo 'Market:';?></h3>
<script>
function display_subcat(vals)
{
jQuery.post("<?php bloginfo('siteurl'); ?>/?get_subcats_for_me=1", {queryString: ""+vals+""}, function(data){
if(data.length >0) {
jQuery('#sub_cats').html(data);
}
});
}
</script>
<p><select class="do_input_new" name="market" onchange="display_subcat(this.value)" >
<option value="">Select Market</option>
More Options...
</select>
<br/><span id="sub_cats">
</span>
</p></li>
Functions:
if(isset($_GET['get_subcats_for_me']))
{
$cat_id = $_POST['queryString'];
if(empty($cat_id) ) { echo " "; }
else
{
$args2 = "orderby=name&order=ASC&hide_empty=0&parent=".$cat_id;
$sub_terms2 = get_terms( 'project_cat', $args2 );
if(count($sub_terms2) > 0)
{
$ret = '<select class="do_input_new" name="subcat">';
$ret .= '<option value="">'.__('Select Subcategory','ProjectTheme'). '</option>';
foreach ( $sub_terms2 as $sub_term2 )
{
$sub_id2 = $sub_term2->term_id;
$ret .= '<option '.($selected == $sub_id2 ? "selected='selected'" : " " ).' value="'.$sub_id2.'">'.$sub_term2->name.'</option>';
}
$ret .= "</select>";
echo $ret;
}
}
die();
}
Now, when I submit the form, the variable $submarket = $_POST['subcat']; is empty. Everything else works (the class is what I expect, the data is what I expect), but it seems the name="subcat" isn't coming through to the $_POST. print_r($_POST) doesn't list subcat. Thoughts?
I'm an idiot. The above code worked perfectly. My problem was that the start of my <form> was in a <div> that I closed out before the majority of the form. I suppose since all the other elements were loaded on the same page that they came over in the $_POST, but because "subcat" was new, and after the <div> closed, it didn't get picked up in the $_POST. The form closed long after this particular element, so it must have been because it wasn't original. Thank you for your help #jcaron!!
kinda got lost here, i want to change a class='label' according to the data pulled out of db with Django. So according to {{account.status}} I will have either class='label-danger' or 'label-info'
My .js
$(document).ready(function () {
if($('#label').attr('value').val() == 'New'){
$('#label').addClass('label-info');
};
else($('#label').attr('value').val() == 'Rep'){
$('#label').addClass('label-warning');
};
else($('#label').attr('value').val() == 'Progress'){
$('#label').addClass('label-success');
};
});
My Html:
{{account.status}}
I think you can do this
PHP:
<?
$getClass = mysql_query("SELECT class FROM myTable");
while($rows = mysql_fetch_array($getClass)){
$class = $rows["class"];
?>
<h1 class='<?php echo $class; ?>' >Hello</h1>
<?
}
?>
I think is may work,but i don't test this yet,still hope it can deal with you job
I am in a big trouble. It's 2:45am and I have been since 6pm searching for ideas or examples or whatever you wanna name it!
I have this js function called from a but I can get it to work AT ALL.
The idea is type you city name and get suggestion in a select box. Than, from the select box you can click in one of the cities and this information going back to your form field.
There are two files: index.php (js function showhint and a form calling another .php file to load the cities as suggestions)
The code can be see at www.bfamily.net
I will be very great-full for any help.
Regards,
Add an event onchange on your select to set the value
function(inputName, event) {
document.getElementByName(inputName)[0].value = event.target.selectedOptions[0].value;
}
But I recomand you to do something like that on your inputs :
<input type="text" name="zipCode1" onkeyup="showHint(this.value)" size="20" value="" style="text-transform:uppercase" list="suggestion">
<datalist id="suggestion">
<option>Houston, TX 77070</option>
<option>Cypress, TX 77433</option>
<option>Cypress, TX 77429</option>
</datalist>
Of course you can either generate the datalist with PHP on the page load or with an AJAX request.
May be this will be helpfull
if (filter_var($q, FILTER_SANITIZE_STRING) || !filter_var($q, FILTER_SANITIZE_STRING) === false) {
if ($q !== "") {
$str = "<select name='suggestion'>";
$q = strtolower($q);
$len=strlen($q);
foreach($zipArray as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name.'<br/>';
} else {
$hint .= "$name".'<br/>';
}
$suggestion[] = $name;
$str .= "<option value='".$name."'>".$name."</option>";
}
}
$str .= "</select>";
if(count($suggestion) > 0) echo $str
}
}
But I think the better way is to have a hidden selectBox in your html and then send json "suggestions" list from .php to your .js file from Ajax and then there add proper options to your selectBox and make it visible
I have been working on this for some time now. I have a php file that has a div which reads a directory and loads the files in the directory into a dropdown. When the user selects from the file the file gets selected and teh operation is performed. However, the file name does not disappear from the dropdown until the page is refreshed. I have tried '.load' and it doesn't work. As in, the content of the div does not get updated.
My code is as follows:
This is the PHP file:
<div id="mgA" class="form-group">
<label>Management Address:</label>
<?php
$path = "/licenses/ve/address/unused";
clearstatcache();
$files = array();
$handle = opendir($path);
echo '<select required id="mgmtAdd" class="form-control select2" style="width: 100%;">';
while ($file = readdir($handle)) {
if (substr($file,0,1) != ".") {
$files[]=$file;
}
echo "<option selected = 'selected' value='0'>Select</option>";
natsort($files); //sorting
foreach($files as $file){
echo "<option value ='$file'>$file</option>";
}
echo '</select>';
if (is_dir_empty($path)) {
echo "Max no of hosts already created";
}
function is_dir_empty($path) {
if (!is_readable($path)) return NULL;
return (count(scandir($path)) == 2);
}
closedir($handle);?>
This is the button which on click the div should reload all the contents again:
$( "#vServer").on( "click", function(e) {
e.preventDefault();
$("#mgA").load(virtualDialog);
alert("refreshed");
virtualDialog.dialog( "open" );
});
Please let me know if anyone has any idea, any help is appreciated! Thank you!
As epascarillo has pointed out, you are using load() incorrectly. This may be more in line with what you wish to do but I did not test (or even check very closely) your PHP code.
I am also assuming that the div #mgA is the content of the jQueryUI dialog that you are opening with virtualDialog.
javascript/jQuery:
$( "#vServer").on( "click", function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'ajax-reload.php',
success: function(d){
$("#mgA").html(d);
virtualDialog.dialog( "open" );
}
});
});
ajax-reload.php
<?php
$path = "/licenses/ve/address/unused";
clearstatcache();
$files = array();
$handle = opendir($path);
$out = '<select required id="mgmtAdd" class="form-control select2" style="width: 100%;">';
while ($file = readdir($handle)) {
if (substr($file,0,1) != ".") {
$files[]=$file;
}
$out .= "<option selected = 'selected' value='0'>Select</option>";
natsort($files); //sorting
foreach($files as $file){
echo "<option value ='$file'>$file</option>";
}
} //<=== this brace was missing
$out .= '</select>';
if (is_dir_empty($path)) {
$out = "Max no of hosts already created";
}
function is_dir_empty($path) {
if (!is_readable($path)) return NULL;
return (count(scandir($path)) == 2);
}
closedir($handle);
echo $out;
?>
See these additional examples of simple AJAX -- sometimes it helps to see the really simple examples:
AJAX request callback using jQuery