Javascript variable works only the first time - javascript

I have function that works with JSON.
function makeItem(data){
var tbl_body = "";
$.each(data, function() {
var id = parseInt(this.ProductId);
var tbl_row = "";
tbl_row += "<a href='article.php?cat=<?=$cat?>&subcat=<?=$subcat?>&id="+id+"'>";
tbl_row += "<div class='subCatImg'><img src='imagesDB/articles/<?=$main["+id+"]['dir']?>/<?=$main["+id+"]['image']?>'></div>";
tbl_row += "<div class='subCatName'>"+this.ProductNameBG+"</div>";
tbl_row += "<div class='subCatText'>"+this.ProductNameBG+"</div>";
tbl_row += "</a>";
tbl_body += "<div class='categoryWrap'>"+tbl_row+"</div>";
})
return tbl_body;
}
The problem is that the variable id works only the first time - in the a tag but not in the second nor the third time.
Is it because the a tag is not immediately closed or because the second and the third time I'm trying to use it in php array. I'm sure that the array works because if I hardcore it(<?=$main[1]['dir]?>) the image is displayed(no need for quotation marks, I need integer).
The thing is that I have to make it dynamic so I can't just type some number.
Why does it work the first time but not the others?

You can convert your PHP array into a json object like this :
var main = <?php echo json_encode($main) ?>;
then iterate through it.

#epascarello is correct. PHP is server side, were JS is client side. Instead, try to do something like
UPDATED:
tbl_row += <?php print("\"<a href='article.php?cat=$cat&subcat=$subcat&id=\" + id + \"'>\""); ?>
tbl_row += <?php print("\"<div class='subCatImg'><img src='imagesDB/articles/$phpVal1/$phpVal2'></div>\""); ?>
tbl_row += <?php print("\"<div class='subCatName'>\" + this.ProductNameBG + \"</div>\"");?>
tbl_row += <?php print("\"<div class='subCatText'>\" + this.ProductNameBG + \"</div>\"");?>
tbl_row += <?php print("\"</a>\"");?>
In this, you will have to pass the value of the id and the dir from JS to php so php can parse it's multidimensional array. You'll notice that <?=$main["+id+"]['dir']?>/<?=$main["+id+"]['image']?> has changed to $phpVal1/$phpVal2.
You can do this a number of ways - perhaps through a click of a button. But php will be done first, and then the JS.
In essence, you are getting all the values from the server (php) and forcing it to write the client side (JS) for you.

Related

How to append a Ajax variable obtained from a loop into a <a href='' '/a> tag

Hi everyone i'm new to Ajax,i'm using ajax to get values from my database in form of an object array from a separate PHP file and displaying them in a table,everything works fine,but i want to create a link and append the ID obtained from the array so that i can send a GET request to another PHP file which will act upon that particular row.
code for the PHP File
<?php
include 'Module/Credentials.php';
$sql="SELECT * FROM queries";
$query= mysqli_query($connection, $sql) or die(mysqli_error($connection));
$data = array();
while ($row = mysqli_fetch_object($query))
{
array_push($data, $row);
}
echo json_encode($data);
`
Ajax code
javascript
` var ajax=new XMLHttpRequest();
var method="GET";
var url="getMessages.php";
var asynchronous=true;
ajax.open(method, url,asynchronous);
ajax.send();
ajax.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
var data=JSON.parse(this.responseText);
console.log(data);
var html="";
for(var b=0;b<data.length;b++){
var ID=data[b].ID;
var name=data[b].name;
var email=data[b].email;
var subject=data[b].subject;
var message=data[b].message;
var link = "management.php?delete=";
$(document).ready(function(){
$('.link').attr('href', link+ID);
});
console.log(data.length);
html +="<tr>";
html +="<td>"+"<a class='link' href=''>Delete</a>"+"</td>";
html +="<td>" + name + "</td>";
html +="<td>" + email + "</td>";
html +="<td>" + subject + "</td>";
html +="<td>" + message + "</td>";
html +="</tr>";
}
document.getElementById("messages").innerHTML += html;
}
}`
the ID on the link is not changing its just displaying a single ID=6
Solution
` var ajax=new XMLHttpRequest();
var method="GET";
var url="getMessages.php";
var asynchronous=true;
ajax.open(method, url,asynchronous);
ajax.send();
ajax.onreadystatechange=function(){
if(this.readyState==4 && this.status==200){
var data=JSON.parse(this.responseText);
console.log(data);
var html="";
for(var b=0;b<data.length;b++){
var ID=data[b].ID;
var name=data[b].name;
var email=data[b].email;
var subject=data[b].subject;
var message=data[b].message;
var link = `management.php?delete=${ID}`;
html +="<tr>";
html +=`<td><a href='${link}'>Delete</a></td>`;
html +="<td>" + name + "</td>";
html +="<td>" + email + "</td>";
html +="<td>" + subject + "</td>";
html +="<td>" + message + "</td>";
html +="</tr>";
}
document.getElementById("messages").innerHTML += html;
}
}`
but i'm getting error messages in NetBeans IDE 8.0.2 like
Expected an operand but found error
`var link== `management.php?delete=${ID}`;`
Expected an operand but found error
`html +=`<td><a href='${link}'>Delete</a></td>`;`
Expected eof but found error ` }`
Try a Template Literal like so:
var link = `management.php?delete=${ID}`;
And if you want it on the html
html +=`<td><a class='link' href='${link}'>Delete</a></td>`;
Please note that I'm using the back ticks `
More info here
Before selecting a HTML element you have to create it. After creation you can manipulate.

