onClick echo PHP code to div (AJAX) - javascript

So what I'm trying to do is the following:
first: When the button add-location is clicked this loads a php file using AJAX.
jQuery
$('.add-location').click(function() {
var locationName = $(this).data('location');
$.post('http://www.example.com/reload-location-2.php?addparam',
{locationName: locationName}, function(data) {
$("textarea#location").html(data);
})
});
PHP FILE
<?php start_session();
$locationName = array_key_exists('locationName',
$_POST) ? (string) $_POST['locationName'] : '';
if(isset($_GET['delparam'])){
unset($_SESSION['locations'][$locationName]);
}
if(isset($_GET['addparam'])){
$_SESSION['locations'][$locationName] = $locationName;
}
?>
<?php foreach ($_SESSION['locations'] as $location): ?>
<?php echo htmlspecialchars($location); echo "\n"; ?>
<?php endforeach;?>
This all works like a charm! No worries here. No what I'm trying to do is when the button add-location is clicked this echo's the following code to a div called textarea#thema.
<?php foreach ($_SESSION['products'] as $product): ?>
<?php echo htmlspecialchars($product); echo "\n"; ?>
<?php endforeach;?>
OR, if that's easier when the page is loaded -> echo that code to the textarea#thema div.
I do not understand AJAX that much but I'm getting there. But I think the last option maybe the easiest solution?
Could anyone help me figure this one out?
What I tried
Right now, When the button add-location is clicked I reload a previous jQuery script:
$('.add-location').click(function() {
var productName = $(this).data('product');
$.post('http://example.com/reload-2.php?addparam',
{productName: productName}, function(data) {
$("textarea#thema").html(data);
})
});
This works, but it adds an extra <p>-tag leaving me with a line break in the code.
I also changed the .html(data); to .val(data); for the textareas. Also I made a new PHP file with just this code:
<?php foreach ($_SESSION['products'] as $product): ?>
<?php echo htmlspecialchars($product); echo "\n"; ?>
<?php endforeach;?>
And this jQuery code:
$('.add-location').click(function() {
var productName = $(this).data('product');
$.post('http://www.example.com/reload-3.php',
{productName: productName}, function(data) {
$("textarea#thema").val(data);
})
});
But still no go... And I don't think this is the way to go?? I hope I gave enough information.

You should use .val() function to fill textarea, not .html().

Related

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

Array value is replaced when second one stores in php

I am storing session values into array getting from URL and try to display it (getting size of product in a shopping cart).
But first value is replaced by second one.
My code:
if(isset($_POST['radio'])){
$_SESSION['sz']=$_POST['radio'];
$si=$_SESSION['sz'];
}
<a href="product_detail.php?pdt_id='.$pdid.'&add=' .$pdid .'&size='.$si.'"
class="cartBtn" onclick="return fun1()">Add to cart</a>';
?>
Display page:
$rt=$_GET['size'];
$_SESSION['wer']=$rt;
$array = $_SESSION['wer']; //Assigns session var to $array
//print_r($array);
echo $array[$x];
}
About First part mistakes :
<?php
if(isset($_POST['radio'])){
$_SESSION['sz']=$_POST['radio'];
$si=$_SESSION['sz'];
}
Add to cart';
?>
Your a tag is completely wrong as #Hearner said. It should be out of the php tag or inside with an "echo" like this :
echo "<a href='product_detail.php?pdt_id=".$pdid."&add=".$pdid."&size=".$si."' class='cartBtn' onclick='return fun1()'>Add to cart</a>";
You cannot access your $si variable out of your if statement. As written here over, if your $si isn't declared before (since you said that it was not your complete code...) then $si (in the link href) does not exist. You should therefore declare it before your if statement OR place your link (a tag) inside your if statement too!
What if your "$_POST['radio']" is NOT set ?? what happens? code missing... !! is $si declared anyway?
About Second part :
<?php
for( $x = 0, $max = count($array); $x < $max; ++$x ) {
$rt=$_GET['size'];
$_SESSION['wer']=$rt;
$array = $_SESSION['wer'];
echo $array[$x];
}
?>
I don't understand what you're trying to do here... need more code/information... cannot help more without your whole code...
EDIT :
Here is a very simple example to show you how to keep your get vars into a session array.
page one (pageOne.php):
<?php
session_start();
if(!(isset($_SESSION['myTest']))){
$_SESSION['myTest'] = "AWESOME";
$_SESSION['varToKeep'] = [];
}else{
echo "A session is already started. This is : ".$_SESSION['myTest']."<br/>";
if(count($_SESSION['varToKeep']>0)){
echo "There are ".count($_SESSION['varToKeep'])." vars in the array!<br/>";
for($i=0;$i<count($_SESSION['varToKeep']);$i++){
echo "Item ".$i." : ".$_SESSION['varToKeep'][$i]."<br/>";
}
}
}
echo "<br/>Click below to add a value in array<br/>";
$random = rand(1,100);
echo "<a href='pageTwo.php?mygetvar=STACKTEST".$random."'>Click here</a>";
?>
page two (pageTwo.php):
<?php
session_start();
echo "myTest value is : ".$_SESSION['myTest']."<br/><br/>";
$value = $_GET['mygetvar'];
$_SESSION['varToKeep'][] = $value;
echo "<a href='pageOne.php'>CLICK HERE TO RETURN ON PAGE ONE!</a>";
?>

