Just like the title above: how to concatenate two strings in JQuery?
This is my code so far:
$(document).ready(function(){
serviceName = '<?=$_GET['services'] . ".php";?>';
serviceID='<?= "#" .$_GET['services'];?>';
serviceClass = '<?=$_GET['services'];?>';
if (serviceName != "") {
alert(serviceID);
$('.main_content').load(serviceName);
$(serviceID).addClass("it");
}
});
As you can see in my above code, in variable name serviceID, I am concatenating hashtag and my GET value and I try to put it on ALERT and the result is correct, but when I assign it to .addClass it’s not working.
Any alternatives and solution is much appreciated.
I guess you meant that the PHP code should be evaluated before arriving to the client, therefore your code syntax is correct, but check out the following looks cleaner and also not polluting the global JavaScript scope (that's what the var ... is for):
var serviceClass = '<?="{$_GET["services"]}";?>';
var serviceName = serviceClass+'.php';
var serviceId = '#'+serviceClass;
but, since your code syntax is correct, you should verify that you actually have an element with serviceId as the id when your are executing it
if (($(serviceId)||[]).length) {
alert('your element with the id:'+serviceClass+' exists');
}
else {
alert('your element with the id:'+serviceClass+' doesn\'t exists');
}
i hope this one solve the issue:
<script>
$(document).ready(function(){
serviceName = '<? echo "./".$_GET["services"].".php";?>';
serviceID = '<? echo "#" .$_GET["services"]; ?>';
serviceClass ='<? echo $_GET["services"]; ?>';
console.log(serviceID);
if(serviceName!=""){
alert(serviceID);
$('.main_content').load(serviceName);
$(serviceID).addClass("it");
}
});
</script>
also check the console in your browser (firebug or chrome developer tools) to see the output ,fit your criteria
Try as but not sure, My change is append "#" Id in jquery
<script>
$(document).ready(function(){
serviceName = '<?=$_GET['services'] . ".php";?>';
serviceID='<?= $_GET['services'];?>';
serviceClass = '<?=$_GET['services'];?>';
if(serviceName!=""){
alert(serviceID);
$('.main_content').load(serviceName);
$("#"+serviceID).addClass("it");
}
});
</script>
Related
My URL is something like this: www.website.com/referral456
In the checkout page of my ecommerce I have a referral field that users have to manually complete with the referral number (in that case 456).
How this field could autocomplete itself directly from the URL?
Just get the current url or param passed (if your app has a router etc).
Then just strip all but the numbers from the string:
<?php
$_SERVER['REQUEST_URI'] = '/referral456';
$value = basename($_SERVER['REQUEST_URI']);
echo preg_replace('/[^0-9]/', '', $value); //456
Then populate the field with it.
https://3v4l.org/F17g6
window.onload = function(){
var param = this.href.substr(this.href.lastIndexOf('/') + 1);
document.getElementById('input#userInputField').value=param;
}
Try this
window.onload = function(){
var getRefId = location.href.split('/')[1].replace('referral','');
document.getElementById('input#refId').value = getRefId ;
}
You could get the url using location.href divide it using split(), and selecting the second element (1) that is referral454654654, then, using replace() you replace referral part with nothing. At the end you have only the number in refId. Here the example:
window.onload = function(){
var refId = location.href.split('/')[1].replace('referral','');
document.getElementById('input#refId').value = refId;
}
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 1 year ago.
I have some information from my db that is being loaded onto my page, but I would like to be able to use an if statement regarding the value of this, and then assign a javascript value to be a boolean value. How can I go about this? (at the moment I am just printing the value)
<?php
if ($_SESSION['loggedin'] = true){
print_r($_SESSION['userlevel']); // THIS IS WHAT I WANT TO SPECIFY IN AN IF STATEMENT
}
?>
<script>
var userloggedin = false;
</script>
What I would like to do in pseudocode:
<script>
var userloggedin = false;
function somefunction(){
if (userloggedin == true){
//Do stuff...//
}
}
</script>
Sorry for my lack of knowledge on the subject, I'm only beginning to learn backend web development.
Have you tried searching the forum for any previous posts with regards to parsing PHP variables to javascript?
With a simple search I found a feed relating to parsing PHP variables to JavaScript here:
Get variable from PHP to JavaScript
Anyway, from my understanding of your problem does this serve as a suitable answer?
<?php
if ($_SESSION['loggedin'] == true){
$userLevel = $_SESSION['userlevel'];
$userLoggedIn = true;
}
else {
$userLevel = null;
$userLoggedIn = false;
}
?>
<script type="text/javascript">
var userLoggedIn = "<?php Print($userLoggedIn); ?>";
var userLevel = "<?php Print($userLevel); ?>";
if (userLoggedIn == true) {
if (userLevel == "levelOne") {
//Your code here
}
else if (userLevel == "levelTwo") {
//Your code here
}
else {
//Your code here
}
}
</script>
You can echo bits of Javascript code from PHP, like this:
<script>
var userloggedin = <?php echo ($_SESSION['loggedin'] ? 'true' : 'false'); ?>;
</script>
First change your if statement to use == double equal signs if you want the expression to work as expected. Then you can simply echo a variable into javascript as in example below:
Simple solution would be similar to:
<?php
if ($_SESSION['loggedin'] == true){
$logged_in = "true";
} else {
$logged_in = "false";
}
?>
<script>
var userloggedin = <?php echo $logged_in;?>;
</script>
You can set a javascript variable with a php value by:
<script>
var jsVar='<?php echo $phpVar ?>';
</script>
A simple solution would be just to echo variable value in script tag. But this is unsafe, because variable is global, meaning it can be modified in client-side console.
Better solution would be an ajax request and php script that returns some response, this way the variable is scoped to ajax response function, so it's safe from modifications. Here's an example:
...
echo json_encode($_SESSION['loggedin'] ? 'true' : 'false');
...
In javascript, you can use jquery .get() request:
$.get("userLoggedIn.php", function(data) {
var response = JSON.parse(data);
if(data === true) {
// user is logged in
}
else {
// not logged in
}
});
If it's important that this functionality is handled before anything else, an synchronous ajax request:
$.ajax({
url: "userLoggedIn.php",
async: false, // this makes request synchronous
success: function (data) {
var response = JSON.parse(data);
if (data === true) {
// user is logged in
} else {
// not logged in
}
});
Synchronous request means that client will wait for request to finish before doing anything else. It's not recommended to be used a lot, but sometimes it's the only way to go about.
So here i am trying to call a function that passes 2 values as parameters (added dynamically using php). The damn thing doesn't seem to work no matter what i try. Can any of you guys point out what i'm doing wrong? Here is the code:
// HTML/PHP
$pid = $row['postID'];
$pt = $row['postTitle'];
//There arrays are working great.
Delete // Does not call delpost
Delete // BUT if i remove the second parameter, it works! How?
// JS
<script language="JavaScript" type="text/javascript">
function delpost(id, title) {
if (confirm("Are you sure you want to delete" + title + "?")) {
window.location.href = 'index.php?delpost=' + id;
}
}
</script>
The quotes on "delpost are wrong. delpost is a function so onclick"<?php echo delpost($pid,$pt); ?>" should work.
Delete // Does not call delpost Delete // BUT if i remove the second parameter, it works! How?
first delete is not working because when you are passing two value on a function one value is blank that why its not working
<?
$pid = 1;
$pt = 2;
//There arrays are working great.
?>
Delete // Does not call delpost
Delete // BUT if i remove the second parameter, it works! How?
<script language="JavaScript" type="text/javascript">
function delpost(id, title) {
alert(id);
if (confirm("Are you sure you want to delete" + title + "?")) {
window.location.href = 'index.php?delpost=' + id;
}
}
</script>
Delete
I tried your code directly and it worked, but i also have added another way of writing it:
<?php
$pid = 42;
$pt = 'Awesometitle 2000';
?>
Delete
Delete 2
<script>
function delpost(id, title) {
console.log(id);
console.log(title);
}
</script>
Both variations should print 42 and "Awesometitle 2000" in your console.
To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.
you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});
Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.
Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!
I am trying to write a function like this:
if ( document.url!= 'search.php') {
window.location = 'search.php'
}
This is not working; it seems I may need to check if URL string contains 'search.php' - or is there another way I can do this check?
It sounds like you're searching for indexOf. Note that it's not document.url, but document.URL:
if (document.URL.indexOf('search.php') == -1) {
window.location = 'search.php';
}
Note: This will also match the following:
http://www.domain.com/search.php
http://www.domain.com/index.php?page=search.php&test
http://www.domain.com/search.php/non-search.php
http://www.domain.com/non-search.php#search.php
Extra note: Why are you doing this? If people have javascript disabled, they will never get forwarded. Maybe you're searching for the 301 or 302 header?
I always use this.
if (window.location.href != 'search.php') {//get the current url
window.location.href = 'search.php' //redirect
}
Try any of these
- alert(document.URL)
- alert(Window.location.href)
- alert(document.location.href)
- alert(window.location.pathname)
for creating dropdown with links -:Put this in the success part of your ajax
var data=JSON.parse(xmlhttp.responseText);
var alldata;
for(var i=0;i< data.length;i++)
{
alldata += "<a id='some_id' onclick='myFunction(this.id);' href='whatever#' class='link'>"+data[i][0]+"</a><hr>";
}
//data[i][0]-->this depends on your json text.
document.getElementById('your_input_field_id or div_id').innerHTML = alldata;