How to parse a PHP variable using a dynamic JS variable?

I have 5 PHP variables, $menu1 to $menu5, that each evaluate to a keyword. I'm trying to populate these 5 PHP variables in JavaScript, and display them. The below code doesn't work. What is wrong with my processing of the PHP variables?
var menu_populator = "";
for (var x = 1; x <= count; x++) {
menu_populator += '<li><a class="myclass" href="#link">' + '<?php echo $menu' + x + '?>' + '</a></li>';
}
$('#nav_menu').html(menu_populator);
Depending on how you are getting the menu data server-side you can try both methods below. One is for set $menu variables but if you are getting data from a database or the $menu variable are created within a loop you might find the second method better.
Method one- PasteBin
Echo your php variables into a javascript array.
var myarray=["<?php echo $menu1;?>","<?php echo $menu2;?>","<?php echo $menu3;?>","<?php echo $menu4;?>","<?php echo $menu5;?>"];
Method Two- PasteBin
Create this array server-side, this will be better if you are creating the current $menu variable in a loop, with this you can just use array_push() to push the values into the array.
<?php
// PHP Array
$menu = array('Home', 'Gallery', 'About');
// How to push new item into array
array_push($menu, 'Contact');
?>
Then just simply echo this array into your javascript myarray variable.
var myarray=<?php echo json_encode($menu);?>;
I have used the following javascript to test both methods and both seem to function just fine. I prefer the second method but I have decided to offer both as I don't know what your PHP looks like or how your $menu variables are being defined so this should cover both.
window.onload=function(){
for(var i=0; i<myarray.length; i++){
var link= document.createElement('a');
link.href="#";
link.innerHTML=myarray[i];
document.body.appendChild(link);
document.body.appendChild(document.createElement('br'));
}
}
If you have any questions about the source code above please leave a comment below and I will get back to you as soon as possible.
I hope this help. Happy coding!
Something like this would do the trick
<?php
$menu = "menu";
echo '
<script>
var count = 10;
var menu_populator="";
for(var x=1;x<=count;x++)
{
menu_populator += \'<li><a class="myclass" href="#link">'.$menu.' \'+x+\'</a></li>\';
}
$(\'#nav_menu\').html(menu_populator);
</script>
';
?>

Pass JS(JQuery) variable to php [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
I've just started with php and js (jquery) and need help. I'm trying to do smth like betting service.
1. On html page user choose racecoast, using jquery I send its ID to php file, and it loads timetable:
like this:
while($row = mysqli_fetch_array($result)) { if ($row['date_time'] > date("Y-m-d h:i:sa")){
echo "<tr>";
echo "<td colspan='6' class='race' style = 'font-size: 14pt;' id = '".$row['raceID']."' >" . $row['raceID'] . "</td>";
it works.
2. Then, in the same php file I use
echo "<script type='text/javascript'>
$(document).ready(function(){
$('.race').click(function() {
var elid = $(this).attr('id');
and js perfectly gets the ID of racecoast.
But I can't send elid value back to php.
I've tried to use simple $_[GET], sessions, cookies, to set value on some attrib in my html and then get it, created one more php file, to send information there by load(...) function. Maybe, I did something wrong?..
I feel that my script should be in php file, but how to be then?
my last try, and more code:
while($row = mysqli_fetch_array($result)) { // if ($row['date_time'] > date("Y-m-d h:i:sa")){
echo "<tr>";
echo "<td colspan='6' class='race' style = 'font-size: 14pt;' id = '".$row['raceID']."' >" . $row['raceID'] . "</td>";
echo "<td colspan='6' class='race' style = 'font-size: 14pt;'id = '".$row['raceID']."'>" . $row['date_time'] . "</td>";
echo "<td colspan='6' class='race' style = 'font-size: 14pt;'id = '".$row['raceID']."'>" . $row['special_title'] . "</td>";
echo "</tr>";//} }
echo "</tbody>
</table>";
echo "
<script type='text/javascript'>
$(document).ready(function(){
$('.race').click(function() {
var nid = $(this).attr('id')
alert(nid);
document.cookie = 'newid=' + nid;
});});
</script>";
$choise = $_COOKIE["newid"];
echo $choise;
To give you a short example, using $.post():
jQuery:
$(document).ready(function() {
$('.race').click(function() {
var elid = $(this).attr('id');
$.post('path/to/your/phpfile.php', {
'elid': elid
});
});
});
And to recieve the data in your PHP-file:
$elid = $_POST['elid'];
Some sidenotes:
Is it really necessary to echoing the total javascript in PHP? Would be better to create a seperate JS-file for that.
But without seeing your whole script it's hard to say if there are other issue present.

How to change conditional PHP if-phrase to JS?

I had a product grid that originally was written in PHP. But I've changed it to AJAX and get the results in JSON and have turned that to JS variables.
Now I need to write the whole HTML structure as a JS string to attach it with jQuery. But I'm having difficulties with this one:
<? if(isset($mv['jan_code']) AND $mv['jan_code']!=''){ ?>
<td>JAN Code</td><td>"+post_meta['jan_code']+"</td>
<? }?>
$mv['jan_code'] is the following JS string: post_meta['jan_code'].
How can I rewrite this PHP if-phrase in JS?
I'm not sure if this is the best way, but this is how I'm thinking of outputting my JSON results:
var fill_grid_json = function(data){
var jsonData=$.parseJSON(data); //change here
$.each(jsonData, function(i) {
// get JS variables
var id = jsonData[i].ID;
var post_title = jsonData[i].post_title;
var post_meta = jsonData[i].post_meta;
var grid_item = "<tr>"+
"<td>" + id + "</td>"+
"<td>" + post_title + "</td>"+
"</tr>";
$(grid_item).appendTo("#testajax tbody");
});
};
I found one of the ways is just creating a JS string like this:
if(post_meta['jan_code'] != ''){
var spectr_jan = "<tr><td>JAN Code</td><td>"+post_meta['jan_code']+"</td></tr>";
} else { var spectr_jan=''; }
and then showing it somewhere using jQuery.

How do I get a php element into a javascript

I am scripting a chat for a forum, and it seems that it uses php to get the user's avatars. (PS idk anything about weather or not javascript can use sql databases or how to work with it so i would like to stick to php) But the problem is that the javascript isnt liking it if i put php variables into it.
getUserNodeString: function(userID, userName, userRole) {
var encodedUserName, str;
if(this.userNodeString && userID === this.userID) {
return this.userNodeString;
} else {
encodedUserName = this.scriptLinkEncode(userName);
str = '<div id="'
+ this.getUserDocumentID(userID)
+ '"><a href="javascript:ajaxChat.toggleUserMenu(\''
+ this.getUserMenuDocumentID(userID)
+ '\', \''
+ encodedUserName
+ '\', '
+ userID
+ ');" class="'
+ this.getRoleClass(userRole)
+ '" title="'
+ this.lang['toggleUserMenu'].replace(/%s/, userName)
+ '">'
+ userName
+ '</a><?php echo \'<img src="test.php" />\' ?>'
+ '<ul class="userMenu" id="'
+ this.getUserMenuDocumentID(userID)
+ '"'
+ ((userID === this.userID) ?
'>'+this.getUserNodeStringItems(encodedUserName, userID, false) :
' style="display:none;">')
+ '</ul>'
+'</div>';
if(userID === this.userID) {
this.userNodeString = str;
}
return str;
}
},
'</a><?php echo \'<img src="test.png" />\' ?>'
is the line thet im trying to use, i havent put my variable yet, im trying it with a test immage first
It should be like this:
+ '</a><img src="<?php echo htmlentities($src, ENT_DISALLOWED | ENT_QUOTES | ENT_HTML5) ?>" />'
You should only escape back into PHP for the specific part of the code that needs to contain the PHP variable. The rest of it should be literal HTML or Javascript.
You should also use htmlspecialchars() to ensure that the variable content is encoded properly to be used in an HTML attribute, in case it contains special characters.
The above is for getting a PHP variable into a JS literal that contains HTML code. If just you want to get a PHP value into a Javascript variable, it's slightly different. Then you can use json_encode() to generate the JS representation:
var js_var = <?php echo json_encode($php_var) ?>;
UPDATE
this is a .js file, its taken from ajax chat
It won't work inside a .js file, because those files are not parsed by PHP. It can be set up so that they get parsed, but I strongly suggest you don't do it, ever.
Besides, you don't need PHP for what you're doing.
ORIGINAL ANSWER
This is not a proper PHP inside this line:
+ '</a><?php echo \'<img src="test.php" />\' ?>'
Or just to strip the PHP part:
<?php echo \'<img src="test.php" />\' ?>
To get it to work, you need to remove those escaped quotes (you don't need to worry about JS quotes, because PHP parser will hit the file first, leaving you with whatever you echoed), and add a semi-colon:
<?php echo '<img src="test.php" />'; ?>
and the full line should be:
+ '</a><?php echo '<img src="test.php" />'; ?>'
which will render as:
+ '</a><img src="test.php" />'
It doesn't really make sense to use PHP for this, but okay.
Of course, it has to be inside a file that the server will parse with PHP (.php files by default, strongly suggest you don't set up PHP parsing for JS files). You never answer about the filetype in the comments.

Categories

Resources