Ajax: Data passing through button value not working

Problem: All the other portions of the program works. When I add data:$("#friendadd").val() it won't update the table. I believe the problem might be with the value form? I've seen others use it to get the value of textboxes but shouldn't it still work when using a submit button?
Purpose: each user on the website has an add-as-friend button next to it. When you click on that button, I want to put the userid of that user into a database "friends".
Javascript
<script>
$(document).ready(function(){
$("#friendadd").submit(function(){//Used to be .each
$.ajax({
type:"POST",
url:"getuser.php",
data:$("#friendadd").val()
});//Add data: and success:function
//$.post('getuser.php');//JSON AJAX, {UserId:"13", FriendId:"16"}
})
});
</script>
PHP and HTML; $ctk_values are each of the users
<form id="friendadd">
<?php
for($i=0; $i<$ctk->rowCount(); $i++){
echo "<img src='".$ctk_values[$i][6]."' alt='Blank' style='width:64px;height:64px'>";//PP, Later add clickable profile
echo "<th rowspan='3'>Attributes</th>";
echo "<tr> ".$ctk_values[$i][0]."</tr>";//UN
echo "<tr> ".$ctk_values[$i][1]."</tr>";//UL
echo "<tr> ".$ctk_values[$i][5]."</tr>";//UA
?>
<input type="submit" value="<?php echo $ctk_values[$i][4];?>"><br>
<?php
}//Ends for loop
?>
</form>
<?php
}
}
?>
getuser.php
<?php
if(!isset($_SESSION)){
session_start();
}
require "conn.php";
$gtu = $dbh->prepare("INSERT INTO friends (AskerId, AcceptorId, mutual, type) VALUES(:AskerId, :AcceptorId, :mutual, :type)");
$gtu->execute(array(
'AskerId'=>$_SESSION['UserId'],
'AcceptorId'=>$_POST['friendadd'],
'mutual'=>false,
'type'=>'friend'
));
?>

Add div class with php in jQuery

My variable contains a color name. My example:
<?php
$myvar = blueColour;
?>
I need to add this value to body of a html page using jQuery:
<script type="text/javascript">
jQuery(body).addClass("<?php echo $myvar; ?>");
</script>
Can I use php inside jQuery this way? Thank you.
EDIT: its an wordpress site. I use this in a if to add that class on a specific page template.
<script type="text/javascript">
jQuery("body").css("color", "<?php echo $myvar; ?>");
</script>
yes, as long as your html file is interpreted by php (having .php/.phtml extension)
I did it. Worked.
Correct is:
jQuery('body').addClass("<?php echo $myvar; ?>");
with
jQuery('body')
not
jQuery(body)
if ( is_page_template('nameOfYouTemplate.php') ) {
echo '<body class='. $myvar .'>';
} else {
echo '<body>';
}

Jquery flickering when I add classes to my divs

I'm having trouble with Jquery and flickering. My problem is this, when I convert my id's to classes the below syntax isn't working. The problem is, it flickers. It flickers approx. 7-8 times. What am I doing wrong? Any help would be appreciated. Thanks everyone.
I would also like to add when I change my classes to ID's everything works great but only one item on my webpage has the ability of hide>click>slideToggle (which isn't what I want because I'm listing more than one item per page for sale). This syntax is below as well, it's very similar to the syntax that does not work but I've decided to include it anyway.
(Not working syntax. Has classes)
<?php
echo "<div class=\"fmv2\">Your Name</div>";
?>
<div class="p122">
<?php
echo form_open("submit/submit_info");
echo form_label('Your Name:','name');
$data = array(
"name" => 'name',
"id" => 'box_width',
"value" => set_value('name')
);
echo form_input($data);
echo '<br>';
echo form_submit('Submit','Submit');
echo form_close();
?>
</div>
My Jquery (Not working, has classes)
// JavaScript Document
$(document).ready(function(){
$(".p122").hide(function(){
$(".fmv2").click(function() {
$(".p122").slideToggle(300);
});
});
});
Working syntax (Has Ids)
<?php
echo "<div id=\"fmv2\">Your Name</div>";
?>
<div id="p122">
<?php
echo form_open("submit/submit_info");
echo form_label('Your Name:','name');
$data = array(
"name" => 'name',
"id" => 'box_width',
"value" => set_value('name')
);
echo form_input($data);
echo '<br>';
echo form_submit('Submit','Submit');
echo form_close();
?>
</div>
My Jquery. (Working, has Ids)
// JavaScript Document
$(document).ready(function(){
$("#p122").hide(function(){
$("#fmv2").click(function() {
$("#p122").slideToggle(300);
});
});
});
I figured out my problem. I've been playing around with the syntax and the below code works.
$(function() { // Shorthand for $(document).ready(function() {
$('div.p122').hide();
$('div.fmv2').click(function() {
$(this).next('div.p122').slideToggle(300);
});
});

Categories

Resources