PHP and JavaScript: Getting a HTML value in PHP - php

I have a span, it looks like this:
<span class="price" id="product-price-167">€47.00</span>
The 47.00 is set dynamically using JavaScript. Now when the user clicks a button, a request to a PHP script is being triggered. I need the 47.00 in that script. How could I do that? I know JS is front end and PHP is server side, but is there some way?
Thanks :)
Solution: I am using a hidden field and read that using
$price = $_POST["price"];

You can use jquery to retrieve the value of the element:
var value = $('#product-price-167').text();
I think that should give you the 47.00.

Using JQuery:
You can get the price inside the span:
var price = $('#product-price-167').text();
You can then parse price accordingly to get rid of the Euro sign. Without knowing exactly where your button will be placed or how it will work, it's kind of difficult to tell you how to get it to your PHP script.
Note that you shouldn't parse as Float if this is a serious application: Use
var parsedNumber = Number(price.replace(/[^0-9\.]+/g,""));

you can easily use jquery to post that value to php page using ajax
<script type="text/javascript">
// i m assuming that 167 in id product-price-167 comes from database in a loop
function buttonClick(pid){
var price=$("#product-price-"+pid).text();
$.ajax({
type : "POST",
data : "price="+price,
url : "yourphppage.php",
success :function(data){
//return something from php page
}
});
}
</script>
and your input button
<input type="button" onclick="buttonClick('167')" />

var path = 'path-to-script.php';
var data = 'price='+Number($('#product-price-167').replace(/[^0-9\.]+/g,"")); // to remove redundant [currency] characters
$.post(path, data, function(returnText){
// do stuff here
});
That should do.

Related

unable to send parameter through ajax to a page itself

