Concatenate php variables and symbol to javascript function in php echo - javascript

I finally got the php variables to pass to the javascript function but they are passing as multiple and getting a warning.
Use of undefined constant app_name - assumed 'app_name'
How can i define the variables?
echo('<li> <a href="#" onClick="runthis(\''.str_replace("'", "\\'", $row[activity]).'\',\''.str_replace("'", "\\'", $row[app_name]).'\');">');
Javascript
function runthis(activity) {
alert(activity);
//$('#live-area').load('../assets/php/multibox.php?id=' + activity);
}
I am trying to concat $row[activity] and $row[app_name] with /
my php explodes on / and breaks into variables
UPDATE
Here is what im doing with the data.
if (isset($_GET['id'])) {
$app = $_GET['id'];
$array2 = explode('/', $app);
$activity = $array2[0];
$app_name = $array2[1];
$SQL1 .= "WHERE activity = '$activity' ";
}
I don't think im handling the string properly.
What should this look like?
I updated the echo onClick to this
echo ('<li> <a href="#" onClick="runthis(\'' . $row['activity'] . '/' . $row['app_name'] . '\')">');
It passes correctly to javascript but when $_GET loads it i get no results

You're dumping PHP output into Javascript context. Use json_encode() to do this properly:
echo '<li>..... ', json_encode($row['activity']), '</li>';
As it stands right now, your array keys aren't quoted, which'll probably cause PHP to issue various warnings, and those warnings will get output in your JS code, causing syntax errors.
json_encode() will take care of ALL the necessary quoting/escaping for you. It'll also be far more readable/maintainable than the abomination you've come up with.
comment followup, split onto 3 lines for a bit more legibility:
echo '<li> <a href="#" onClick="runthis(';
echo json_encode("{$row['activity']}/{$row['app_name']}");
echo ')">';

You're getting Use of undefined constant app_name - assumed 'app_name' because you're saying $row[app_name] instead of $row['app_name'].

Related

Copy php variable to a JavaScript variable cause Design issue

