how to use javascript variable in php inside a javascript function - javascript

i am trying to fetch JavaScript variable "i" in my PHP Code within a JavaScript function in the below code, I find problem in retrieving records, either first record or the last record repeats instead of all records in database.. can you guys help me out ?
Thanks
<?php
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
?>
<script language="javascript" type="text/javascript">
var intervalID = 0;
var time = 10;
MsgPop.displaySmall = true;
MsgPop.position = "bottom-right";
$(document).ready(function(){
var test = MsgPop.open({
Type: "success",
AutoClose: true,
Content: "Welcome to MsgPop!"});
MsgPop.live();
});
function showMessages(){
var n = '<?php
echo $nr;
?>';
var i = 0;
while (i < n){
var name = '<?php
echo $results[i]['name'];
?>';
MsgPop.open({
Type: "success",
Content: name,
AutoClose: false});
i++;
}
</script>

First you have to create a php file which return same array. File contain
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
echo json_encode($results);
exit;
Now you have to call this file using ajax from your javascript code.
$.ajax({
type: "POST",
url: "sql.php", //your file url
})
.done(function (data) {
//you get your array data(json format)
});
now you get that array in ajax response in json format and you can do anything with this data.

Impossible: PHP is a server side language that runs only at server. but javascript is a client side script it only run at your browser only. Php only gives response depends on your requests. The roll of php is end at server. But the javascript work with your response only, that is javascript can work at browser only.

You could try using AJAX, or else it isn't happening. Like said PHP is server-side only... Good luck!

PHP cannot fetch javascript variables. You should try another strategy.
At the server side (PHP), try to store $resuts in a javascript variable.
var results = '<?php echo json_encode($results); ?>';
Then at the browser side, try to access the data with javascript functions.
var name = results[i]['name'];

Related

POST-GET session variable (javascript-php) -javascript takes the previous variable but not last created

From the selected value (from the form) I create a variable (var parcela).
var parcela;
$(document).ready(function(){
parcela = localStorage.getItem("parcela");
if (parcela !== '') {
$('#parcela').val(parcela);
}
$("#parcela").on('change',function() {
selectBoxVal_1 = $('#parcela').val();
if (typeof(Storage) !== "undefined") {
localStorage.setItem("parcela", selectBoxVal_1);
} else {
alert('Sorry! No Web Storage support..');
}
location.reload();
});
});
From the created variable (parcela), I create a session variable in PHP.
$.post("phpscripts/session.php", {"parc_id": parcela});
PHP (session.php)
<?php
session_start();
$parcela = $_POST["parc_id"];
$parcela_int = (int)$parcela;
if($_POST){
$_SESSION['parcela_id'] = $parcela_int;
}
?>
After that, the created session variable urge to another php script
query.php
<?php
session_start();
require("common.php");
$user_id = htmlentities($_SESSION['user']['id_korisnika']);
$parc = $_SESSION['parcela_id'];
try
{
$stmt = $db->prepare("SELECT y_cent, x_cent FROM parcele WHERE id_korisnika='$user_id' AND id_parcele='$parc' ");
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
....
This all works perfectly!
However, when I call a php script with query (query.php) in javascript, there is a problem. JS takes the previous session variable instead of the last selected.
$.ajax({
url: 'phpscripts/query.php',
type: 'GET',
success : function(data) {
chartData = data;
//console.log(chartData);
...
Does anyone know what the problem is? I'm trying for two days to solve this ...
Note: The javascript code is contained in a single script.
I solved the problem. I had to extract part of javascript code that calls the php script into a separate script. I called the new JS script with jQuery getScript() Method.
Thank you #knets.

Populating an array through jquery AJAX in php

I have a function in a compare.php that takes a parameter $data and uses that data to find certain things from web and extracts data and returns an array.
function populateTableA($data);
So to fill array I do this
$arrayTableA = populateTableA($name);
now this array is then used to iterate tables..
<table id="tableA">
<input type="text" name="search"/><input type="submit"/>
<?php foreach($arrayTableA as $row) { ?>
<tr>
<td><?php echo $row['name']?></td>
<td><?php echo $row['place']?></td>
</tr>
</table>
Now what I want to do is to enter some data on input and then through jquery ajax
function populateTableA($data);
should be called and $array should be refilled with new contents and then populated on tableA without refreshing the page.
I wrote this jquery but no results.
$(document).on('submit',function(e) {
e.preventDefault(); // Add it here
$.ajax({ url: 'compare.php',
var name = ('search').val();
data: {action: 'populateTableA(name)'},
type: 'post',
success: function(output) {
$array = output;
}
});
});
I have been doing web scraping and the above was to understand how to implement that strategy... original function in my php file is below
function homeshoppingExtractor($homeshoppingSearch)
{
$homeshoppinghtml = file_get_contents('https://homeshopping.pk/search.php?category%5B%5D=&search_query='.$homeshoppingSearch);
$homeshoppingDoc = new DOMDocument();
libxml_use_internal_errors(TRUE);
if(!empty($homeshoppinghtml)){
$homeshoppingDoc->loadHTML($homeshoppinghtml);
libxml_clear_errors();
$homeshoppingXPath = new DOMXPath($homeshoppingDoc);
//HomeShopping
$hsrow = $homeshoppingXPath->query('//a[#class=""]');
$hsrow2 = $homeshoppingXPath->query('//a[#class="price"]');
$hsrow3 = $homeshoppingXPath->query('(//a[#class="price"])//#href');
$hsrow4 = $homeshoppingXPath->query('(//img[#class="img-responsive imgcent"])//#src');
//HomeShopping
if($hsrow->length > 0){
$rowarray = array();
foreach($hsrow as $row){
$rowarray[]= $row->nodeValue;
// echo $row->nodeValue . "<br/>";
}
}
if($hsrow2->length > 0){
$row2array = array();
foreach($hsrow2 as $row2){
$row2array[]=$row2->nodeValue;
// echo $row2->nodeValue . "<br/>";
}
}
if($hsrow3->length > 0){
$row3array = array();
foreach($hsrow3 as $row3){
$row3array[]=$row3->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
if($hsrow4->length > 0){
$row4array = array();
foreach($hsrow4 as $row4){
$row4array[]=$row4->nodeValue;
//echo $row3->nodeValue . "<br/>";
}
}
$hschecker = count($rowarray);
if($hschecker != 0) {
$homeshopping = array();
for($i=0; $i < count($rowarray); $i++){
$homeshopping[$i] = [
'name'=>$rowarray[$i],
'price'=>$row2array[$i],
'link'=>$row3array[$i],
'image'=>$row4array[$i]
];
}
}
else{
echo "no result found at homeshopping";
}
}
return $homeshopping;
}
As mentioned in the comments PHP is a server side language so you will be unable to run your PHP function from javascript.
However if you want to update tableA (without refreshing the whole page) you could create a new PHP page that will only create tableA and nothing else. Then you could use this ajax call (or something similar) -
$(document).on('submit','#formReviews',function(e) {
e.preventDefault();
$.ajax({
url: 'getTableA.php', //or whatever you choose to call your new page
data: {
name: $('search').val()
},
type: 'post',
success: function(output) {
$('#tableA').replaceWith(output); //replace "tableA" with the id of the table
},
error: function() {
//report that an error occurred
}
});
});
Hi You are doing it in wrong way.You must change your response to html table and overwrite older one.
success: function(output) {
$("#tableA").html(output);
}
});
In your ajax page create a table with your result array
You are in a very wrong direction my friend.
First of all there are some syntax error in your JS code.
So use JavaScript Debugging
to find where you went wrong.
After that Basic PHP with AJAX
to get a reference how ajax and PHP work together
Then at your code
Create a PHP file where you have to print the table part which you want to refresh.
Write an AJAX which will hit that PHP file and get the table structure from the server. So all the processing of data will be done by server AJAX is only used for request for the data and get the response from the server.
Put the result in your html code using JS.
Hope this will help

Getting a value from Javascript in PHP [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am not very experienced in web programming and am attempting to run a script which updates my database.
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts)
<?php
include_once 'accounts/config.php';
$text = ...;
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
}
</script>
I have no idea what to put in the $text section as shown with $text = ...; in order to get the variable texts from above.
EDIT
I have updated my code but the function does not seem to be accessing the PHP file. I am using a button to call the function and I have also tested it so i know the function is being called. My file is called update.php and is in the same directory as this file.
<button onclick="myFunction()">Click This</button>
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: "update.php",
type: "POST",
data: {texts:texts},
success: function(response){
}
});
}
</script>
you can post your $texts value to other php page using ajax and get the variable on php page using $_POST['texts'] and place update query there and enjoy....
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: 'update.php',
type: "POST",
data: {texts:texts},
success: function(response)
{
}
});
And your php file will be named as update.php
<?php
include_once 'accounts/config.php';
$text =$_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE `enemies` SET `text`='".$text."' WHERE `id`=1";
$result = mysql_query($query) or die(mysql_error());
?>
PHP runs on the server and then generates output which is then returned to the client side. You can't have a JavaScript function make a call to inlined PHP since the PHP runs before the JavaScript is ever delivered to the client side.
Instead, what you'd need to do is have your function make an AJAX request to a server-side PHP script that then extracts the data from the request body and then stores it in the database.
PHP: "/yourPhpScript.php"
<?php
include_once 'accounts/config.php';
$text = $_POST['data'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text='".$text.'" WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
JavaScript:
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts);
// append data as a query string
var params = 'data='+texts;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
// when server responds, output any response, if applicable
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
// replace with the filename of your PHP script that will do the update.
var url = '/yourPhpScript.php';
xmlhttp.open("POST", url, true);
xmlhttp.send(params);
}
A word of caution: This is not a safe, production-friendly way of updating data in your database. This code is open to SQL injection attacks, which is outside the scope of your question. Please see Bobby Tables: A guide to preventing SQL injection if you are writing code that will go into production.
You are wrong in approach
You should use ajax to post 'texts' value to your php script
https://api.jquery.com/jquery.post/ and create separate php file where you will get data from ajax post and update DB
javascript:
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
type: "POST",
url: "update.php",
data: "texsts=" + texts,
success: success
});
}
</script>
update.php
<?php
include_once 'accounts/config.php';
$text = $_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
i will use PDO if i was you, what you do mysql_query are outdated, if you use my framework https://github.com/parisnakitakejser/PinkCowFramework you can do the following code.
<?php
include('config.php');
$text = $_POST['text'];
$query = PinkCow\Database::prepare("UPDATE enemies SET text = :text WHERE id = 1");
$bindparam = array(
array('text', $text, 'str')
);
PinkCow\Database::exec($query,$bindparam);
$jsonArray = array(
'status' => 200
);
echo json_encode($jsonArray);
?>
place this code in jsonUpdateEnemies.php file and call it width jQuery
<script>
function myFunction(yourText) {
$.post( 'jsonUpdateEnemies.php', {
'text' : yourText
}, function(data)
{
alert('Data updated');
},'json');
}
</script>
its a little more complex then you ask about, but its how i will resolved your problem, :)