I am sending parameter to a page itself on keyup event.
I am sending a parameter though ajax like url:"http://localhost/application/views/pages/users/tags.php?tagfilter=lif",
and getting its value in a javascript function ('/instruction/showtags/<?php if( isset($_GET['tagfilter']) && $_GET['tagfilter'] == "") {echo $_GET['tagfilter'];} ?> ', {
I checked,my console , its showing no errors & no warning.
But i am sure its either not sending parameter or it may be its not getting the parameter.
Please let me know , why my parameter is not sending ? Is the way of writing ajax code is correct?
If you could not understand my question, then please let me know, i will try to explain it in some other way.
Full Source code:
tags.php
<input placeholder="Search" id="tagfilter" name="tagfilter" type="text"/>
Jquery/ajax function
<script type="text/javascript">
$(document).ready(function() {
$('#tagfilter').keyup(function(e){
// alert("called");
$.ajax({
url:"http://localhost/application/views/pages/users/tags.php?
tagfilter=lif",
type:"get",
success: function(){
}
});
});
});
</script>
My Infinite scroll js file, including in the same page
<script>
(function($) {
$.fn.scrollPagination = function(options) {
var settings = {
nop : 10, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : 'No More Data To Display!', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.
}
.............................
.............................
.............................
Update:
What exactly i am trying to do?
I have implemented a infinite scroll with jquery. When my page loads, it call my controller, and from from controller it takes data and display it in my view page.
Now , i plan to put search on this page with infinite scroll.
I have a textbox, from this textbox i am trying to do search on keyup event.
I am trying with this logic. If you have any better logic, please share with me,because i am struggling from long time to implement this.
Ok. I don't know your structure so what I have is few tips.
First: you need to know that javascript processing is much faster than PHP as long as JS is a Client Side language when PHP is Server Side language. so try to keep your php data in javascript vars like this:
var seg3 = "<?php echo $this->uri->segment(3) ?>";
$.post("/instruction/showtags/" + seg3, {...etc
then for your safety just try to check whether you need all the url not just part of it ( depends on CI configuration ) so your code can come up like this
var seg3 = "<?php echo $this->uri->segment(3) ?>";
var myurl = "<?php echo site_url('casting/send_email'); ?>" + seg3;
$.post(myurl, {...etc
And be sure not to use $_GET.
Second, make sure you're sending the segment and it's there. you can always use the
console.log() in javascript to keep up with the data and see if it's empty or not.
whether you want it on keyup or keydown or whatever it will be the same.
and if you are using json make sure to add it as the last arg to your $.post() method you can see the jquery api for it.
You check if $_GET['tagfilter'] == "", and only if the string is empty you print it.
so it should be:
<?php if( isset($_GET['tagfilter']) && $_GET['tagfilter'] != "") { echo $_GET['tagfilter'];} ?>

pass variable from input box to php

Hi all i know this question has been posted but being a total noob i couldnt get what answers meant. Please help. I want to pass inputbox value dynamically to a php variable . i am using javascript here please suggest if there's another way without using form submission , _GET or _POST. i want it done dynamically without any submission.
function showHint(str)
{
document.getElementById('TK').innerHTML = str;
var str = str
}
</script>
<html>
<head>Inputbox</head>
<title>TEST PAGE </TITLE>
<body>
<input type='text' id='TK' name='TK' onkeyup='showHint(this.value)'/>
<?php
$str = var str ;
echo "<a href = 'newpage.php?S=$str'/>" ; ?>
</body>
</html>
No. You can't. PHP is NOT a dynamic language, and it does NOT run client side. PHP runs once, and only once, and that's when the page is loaded. It runs its script and it stops. What you can do is get javascript to do an AJAX call. AJAX is basically a way of passing information to another page and getting the data, all in JavaScript. Do some research on it, but in short, you can't make PHP run once it's already been run
<script type="text/javascript" >
function process(){
var field1 = 'whatever';
var field2 = 'more whatever';
$.post("go.php",{field:field1,bext_field:field2},function(result){
alert(result);
});
};
</script>
This will alert out whatever you ECHO from GO.PHP.
You will also need a handler like:
onClick="process();"
on a div, button, image, just about anything you want to "initiate" your post
I would imagine the other answers you found probably would have said the following:
PHP executes before the user has a chance to see the page.
JS let you control what happens after.
Therefore, your problem is that you are trying to use PHP to do something it simply cannot.
Use those points to help guide your decisions when developing your applications. In this case, if you're trying to build a link based on what a user types in a box, your solution to the problem isn't PHP at all (the page is already loaded, you're too late!) -- your solution is JS.
Think about it like this:
/*
assumes you already have an <a> on the page. if not, you'll
have to create a new <a> element dynamically. (google "mdn createElement"
for help)
*/
function showHint (str) {
document.getElementById('TK').innerHTML = str;
var link = document.getElementById('your-a-link');
link.setAttribute('href', 'newpage.php?S=' + str);
}

How to get value from PHP array in jQuery?

I have a function:
$("button.btn-info").click(function() {
var id=this.id;
});
So, and I have to get item from PHP array $records with 'id' number. I need to insert this item into 'alert' function, but I don't know how I can pass variable from JS to PHP.
Please, tell me.
Use for example json_encode($records) and output it in a <script> tag in your html file like this:
<script type="text/javascript">
var records = <?php echo json_encode($records); ?>;
</script>
this should usually stand before your other js code that depends on the records-var.
or else you could use ajax (jQuery.get) if you want to load this var dynamically.
Not entirely sure I understand your question. It appears you just wish to write your PHP variable out to the javascript:
$("button.btn-info").click(function() {
var id=<?php echo $records->id?>;
});
Just remember that the Web page that hosts the JavaScript is static. If you want it to interact with PHP, you need to utilize AJAX or something else more advanced.

Can a variable go to a hidden PHP page using jQuery?

My PHP page
<ul id="upvote-the-image">
<li>Upvote<img src="image.png" /></li>
</ul>​
is currently successfully sending variable to javascript
$("#upvote").each(function(index) {
var upthis = $(this).attr("rel");
var plusone = upthis;
$.post("upvote.php", {
'plusone': plusone
});
alert(plusone);
});​
(The alert in the code is for testing)
I have multiple images using the rel tag. I would like for each to be able to be upvoted and shown that they are upvoted on the page without loading a new page.
My question, and problem: what is my next step? I would just like to know how to send a value to upvote.php. I know how touse mysql to add an upvote, just not how to send a value to upvote.php, or even if my javascript code opens the page correctly.
thanks
I think you need something like this:
<ul id="upvote-the-image">
<li><span rel="50" id="upvote">Upvote</span><img src="image.png" /></li>
</ul>​
<span id="result"></span>
$("#upvote").click(function(index) {
var upthis = $(this).attr("rel");
var oOptions = {
url: upvote.php, //the receiving data page
data: upthis, //the data to the server
complete: function() { $('#result').text('Thanks!') } //the result on the page
};
$.ajax(oOptions);
}
You dont need an anchor, I changed it for a span, you can test asyc connection using F12 in your browser
Your javascript never opens the php page, it just sends data to it, and receives an http header with a response. Your php script should be watching for $_POST['plusone'] and handle database processing accordingly. Your next step would be to write a callback within your $.post function, which I recommend changing to the full ajax function while learning, as it's easier to understand and see all the pieces of what's happening.
$.ajax({
type: 'POST',
url: "upvote.php",
data: {'plusone': plusone},
success: function(IDofSelectedImg){
//function to increment the rel value in the image that was clicked
$(IDofSelectedImg).attr("rel")= upthis +1;
},
});
You'd need some unique identifier for each img element in order to select it, and send it's id to the php script. add a class instead of id for upvote and make the id a uniquely identifiable number that you could target with jquery when you need to increment the rel value. (From the looks of it, It looks like you're putting the value from the rel attribute into the database in the place of the old value.)
A good programming tip here for JQuery, Don't do:
<a href="javascript:return false;"
Instead do something like:
$(function(){
$('#upvote').on('click', function(event){
event.preventDefault();
$.post('upvote.php', {'plusone': $(this).attr('rel')}, function(data){
alert('done and upvoted');
});
});
});
That is a much better way to handle links on your DOM document.
Here are some Doc pages for you to read about that coding I use:
http://api.jquery.com/on/
http://api.jquery.com/jQuery.post/
Those will explain my code to you.
Hope it helps,

PHP post and get value to a jQuery box page, refresh page as `msnbc.com`

Finally, I find some article in http://code.google.com/intl/en/web/ajaxcrawling/docs/getting-started.html msnbc use this method. Thanks for all the friends.
Thanks for your all help. I will study it for myself :-}
Today, I updated my question again, remove all of my code. Maybe my thinking all wrong.
I want make a products show page.
One is index.php, another is search.php (as a jquery box page). index.php has some products catagory lists; each click on product catagory item will pass each value to search.php. search.php will create a mysql query and view products details. It(search.php) also has a search box.(search.php can turn a page to show multiple products; the search result looks similar to a jQuery gallery...).
I need to do any thing in search.php but without refreshing index.php.
I tried many method while I was thinking: Make search.php as an iframe (but can not judge search.php height when it turn page and index.php without refresh); use jquery ajax/json pass value from index.php to search.php, then get back all page's value to index.php. (still met some url rule trouble. php depend on url pass values in search.php, but if the value change, the two page will refresh all. )
so. I think, ask, find, try...
Accidental, I find a site like my request.
in this url, change search word after %3D, only the box page refresh
in this url, change search word after = the page will refresh
I found somthing in its source code, is this the key rules?
<script type="text/javascript">
var fastReplace = function() {
var href = document.location.href;
var siteUrl = window.location.port ? window.location.protocol+'//'+window.location.hostname +':'+window.location.port : window.location.protocol+'//'+window.location.hostname;
var delimiter = href.indexOf('#!') !== -1 ? '#!wallState=' : '#wallState=';
var pieces = href.split(delimiter);
if ( pieces[1] ) {
var pieces2 = pieces[1].split('__');
if ( pieces2[1] && pieces2[1].length > 1) {
window.location.replace( unescape(pieces2[1].replace(/\+/g, " ")));
}
}
}();
</script>
If so. in my condition. one page is index.php. another is search.php.
How to use js make a search url like
index.php#search.php?word=XXX&page=XXX
then how to pass value from one to another and avoid refreshing index.php?
Still waiting for help, waiting for some simple working code, only js, pass value get value.
Thanks to all.
I have read your problem, though I can not write complete code for you (lack of time ) So I can suggest you to what to do for your best practice
use dataType ='json' in jQuery.ajax function and
write json_encode() on B.php
and json_decode() on A.php or $.getJSON()
Alternate:
Read
jQuery.load()
assuming you really want to do something like here: http://powerwall.msnbc.msn.com/
I guess they are using a combination of ajax-requests and something like this: http://tkyk.github.com/jquery-history-plugin/
make shure that the navigation (all links, etc.) in the box works via ajax - check all the links and give them new functionality by js. you can write some function which requests the href url via ajax and then replace the content of your box. ...
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
//update url in addressbar
change_box_links(output_area);
}
});
});
});
}
it is upgradeable but shell show the main idea...
addendum[2011-05-15]
Get away from thinking you will have two files, that can handle some many "boxes". i mean you can do this but it's worth it.
but to be able to set up your templates like normal html page you could use the above script to parse the ajax requested html pages.
build your html-pages for
viewing the content,
viewing the search result
, etc.
on your main page you have to provide some "box" where you can display what u need. i recommand a div:
<div id="yourbox"></div>
your main page has buttons to display that box with different content, like in the example page you have showed us. if you click one of those a JS will create an ajax call to the desired page:
(here with jquery)
$('#showsearch_button').bind('click', function(){showsearch();});
function show_search() {
$.ajax({
url: 'search.php',
success: function(data){
var output_area = $('#yourbox');
output_area.html(data);
$.address.hash('search');
change_box_links(output_area);
}
});
});
for other buttons you will have similar functions.
the first function (see above) provides that the requested box-content can be written as a normal html page (so you can call it as stand-alone as well). here is the update of it where it also provides the hashtag url changes:
jquery and requireing the history-plugin
function change_box_links(output_area){
output_area.find('a').each(function(){
$(this).bind('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.ajax({
url: url,
success: function(data){
output_area.html(data);
var name = url.replace('/\.php/','');
$.address.hash(name);
change_box_links(output_area);
}
});
});
});
}
and you will need some kind of this function, which will bind the back and forward buttons of your browser:
$.address.change(function(event) {
var name = $.address.hash();
switch(name){
case 'search': show_search(); break;
default: alert("page not found: "+name);
}
});
the above code should give an idea of how you can solve your problem. you will have to be very consequnt with filenames if you just copy and past this. again: it is improveable but shell show you the trick ;-)
im not sure that i fully understood what you want, but correct me if i didnt,
i think u need something like a dropdown that once the user select one item some div inside ur page show the result of another page result..
if so u can do it with jquery .load() and here is an example (no need for json)
Step 1:
Index.php
<p>
brand:<select id=jquerybrand>$jquerybrands</select><br />
Model:<select id=jquerycars></select><br />
</p>
<script type=\"text/javascript\">
$(document).ready(function(){
$('#jquerybrand').change(function(){
var value=$(this).value;
var url='api/quick.php?'+this.id+'='+this.value+' option';
$('#jquerycars').load(url);
});
});
</script>
This will simply show 2 dowpdown boxs (can be text or anything u like). and will add a listener to any change in value. once changed it will submit the id of the field and the new value to api/quick.php , then quick.php responce will be loaded into #jquerycars dropdown.
Step 2 quick.php
if(isset($_GET['jquerybrand'])){
$jquerycars="";
require_once("../lib/database.php");
$sql_db = new database();
$l=$sql_db->Item_in_table("car","sheet1","WHERE `brand`='$jquerybrand';");
foreach($l as $l)$jquerycars .="<option>$l</option>";
echo $jquerycars;//response that will replace the old #jquerycars
}
this will confirm that this is a request to get the query result only, then it will do the query and echo the results.
now once the results come back it will replace the old :)
hope it helps :).

Categories