**This is my code **
I am sending copying data from a php variable to a JavaScript variable here
<?php
include('includes/config.php');
include('includes/classes/Artist.php');
include('includes/classes/Album.php');
include('includes/classes/Song.php');
if(isset($_SESSION['userLoggedIn'])){
$userLoggedIn = $_SESSION['userLoggedIn'];
echo "<script>userLoggedIn = '$userLoggedIn';</script>";
// echo "<script>console.log('$userLoggedIn')</script>";
}else{
header('location:register.php');
And if i use the echo statement in the if statement here
it cause this. see the left side navigation bar;
Error image
And if i don;t use the echo statement the page is fine looks like this
Without error
I can't access the picture you uploaded right now, but I saw an error
echo "<script> var userLoggedIn = '" . $userLoggedIn . "'; alert(userLoggedIn); </script>";
Change the part we print on the screen in this way, data will be displayed on the screen.
I used this code inside the body of the html part and it works fine
<?php
if($userLoggedIn){
echo "<script>userLoggedIn = '$userLoggedIn';</script>";
}
?>

How to pass php variable in window.location javascript

I want to pass the php variable inside the window.location javascript this is my php code and i am unable to do that.
echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.'"&sDate="'.$startdate.'"&eDate="'.$enddate;</script>';
try to set quotation marks
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'"</script>';
You are closing your quote in JS
echo '<script>location.href = "reportConsumption.php?creategenReport="'.$genid.'"&sDate="'.$startdate.'"&eDate="'.$enddate;</script>';
Should be
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'</script>';
This will cause an error in JS on the client side, you could see this by pressing f12 and looking in the console log in the browser debugger. Your source code will look like this
<script>location.href = "reportConsumption.php?creategenReport="35"&sDate="...
//where this is a quoted block
"reportConsumption.php?creategenReport="
//and this is just chilling in space
35
//and then a new quoted block, etc.
"&sDate="
And you had this other (php syntax error) issue I took the liberty of fixing.
.$enddate;</script>';
Just in PHP you can redirect with
header("Location: $url");
But you have to be sure of 2 things:
You do not output "Anything" not even a line return before calling header
You call exit(); immediately after it. If you don't PHP will continue to execute the current script after it executes the redirect. Which is probably not desirable.
You are closing the double quotes too early. It should be close at the end of the URL. So you have a syntax error in your JavaScript:
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate.'";</script>';
Or separate using a variable to be more clear:
$url = 'reportConsumption.php?creategenReport='.$genid.'&sDate='.$startdate.'&eDate='.$enddate;
echo '<script>location.href = "'.$url.'";</script>';
You should not use double quote around the values for GET param
echo '<script>location.href = "reportConsumption.php?creategenReport='.$genid.
'&sDate='.$startdate.'&eDate='. $enddate .'"';</script>';

In WordPress how do I pass multiple variables into the URL and retrieve them?

For some reason I can only retriever the first variable, in this instance, "product_category" out of the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon .
I'm outputting javascript to confirm that I've set the variable, but again, only coffee will be alerted, and not brand. I'm using WordPress's 'get_query_var'. See code below:
<?php
echo '<script> product_category = "' . get_query_var('product_category') . '";
brand = "' . get_query_var('brand') . '";
alert(product_category);
alert(brand);
</script>';
?>
Any help would be appreciated - I'm struggling to solve it!
Since you are testing, maybe you could test the php directly? The function get_query_var is just a wrapper for the generic php array $_GET. You should have these values available at $_GET['product_category'] and $_GET['brand']. But instead of assuming everything is where it is supposed to be, why not check what you actually have?
<?php
add_settings_error("var-test", "var-test", implode(", ", array_keys($_GET)));
?>
Disclaimer: I am a Drupal developer, not Wordpress, but they are both php.
I am using the documented message tool here, for a little cleaner php code.
https://codex.wordpress.org/Function_Reference/add_settings_error
You could still use your javascript if you would like:
<?php
echo '<script> alert( '. implode(", ", array_keys($_GET)) .');
</script>';
?>
Second possibility. The reason for using a wrapper function instead of the raw core is for what it provides in that wrap. My normal assumption is sanitation and security filters, which are poor for testing but essential for production environments. However, with a little bit of reading on the function you are using, it says it only returns values for known query objects and if you are using custom variables in the url you should register them. https://codex.wordpress.org/Function_Reference/get_query_var
Have you registered "brand"?

calling a php function, within html code, within a php echo statement

Ok so ive looked at AJAX and to be honest im having trouble understanding how i am going to apply it to my code. Il go into more depth about what i am trying to do, and maybe someone can help me better understand how to incorporate an AJAX call.
So i have one function, called add_signups which takes in 3 parameters and inserts some data into a mysql table.
function add_signup($society, $student_email, $event) {
$member_fields = array('name','student_num','student_email',);
$fields = '`' . implode('`, `',($member_fields)) . '`';
$query = mysql_query("SELECT $fields FROM `$society members` WHERE `student_email`='$student_email'");
$elems = mysql_fetch_assoc($query);
array_walk($elems, 'array_sanitize');
$data = '\'' . implode('\', \'', $elems) . '\'';
$result = mysql_query("INSERT INTO `$event` ($fields) VALUES ($data)");
}
I have another method, called get_names which prints a list of email addresses. I am trying to call the add_signup method once a user clicks on one of the email addresses, this will insert that users email address, along with some other info into the table.
function get_names($society, $event){
$records= mysql_query("SELECT `student_email` FROM `$society members` ORDER BY `student_email`");
while($emails = mysql_fetch_assoc($records)){
echo ' <li style="cursor:pointer;" onclick="' add_signup($society, $emails['student_email'], $event) '); ">' .$emails['student_email'] . "</li>";
}
}
What i dont understand is where to put what in terms of using an ajax call. Im thinking i need to put the add_signup() method in a seperate php file, then in the html file within <script> tags put the following
function jsfunction(){
$.ajax({
type: "POST",
url: "add_signupmethod.php",
data: { "what to put here??" },
success: " what to put here? "
});
}
obviously i would need to change the onclick event to call the js function but is that anywhere near correct?
Or do i even need to use ajax and is there a much easier way of doing it? Ive been stuck on this for almost two days now, the frustrating thing is i know that the add_signup() function works as i tested it outside of the otherfunction. Would greatly appreciate anyone helping me out with this.
Original message
echo ' <li style="cursor:pointer;" onclick="' add_signup($society, $emails['student_email'], $event) '); ">' .$emails['student_email'] . "</li>";
Can anyone help with this? Im trying to call a php function once a list element is clicked, only the html code is being generated itself by another php function in an echo statement.
I keep getting syntax errors so is it as simple as that or is it even possible at all to do this? if not, what could i do to get the result i want? the actual error code is
Parse error: syntax error, unexpected 'add_signup' (T_STRING), expecting ',' or ';' in C:\Users. . .
You're missing the dot (concatenation) before and after your add_signup method.
echo ' <li onclick="document.write(' . add_signup($society, $names['name'], $event) . '); ">' . $names['name'] . "</li>";
That will get rid of your syntax error. However it will also execute the add_signup method immediately, and not when the button is clicked.
To call this when the button is clicked, start looking into how to make Ajax calls client-side.

PHP active write to DIV with arrays

Once again I'm posting for something that I've never dealt with or have not found the answers with my google searches.
I have a web app, that I want to turn on a "logging" section.
I want an empty DIV to have data written to it (they're array CURL requests and json responses).
I have found how to Jquery write to a div, but this doesn't work with arrays. Does anyone have a better suggestion for me?
Code:
<script>
function updateProgress(progress){
$("#progress").append("<div class='progress'>" + progress + "</div>");
}
</script>
<div id='progress'></div>
in PHP:
echo "<script language='javascript'>parent.updateProgress('$response');</script>";
Error: Array to string conversion
use .html() to write in to div
<script>
function updateProgress(progress) {
$("#progress").html("<div class='progress'>" + progress + "</div>");
}
</script>
PHP:
echo "<script>";
echo "$(document).ready(function() {";
echo "updateProgress(" . $response. ");";
echo "});";
echo "</script>";
The problem is inside your PHP code. The variable $response is an array and you're attempting to convert it to (cast it as) a string, hence the error, "Array to string conversion".
Basically, you're doing this:
echo (string)array('value1', 'value2'); // Notice: Array to string conversion
If this is just a basic array (as the above example is), you can easily fix this by using implode. For example:
echo "<script language='javascript'>parent.updateProgress('" . str_replace("'", ''', implode(', ', $response)) . "');</script>";
If it's more complex (multi-dimensional array), you'll need to do some further processing to get only the values you want to show on the page.
The way you call this function parent.updateProgress('$response'); is wrong, you need not remove parent from invoking statement something like this.
echo "<script language='javascript'>updateProgress('".$response."');</script>";
//-----------remove parent from here^
Now this function updateProgress will be invoked successfully.
If $response is an array, and you want to display this as string then you can use it.
$response = implode(", ", $response);
echo "<script language='javascript'>updateProgress('".$response."');</script>";

Categories