Failed to send data via the callback function argument to $.post method in javascript from a php file

My javascript posts a request and after it succeed, the response(the echo statement in php file) is send to the .html() method in the call back function (so that I can use it to display on the webpage). But the data I tried to send from the php file never seems to appear in the var 'recData'. Please help me to find the problem.
JavaScript Code:
$.post(php_file_url, function(response) {
$( "#Trend" ).dialog({modal: true,
width: 900,
height:550 });
$( "#Trend" ).html(response);
});
Php Code:
.....;
$arrayVar;
echo"<script>
var recData = <?php echo json_encode($arrayVar); ?>;
...*use recData *...;
</script>";
php is backend language so you can't do it
var recData = <?php echo json_encode($arrayVar); ?>;
true is
echo"<script>
var recData = ".json_encode($arrayVar).";
...*use recData *...;
</script>";

how to use javascript variable inside php in javascript function

I'm using JavaScript to redirect a page with dynamic parameter.
Here is the code, I had to use the PHP function inside JavaScript. It works but it isn't using the javascipt variable
<script type="text/javascript">
var $map = jQuery.noConflict();
$map(document).ready(function(){
$map("#map_search").click(function(){
var staffname = $map("#staffname").val();//alert(staffname);
var from = $map("#cdate_from").val();
var to = "<?php echo site_Encryption(from); ?>";alert(to);
var status = $map("#status").val();
window.location = "http://localhost/staff/booking.php?date="+to+"&tdate="+to;
var to = "<?php echo site_Encryption(from); ?>";alert(to);
Here I use the PHP function and "from" is JavaScript variable that I want to use.
You can do an ajax request, something like:
var from = blablah...;
$.getJSON("encryption.php", {from : from}, function (data)
{
alert(data.to);
});
encryption.php :
<?php
blabla...
echo json_encode(array("to" => site_Encryption($_GET["from"])));
?>
(It's a sample code, don't copy-paste, read some ajax tutorials ^^)
An alternative could be to make the encryption on client side.

Categories