I have written the following code in custom.php file (just one file!):
jQuery(function ($) {
$('.price_calc').hide();
$('.lengthm2, .widthm2').keyup(function(){
var priceProduct = <?php echo $priceProduct; ?>;
var lengthM2 = $("#lengthM2").val();
var widthM2 = $("#widthM2").val();
var totalM2 = (lengthM2 / 100) * (widthM2 / 100);
var totalPrice = totalM2 * priceProduct;
$(".m2_customer_total").html(totalM2.toFixed(2));
$(".price_customer_total").html('€'+ totalPrice.toFixed(2));
console.log(lengthM2);
console.log(widthM2);
});
Now in the same file I have added the following code:
<?php
$lengthM2 = $_POST['length'];
$widthM2 = $_POST['width'];
echo do_shortcode( '[gravityform id="2" title="false" field_values="lengthM2='.$lengthM2.'&widthM2='.$widthM2.'"]' )
?>
I can't use the POST variables as I did not post anything.
But how can I manage this works correctly? I tried $.post (jQuery) which not works at all.
Related
I use the code below for simple search and it works well in index.php but because i added the code in header.html for include in all pages and the code result work only in index.php.
https://stackoverflow.com/a/34131517/5227465
index.php?text=keyword = ok
otherpage.php?text=keyword = here not work because search Processing only in index.php
I think the problem in this element means the current page that contains the code:
(document.getElementById)
<form id = "your_form" onsubmit="yourFunction()">
<input type="text" name="keywords">
<input type="submit" value="Search">
</form>
function yourFunction(){
var action_src = "http://localhost/test/" + document.getElementsByName("keywords")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
}
any help?
I didnt test it but try this:
function yourFunction(){
var action_src = "http://localhost/test/<?php echo basename(__FILE__, ''); ?>" + document.getElementsByName("keywords")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
}
<?php
$imgDir = 'images/';
$images = glob($imgDir . '*.{jpg,jpeg,png,gif}',GLOB_BRACE);
echo json_encode($images);
?>
<script>
jQuery(function(){
var phpvar = '<?php echo json_encode($images) ?>';
jQuery('body').append('<img src="' + phpvar + '"/>');
});
</script>
The top php scans the folder 'images' and echoes all the file pathnames. However i want to use the array formed from this and append it to the document/body to display the images using . But i'm not sure how to pass the php variable '$images' to jquery/javascript
The phpvar that you're creating is actually an array (provided you remove the quotes), so you need to loop through this array and add each image separately, like this:
jQuery(function(){
var phpvar = <?php echo json_encode($images) ?>;
$.each(phpvar, function(id, image){
jQuery('body').append('<img src="' + image + '"/>');
});
});
In my opinion you are wasting processing and a needless framework for simple PHP array processing.
No need for either JSON, JSONEncode or jQuery:
foreach (glob('images/*.{jpg,jpeg,png,gif}',GLOB_BRACE) as $filename) {
echo '<img src=".$filename.'" alt="" />'."\n";
}
<?php
$imgDir = 'images/';
$images = glob($imgDir . '*.{jpg,jpeg,png,gif}',GLOB_BRACE);
$image_var ="";
foreach($images as $img)
{
$image_var.="<img src=".$img.">";
}
echo json_encode($image_var);
?>
<script>
jQuery(function(){
var phpvar = <?php echo json_encode($image_var) ?>;
jQuery('body').append(phpvar);
});
</script>
How do I pass a variable in a php file that is loaded into a page (DOM) to a jQuery function??
Iv'e tried various method's while searching online but I haven't figured out how to use them correctly.
I need the var navHeaderTitle to be passes to the jQuery load() callback function so it sets the HTML tag, #navHeaderTitle, to the variable called in the php file.
Thnx for you help.
php:
<?php
$con = mysql_connect("localhost","user","pw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM some_list");
$navHeaderTitle = "MY NEW TITLE";//<--I NEED 2 INJECT THIS!!
while($row = mysql_fetch_array($result))
{
echo "<div id='navItem' title='$navHeaderTitle'>";
echo "<h1>" . $row['label'] . "</h1>";
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "</div>";
}
mysql_close($con);
?>
JavaScript in the HTML Head:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function() {
$('#navHeaderTitle').text($(html).find('div#navItem').attr('title'));//<--GET THE VAR FROM LOADED PHP FILE!!
});
});
</script>
<body>
<div id="navPanel">
<div id="navHeader">
<img src="images/ic_return.png" style="float: left;"/>
<img id="listSortBtn" src="images/ic_list_sort.png" style="float: right;"/>
<h4 id="navHeaderTitle"></h4>//THIS IS WHAT NEEDS THE VAR DATA!!
</div>
<div id="navScrollContainer" class="navContentPosition">
<div id="navContent">HTML CONTENT from PHP GETS DUMPED IN HERE</div>
</div>
</div>
</body>
Ive tried using this but not sure how to:
$.get('scripts/my_list.php', {}, function(data){
data = split(':');
})
I would have the php file return a json object that contains two parts, the html you want to echo and the title you want to use.
Then I would use jQuery's .ajax() function instead of .load() to get the return value from your php script in a javascript variable instead of dumping it directly as .load() does.
replace echo("$navHeaderTitle"); with
echo("<script> var navHeaderTitle = $navHeaderTitle </script>");
and remove var navHeaderTitle = ''; from the <head> script..
that will setup a JS variable like you're using, but you have to do that before the code in the <head> loads...
EDIT
ok don't echo("$navHeaderTitle"); you can put it into the HTML like:
echo "<div id='navItem' title='$navHeaderTitle'>";
then in the JS you can do:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function(response) {
$('#navHeaderTitle').text($(response).attr('title'));
});
});
</script>
here's a jsfiddle demo: http://jsfiddle.net/JKirchartz/hdBzF/ (it's using fiddle's /echo/html/ so the load has some extra stuff to emulate the ajax)
It would be cleaner to pass the var in a custom attribute (data-var), then fetch it width JQuery
$(some_element).attr("data-var");
I hate to mess my JS code with php.
I have a problem with some JSON data. I don't know how to take some data generated in PHP and turn that into something that I can use in my jQuery script. The functionality I need is this: I need to be able to click on images on the page, and depending on the selected element, I need to show results from my DB.
Here's the HTML page that I've got:
<html>
<head>
<title>pippo</title>
<script><!-- Link to the JS snippet below --></script>
</head>
<body>
Contact List:
<ul>
<li><a href="#">
<img src="contacts/pippo.png" onclick="javascript:change('pippo')"/>pippo
</a></li>
<li><a href="#">
<img src="contacts/pluto.png" onclick="javascript:change('pluto')"/>pluto
</a></li>
<li><a href="#">
<img src="contacts/topolino.png" onclick="javascript:change('topolino')"/>topolino
</a></li>
</ul>
</body>
</html>
Here's PHP code being called:
<?php
include('../dll/config.php');
$surname = $_POST['surname'];
$result = mysql_query("select * from profile Where surname='$surname'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$_POST['name'] = ucfirst($row['name']);
$_POST['tel'] = $row['telephone'];
$_POST['companymail'] = $row['companymail'];
$_POST['mail'] = $row['email'];
$_POST['fbid'] = $row['facebook'];
}
?>
Here's the Ajax JavaScript code I'm using:
<script type="text/javascript">
function change(user) {
$.ajax({
type: "POST",
url: "chgcontact.php",
data: "surname="+user+"&name=&tel=&companymail=&mail=&fbid",
success: function(name,tel,companymail,mail,fbid){
alert(name);
}
});
return "";
}
</script>
Someone told me that this JS snippet would do what I want:
$.getJSON('chgcontact.php', function(user) {
var items = [name,surname,tel,companymail,email,facebook];
$.each(user, function(surname) {
items.push('surname="' + user + "'name='" + name + "'telephone='" + telephone + "'companymail='" + companymail + "'mail='" + mail + "'facebook='" + facebook);
});
/*
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
*/
});
But it is not clear to me - I don't understand how I need to use it or where I should include it in my code.
You will have to create a proper JSON string in your PHP script, and then echo that string at the end of the script.
A simple example:
$person = new stdClass;
$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )) {
$person->name = ucfirst($row['name']);
$person->tel = $row['telephone'];
$person->companymail = $row['companymail'];
$person->mail = $row['email'];
$person->fbid = $row['facebook'];
}
echo json_encode($person);
There are several problems with your code I have tried to explain via the corrected and commented code here:
HTML & JavaScript
<html>
<head><title>pippo</title>
<!-- added link to jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- javascript can go here -->
<script type="text/javascript">
$.ajax({
type: "POST",
url: "chgcontact.php",
// use javascript object instead of `get` string to represent data
data: {surname:user, name:'', tel:'', companymail:'', mail:'', fbid:''},
success: function(data){
// removed name,tel,companymail,mail,fbid
alert(JSON.parse(data));
}
});
return "";
}
</script>
</head>
<body>
Contact List:
<ul>
<!-- removed `javascript` form onclick handler -->
<li><img src="contacts/pippo.png" onclick="change('pippo')"/>pippo</li>
<li><img src="contacts/pluto.png" onclick="change('pluto')"/>pluto</li>
<li><img src="contacts/topolino.png" onclick="change('topolino')"/>topolino</li>
</ul>
</body>
</html>
PHP
<?php
$surname = $_POST['surname'];
$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )){
// create data object
$data = new stdClass();
// add values to data object
$data->name = ucfirst($row['name']);
$data->tel = $row['telephone'];
$data->companymail = $row['companymail'];
$data->mail = $row['email'];
$data->fbid = $row['facebook'];
// send header to ensure correct mime type
header("content-type: text/json");
// echo the json encoded data
echo json_encode($data);
}
?>
All code is untested, but you should be able to see what I have done at each step. Good luck.
And to expand on Brian Driscoll's answer. You will need to use the user.name format to access the name field from the returned $.getJSON("blah", function(user){});
so...
items.push('surname="'+user+"'name='"+user.name+"'telephone='"+user.telephone+"'companymail='"+user.companymail+"'email='"+user.email+"'facebook='"+user.facebook+);
In this format that you have created it will just push a long ugly looking string so you might want to spend some time making it look better. Good luck!
JSON that is POSTed to a PHP page generally isn't in the $_POST variable, rather it is in $HTTP_RAW_POST_DATA.
I like to get a dir listing in php
glob("*.jpg");
or
$dir = '.'; //requested directory to read
$notthat = array('.', '..'); //what not to include
$listedfiles = array_diff(scandir($dir), $notthat); // removed what not to include
so i like to send that array to a javascript like that (slides = $listedfiles)
function startSlideshow(slides) { .. do something..}
What is the best way to do that ?
json_encode is your friend for this. No looping is necessary. It will return a pure json object string that you can then just echo into your js file using PHP. Example:
var slides = <?php echo json_encode( $filelistarray );?>
function startSlideshow(slides) { .. do something..}
you can always just do an echo of it to a javascript :
echo ' <script type="text/javascript">
var filelist = [];
';
foreach($listedfiles as $file)
{
echo " filelist[] = $file; ";
}
echo "</script>";
PHP and Javascript cannot directly interact, however, you can output Javascript from PHP the same way you can output plain text or HTML:
<script type="text/javascript">
var slides = [];
<?php
foreach ($listedfiles as $file)
{
echo "slides[] = '" . addslashes($file) . "';\n";
}
?>
// ... do js stuff
</script>
Basically, after creating your array in PHP, you output the JS code to create the same array in javascript.