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
Related
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 />";
?>
I am using following code to pass PHP variables to javascript. but it is not working.
function gto(str) {
document.getElementById('goto').action = str;
document.getElementById('ID').value = <?php echo "$userid" ?>;
document.getElementById('name').value = <?php echo "$user_name" ?>;
document.getElementById('gname').value = <?php echo "$usergname" ?>;
document.getElementById('fmname').value = <?php echo "$userfname" ?>;
document.getElementById('img').value = <?php echo "$userimg" ?>;
document.getElementById('email').value = <?php echo "$useremail" ?>;
document.getElementById('goto').submit();
}
Following is the PHP code
<?php
if($_POST["name"] == null)
{
$user_name = 'Annomyous';
}
else{
$user_name = $_POST["name"];
$userid= $_POST["id"];
$usergname= $_POST["gname"];
$userfname= $_POST["fname"];
$userimg= $_POST["img"];
$useremail= $_POST["email"];
}
echo "<p style='color : white'>$user_name";
echo "$userid" ;
echo "$gname";
echo "$fname";
echo "$img";
echo "$email";
echo "$user_name";
echo "$user_name</p>";
$user_name =htmlspecialchars($user_name);
$user_name =str_replace("<script>","", $user_name);
?>
the output is a follows:
ReAlItY TuTs104598758504708047866ReAlItY TuTsReAlItY TuTs//this is php echo output.
JAVASCRIPT OUTPUT:-
function gto(str) {
document .getElementById('goto').action = str;
document.getElementById('ID').value = ;
document.getElementById('name').value = Annomyous;
document.getElementById('gname').value = ;
document.getElementById('fmname').value = ;
document.getElementById('img').value = ;
document.getElementById('email').value = ;
document.getElementById('goto').submit();
}
Function gto is called here:
<button class="w3-btn header-btn" onclick="gto('Contact.php');">Contact Us</button>
I can see in PHP output I am getting all variable output.
but nin juavascript im getting only Annonymous why????
I need to pass post variables to contact us so i am using the form tag and javascript but this is not working Please help me!
Thanks in Advance
values from php to js can be passed in many ways, here's one of them
try to pass the php values when calling the js function, like this:-
<button onclick="gto('Contact.php','<?php echo $userid;?>','<?php echo $username;?>');">Contact Us</button>
and then get values on js function like this:-
function gto(str,userid,username) {
document .getElementById('goto').action = str;
document.getElementById('ID').value = userid;
document.getElementById('name').value =username;
}
that's it, now use the values in js as your wish
Uh, found another issue. The js is in smart quotes, which won't work... "`" is invalid. use "'".
Also, w3schools can't handle php in their editor, so it's no use.
Example for POST requests: https://www.w3schools.com/code/tryit.asp?filename=FQSA8MJYGJ47
Hope this helps.
So what I'm trying to do is the following:
first: When the button add-location is clicked this loads a php file using AJAX.
jQuery
$('.add-location').click(function() {
var locationName = $(this).data('location');
$.post('http://www.example.com/reload-location-2.php?addparam',
{locationName: locationName}, function(data) {
$("textarea#location").html(data);
})
});
PHP FILE
<?php start_session();
$locationName = array_key_exists('locationName',
$_POST) ? (string) $_POST['locationName'] : '';
if(isset($_GET['delparam'])){
unset($_SESSION['locations'][$locationName]);
}
if(isset($_GET['addparam'])){
$_SESSION['locations'][$locationName] = $locationName;
}
?>
<?php foreach ($_SESSION['locations'] as $location): ?>
<?php echo htmlspecialchars($location); echo "\n"; ?>
<?php endforeach;?>
This all works like a charm! No worries here. No what I'm trying to do is when the button add-location is clicked this echo's the following code to a div called textarea#thema.
<?php foreach ($_SESSION['products'] as $product): ?>
<?php echo htmlspecialchars($product); echo "\n"; ?>
<?php endforeach;?>
OR, if that's easier when the page is loaded -> echo that code to the textarea#thema div.
I do not understand AJAX that much but I'm getting there. But I think the last option maybe the easiest solution?
Could anyone help me figure this one out?
What I tried
Right now, When the button add-location is clicked I reload a previous jQuery script:
$('.add-location').click(function() {
var productName = $(this).data('product');
$.post('http://example.com/reload-2.php?addparam',
{productName: productName}, function(data) {
$("textarea#thema").html(data);
})
});
This works, but it adds an extra <p>-tag leaving me with a line break in the code.
I also changed the .html(data); to .val(data); for the textareas. Also I made a new PHP file with just this code:
<?php foreach ($_SESSION['products'] as $product): ?>
<?php echo htmlspecialchars($product); echo "\n"; ?>
<?php endforeach;?>
And this jQuery code:
$('.add-location').click(function() {
var productName = $(this).data('product');
$.post('http://www.example.com/reload-3.php',
{productName: productName}, function(data) {
$("textarea#thema").val(data);
})
});
But still no go... And I don't think this is the way to go?? I hope I gave enough information.
You should use .val() function to fill textarea, not .html().
I am currently having trouble with this. I would like to make one of my variables in Javascript have a PHP value. Here is what I mean:
<script>
JSvariable = <?php echo $PHPvariable; ?>;
</script>
For some reason that is not working. Here is my full (snippet) of code:
<script>
currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
I am sure it is some stupid mistake, but I can not seem to find it! What is the problem? Thank you!
PS #parentcommentholder is an input field, and it just had the value 0 after the field is supposed to of been changed.
Here is some source:
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<script>
var currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
<input id="parentcommentholder"></div>
Don't forgot for give quotes ' or ". Use following:
<script>
var JSvariable = '<?php echo $PHPvariable; ?>';
//or
var JSvariable = "<?php echo $PHPvariable; ?>";
</script>
Reason: If php variable contains string and if while assigning it to javascript variable we shall not give quote like:
<?php $PHPvariable = 'String';?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = String;//which will give error in javascript
But this will work fine if PHP variable contains a numeric value like:
<?php $PHPvariable = 2;?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = 2;//which will work perfect
Complete code should be:
<script>
var currentreplyid = "<?php echo $allpostcomments[$key]['replyid']; ?>";
//or if you are sure your variable contains int value
var currentreplyid = parseInt("<?php echo $allpostcomments[$key]['replyid']; ?>");
$('#parentcommentholder').val(currentreplyid);
</script>
Try the below instead of using javascript (as I don't think you need it):
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<input id="parentcommentholder" value="<?php echo ((int)$allpostcomments[$key]['replyid']>0) ? $allpostcomments[$key]['replyid'] : 0; ?>" />
<?php
}
?>
If your defiantly sure $allpostcomments[$key]['replyid'] is bringing back a value, this should work without any issues.
I'm build an hybrid app based on JqueryMobile. And now I'm trying to get a simple array with the categorys that I select from my mysql table. I saw many questions related to this and tired a thousand solutions but nothing worked.
Here's what I have:
PHP Code:
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
while($row = mysql_fetch_assoc($sql)) {
$id[] = $row;
//$id[] = $row['Tipo']; doesn't work either
}
echo json_encode($id);
mysql_close($conn);
with this I get blank result.
The closest I got was with this:
$id=array();
$i=0;
while ($row = mysql_fetch_assoc($sql)) {
$id[] = array("data$i" => $row['Tipo']);
echo json_encode($id[$i]);
$i++;
}
with the result:
{"data0":"Restaurantes"}{"data2":"Shopping"}{"data3":"Eventos"}{"data4":"Hoteis"}{"data5":"Oficinas"}{"data6":"Combustiveis"}
but this is obviously wrong because it has multiple json_encode invocations.
Im trying to get it with Jquery's .$get
<script type="text/javascript">
var inicio=function(argument){
$("#submit").click(function(e){
e.preventDefault();
$.get('http://myurl/get_category.php',{
},function(answer){
alert(answer.length+" "+answer); //trying to know whats happening with the data.
for (var i = 0; i < answer.length; i++) { //my final objective is to fill a listview.
$('#list').append("<li> <h3>"+answer.tipo+"</h3></a></li>");
}
$('#list').listview('refresh');
},"json"
);
});
}
$(document).on('ready',inicio);
</script>
As I said I searched into many questions and solutions but always got null values. I don't have too much experience with PhP and this is me studying and making experiences with JqueryMobile so.. something's wrong here that I can't see..
Thank you.
Found the solution here on this post
Everything on the DB must be set to UTF-8 or utf8mb4 and now it's finally working. Apreciated everyone's help :)
Try something like this...
If you want only to get the values of column 'Tipo',
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
$i=0;
while($row = mysql_fetch_assoc($sql)) {
$id["data".$i] = $row['Tipo'];
$i++;
}
echo json_encode($id);
mysql_close($conn);
If you awnt to get all the values,
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
$i=0;
while($row = mysql_fetch_assoc($sql)) {
foreach($value as $key=>$value){
$id["data".$i][$key] = $value;
}
$i++;
}
echo json_encode($id);
mysql_close($conn);
You can use the following query:
$sql=mysql_query("SELECT Tipo FROM tfc_db.Category ");
$id=array();
while($row = mysql_fetch_assoc($sql)) {
$id[] = $row['Tipo'];
}
echo json_encode($id);
mysql_close($conn);
It will return the categories as an array of strings in JSON. e.g. ["entry 1","entry 2"]. If you decide to use this then you would need to adjust your Javascript code.
Your javascript code contains some problems on this line:
$('#list').append("<li> <h3>"+answer.tipo+"</h3></a></li>");
In the case of you using
$id[] = $row;
In PHP, then the column name would be named Tipo, not tipo (case sensitive). The second issue is that you are trying to access answer.tipo and not the element of the array answer[i].tipo.
So with your current php code you can make it working by changing the javascript.
This line
$('#list').append("<li> <h3>"+answer.tipo+"</h3></a></li>");
To
$('#list').append("<li> <h3>"+answer[i].Tipo+"</h3></a></li>");
Edit: Since your apparently having issues here is the full code I used.
//query.php
<?php
mysql_connect ('localhost','username','password');
mysql_select_db('db_test');
$sql=mysql_query("SELECT Tipo FROM db_test.Category ");
$id=array();
while($row = mysql_fetch_assoc($sql)) {
$id[] = $row;
}
echo json_encode($id);
mysql_close($conn);
?>
<html>
<head>
<title> JQuery db test </title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id='list' class='list'>
</div>
<script>
var debug;
$.get('http://www.example.com/test/query.php',{
},function(answer){
debug=answer;
//alert(answer.length+" "+answer); //trying to know whats happening with the data.
for (var i = 0; i < answer.length; i++) { //my final objective is to fill a listview.
$('#list').append("<li> <h3>"+answer[i].Tipo+"</h3></a></li>");
}
// $('#list').listview('refresh');
},"json"
);
</script>
</html>
[PHP]
$id = array();
while($row = mysql_fetch_assoc($sql))
$id[] = $row['Tipo'];
echo json_encode($id);
[JS]
$(document).ready(function(){
$('#submit').click(function(e){
$.ajax({
url: '/get_category.php',
type: 'GET',
dataType: 'json'
}).done(function(res){
$('#list').html('');
for(var i=0;i<res.length;++i)
$('#list').append('<li><h3>'+res[i]+'</h3></li>');
});
});