jQuery take array from php file and display in html - javascript

This is my php script to display json data:
$get_chat = "SELECT * FROM chat WHERE u_id1='$u_id' && u_id2=2 ORDER BY data DESC";
$run_chat = $conn->query($get_chat);
if ($run_chat->num_rows > 0) {
while($chat_row = $run_chat->fetch_assoc()) {
echo json_encode( $chat_row );
}
}
This is my result from php file:
{"u_id1":"1","content":"ae","u_id2":"2","data":"17\/03\/27 02:02"}
{"u_id1":"1","content":"ax","u_id2":"2","data":"17\/03\/27 02:01"}
{"u_id1":"1","content":"fd","u_id2":"2","data":"17\/03\/26 11:49"}
{"u_id1":"1","content":"hh","u_id2":"2","data":"17\/03\/26 11:47"}
And now I whant to display all of this in html.

Try something like:
<?php while($chat_row = $run_chat->fetch_assoc()): ?>
<p><?= $chat_row['content']; ?></p>
<?php endwhile; ?>
No need to use json_encode unless you want a Javascript object from my understanding, and it doesn't seem like that's what you're trying to do.

Related

How can I prevent `[` and `]` to be parsed as array in JavaScript from PHP?

I have array in my PHP like this:
$arr['itemDetail[0][itemDescription]'] = Sample Product;
$arr['itemDetail[0][itemPrice]'] = 50000;
$arr['itemDetail[0][itemQty]'] = 2;
$arr['itemDetail[1][itemName]'] = Sample Product Again;
$arr['itemDetail[1][itemDescription]'] = Sample Product Again;
$arr['itemDetail[1][itemPrice]'] = 150000;
$arr['itemDetail[1][itemQty]'] = 1;
That array will be parsed into URI with:
$uri = '/process?'.http_build_query($arr);
Then I retrieve the parameter in JavaScript with:
<?php foreach ($params as $_key => $_val): ?>
<script>console.log("<?php echo $_key; ?> <?php echo $_val; ?>");</script>
<?php endforeach ?>
Why does in my JavaScript console the value in $_key and $_val returned itemDetail Array?
What I expect for the console.log(); is to return:
itemDetail[0][itemDescription] Sample Product
itemDetail[0][itemPrice] 50000
itemDetail[0][itemQty] 2
itemDetail[1][itemName] Sample Product Again
itemDetail[1][itemDescription] Sample Product Again
itemDetail[1][itemPrice] 150000
itemDetail[1][itemQty] 1
And not
itemDetail array
What is the problem?
PHP array is read by 'echo' as word 'array'. You need to encode array to js-string by PHP and then parse it with JS:
<?php foreach ($params as $_key => $_val): ?>
<script>console.log("<?php echo $_key; ?> JSON.parse('<?php echo json_encode($_val); ?>')");</script>
<?php endforeach ?>

Get javascript variable value in php

I need to get javascript variable value in php file.
html example:
UPDATE:
$html = '
<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
Shout I use regex ? regex is very complex to me... any help ?
<?php
$html = '<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
$variables = ["adminSeq", "companyId"];
$counter = 0;
foreach($variables as $variable) {
preg_match_all('/"(.*?)"/', $html, $matches);
${"$variable"} = ($matches[1])[$counter];
$counter++;
}
echo $adminSeq; // Prints out: 3423423423423
echo $companyId; // Prints out: 2349093284234
?>
You can also use GET requests to do this. The link would look like http://localhost/?adminSeq=3423423423423&companyId=2349093284234 then get out these values in PHP with:
<?php
$adminSeq = $_GET["adminSeq"];
$companyId = $_GET["companyId"];
?>

change class according to value from database

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

Passing array values to js

So current setup is as following:
PHP:data.php
<?php
$method = $_SERVER['REQUEST_METHOD'];
$data = array(
"16508",
"16498",
"16506"
);
if ($method === "GET") {
echo json_encode($data);
}
?>
JS:
$.get("./page_asset/data.php").then(function(returned) {
data = JSON.parse(returned);
};
Now, how do I parse the data without getting the specific php page (as I don't want to rely on the specific php address such as "/page-asset/data.php").
For example:
PHP:
<?php
$data = array(
"16508",
"16498",
"16506"
);
?>
I simply want to pass these values to js without relying on the page url.
You can use PHP to create the Javascript in the original page. json_encode() can be used to convert a PHP value to the analogous JS literal.
<?php
$data = array(
"16508",
"16498",
"16506"
);
?>
<script>
var data = <?php echo json_encode($data); ?>;
</script>
You can use a hidden field:
<input id="my-data" type="hidden" value='<?php echo json_encode($data)?>' />
And then you can parse the input value from javascript:
var data = $.parseJSON($('#my-data').val());

Access Wordpress PHP Variables within Plugin JS

edit: I'm now wondering how I can access post ID from within plugin (outside of loop). If I try to get the post id, it returns 0.
How does one access a specific page's PHP variables within a plugin JS file?
I originally had the JS in the page template file but have moved it to a plugin. Now I am unsure how to access that page's PHP variables. Maybe move the PHP logic to a plugin function?
content-course.php (JS)
<?php
$user_id = get_current_user_id();
$course_id = $post->ID;
$vimeo_progress = 0;
$vimeo_seconds = 0;
if ( is_user_logged_in() ) {
// Run WP query to retrieve user progress
$row = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $table_name WHERE user_id = %d AND course_id = %d;", $user_id, $course_id) );
if ($row) {
$vimeo_seconds = $row->seconds_played;
$vimeo_progress = $row->progress_percent;
}
}
?>
<script>
jQuery(document).ready(function($) {
var progress = <?php echo $vimeo_progress; ?>;
var seconds = <?php echo $vimeo_seconds; ?>;
var userProgress = <?php echo $vimeo_seconds; ?>; //example user data retrieved
var lastUpdateProgress = <?php echo $vimeo_progress; ?>;
var videoUrl;
var courseID = <?php echo $course_id; ?>;
</script>
How would the JS script be able to access the PHP variables if moved to the plugin? Do I need to move the PHP above the script to a plugin function.. because then I am not sure how it would pass the data to the JS.
Wordpress have a classified function for the job
wp_localize_script()
Take a look. It's very easy to do.
http://codex.wordpress.org/Function_Reference/wp_localize_script

Categories

Resources