This question already has answers here:
jQuery simple value get issue with .val()
(3 answers)
Closed 9 years ago.
thanks for taking the time. I'm working on building a visual shopping cart into multiple pages of a parallax site. Because each 'page' of the parallax forces open and close a form, I cannot use a continuous form. To remedy this, I am using jquery to place the value of the choices on the preceding pages into one page, filling spans.
I'd like to be able to grab these final choices from the dom using ajax to put them to a processing page to store the customers choice information, and check it against a dwolla transaction. I haven't got to setting up the dwolla transaction and check yet, because I have not been able to get my data to the php processing page, and get it to return an echo-able value. This is built off wordpress by the way, and allot of times, filters wordpress is implementing screw me up.
Here's the site; http://ecigjuiceclub.com
Lets jump into the code!
AJAX:
function post()
{
var name = $('#cname').val();
var street1 = $('#cstreet').val();
var street2 = $('#cstreet2').val();
var city = $('#ccity').val();
var state = $('#cstate').val();
var zip = $('#czip').val();
var email = $('#cemail').val();
var phone = $('#cphone').val();
var flavor = $('#cflavor').val();
var strength = $('#cstrength').val();
var refcode = $('#crefcode').val();
$.post('process.php',{postname:cname,poststreet1:cstreet,poststreet2:cstreet2,postcity:ccity,poststate:cstate,postzip:czip,postemail:cemail,postphone:cphone,postflavor:cflavor,poststrength:cstrength,postref:crefcode},
function(data)
{
$('#thankyou').html(data);
});
}
Php process.php
<?php
$name = $_POST['postname'];
$street1 = $_POST['poststreet1'];
$street2 = $_POST['poststreet2'];
$city = $_POST['postcity'];
$state = $_POST['poststate'];
$zip = $_POST['postzip'];
$email = $_POST['postemail'];
$phone = $_POST['postphone'];
$flavor = $_POST['postflavor'];
$strength = $_POST['poststrength'];
$refcode = $_POST['postref'];
if($zip == 90804)
{
echo "1";
}
else
{
echo "0";
}
?>
HTML Snippet (where in the DOM I'm attempting to grab):
<span style="color:#EF5D3D;">Email: </span><span style="font-size:28px;" id="cemail"></span>
<span style="color:#EF5D3D;">Phone: </span><span style="font-size:28px;" id="cphone"></span>
i think you better try innerHTML instead values i dont know the exact syntax in jquery. iprefer u use input or else instead span
var email = $('#cemail').text();
var phone = $('#cphone').text();
These should be the replacements on the post() function. Adding an alert message (as an example) at the opening of the post() function could help you check their values before they get passed in the Ajax request.
alert($('#cemail').text() + ' ' $('#cphone').text());
Also make sure to clear your cache just to make sure your javascript edits have been implemented.
The console is showing the following errors which may or maynot prevent other scripts from running:
Uncaught ReferenceError: Modernizr is not defined
ecigjuiceclub.com/:825
Blocked a frame with origin "https://www.youtube.com" from accessing a
frame with origin "http://ecigjuiceclub.com". The frame requesting
access has a protocol of "https", the frame being accessed has a
protocol of "http". Protocols must match.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can i select the fragment after the '#' symbol in my URL using PHP?
The result that i want is "photo45".
This is an example URL:
http://example.com/site/gallery/1#photo45
If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.
That part is called "fragment" and you can get it in this way:
$url=parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
A) already have url with #hash in PHP? Easy! Just parse it out !
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
B) You want to get a #hash by sending a form to PHP? => Use some JavaScript MAGIC! (To pre-process the form)
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']
Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )
C) You want to get the #hash in PHP JUST from requested URL?
YOU CAN'T !
...(not while considering regular HTTP requests)...
...Hope this helped :)
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23.
This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No
Escape.
Discussion: This technique will of course also work with other special
characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
You can't get the text after the hash mark. It is not sent to the server in a request.
I found this trick if you insist want the value with PHP.
split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP
If you are wanting to dynamically grab the hash from URL, this should work:
https://stackoverflow.com/a/57368072/2062851
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.
setup your strings with a div id, so the name anchor goes where its supposed to and the JavaScript can change the text colors
<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>
Use JavaScript to do the heavy work, on the server side, inserted in your PHP page, or wherever..
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
I am launching the Java function automatically when the page is loaded.
<script>
$( document ).ready(function() {
get the anchor (#tesla) from the URL received by the server
var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
trim the hash sign off of it
myhash1 = myhash1.substr(1) //myhash1 == tesla
I need to highlight the term and the description so I create a new var
var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
Now I can manipulate the text color for the term and description
var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>
This works. client clicks link on client side (example.com#tesla) and goes right to the term. the term and the description are highlighted in blue by JavaScript for quick reading .. all other entries left in black..
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How can i select the fragment after the '#' symbol in my URL using PHP?
The result that i want is "photo45".
This is an example URL:
http://example.com/site/gallery/1#photo45
If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.
If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.
That part is called "fragment" and you can get it in this way:
$url=parse_url("http://example.com/site/gallery/1#photo45 ");
echo $url["fragment"]; //This variable contains the fragment
A) already have url with #hash in PHP? Easy! Just parse it out !
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
B) You want to get a #hash by sending a form to PHP? => Use some JavaScript MAGIC! (To pre-process the form)
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form's method attribute you get this hash in PHP by:
$_GET['fragment'] or $_POST['fragment']
Possible returns: 1. ""[empty string] (no hash) 2. whole hash INCLUDING the #[hash] sign (because we've used the window.location.hash in JavaScript which just works that way :) )
C) You want to get the #hash in PHP JUST from requested URL?
YOU CAN'T !
...(not while considering regular HTTP requests)...
...Hope this helped :)
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23.
This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No
Escape.
Discussion: This technique will of course also work with other special
characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
You can't get the text after the hash mark. It is not sent to the server in a request.
I found this trick if you insist want the value with PHP.
split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP
If you are wanting to dynamically grab the hash from URL, this should work:
https://stackoverflow.com/a/57368072/2062851
<script>
var hash = window.location.hash, //get the hash from url
cleanhash = hash.replace("#", ""); //remove the #
//alert(cleanhash);
</script>
<?php
$hash = "<script>document.writeln(cleanhash);</script>";
echo $hash;
?>
You can do it by a combination of javascript and php:
<div id="cont"></div>
And by the other side;
<script>
var h = window.location.hash;
var h1 = (win.substr(1));//string with no #
var q1 = '<input type="text" id="hash" name="hash" value="'+h1+'">';
setInterval(function(){
if(win1!="")
{
document.querySelector('#cont').innerHTML = q1;
} else alert("Something went wrong")
},1000);
</script>
Then, on form submit you can retrieve the value via $_POST['hash'] (set the form)
You need to parse the url first, so it goes like this:
$url = "https://www.example.com/profile#picture";
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
If you need to parse the actual url of the current browser, you need to request to call the server.
$url = $_SERVER["REQUEST_URI"];
$fragment = parse_url($url,PHP_URL_FRAGMENT); //this variable holds the value - 'picture'
Getting the data after the hashmark in a query string is simple. Here is an example used for when a client accesses a glossary of terms from a book. It takes the name anchor delivered (#tesla), and delivers the client to that term and highlights the term and its description in blue so its easy to see.
setup your strings with a div id, so the name anchor goes where its supposed to and the JavaScript can change the text colors
<div id="tesla">Tesla</div>
<div id="tesla1">An energy company</div>
Use JavaScript to do the heavy work, on the server side, inserted in your PHP page, or wherever..
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
I am launching the Java function automatically when the page is loaded.
<script>
$( document ).ready(function() {
get the anchor (#tesla) from the URL received by the server
var myhash1 = $(location).attr('hash'); //myhash1 == #tesla
trim the hash sign off of it
myhash1 = myhash1.substr(1) //myhash1 == tesla
I need to highlight the term and the description so I create a new var
var myhash2 = '1';
myhash2 = myhash1.concat(myhash2); //myhash2 == tesla1
Now I can manipulate the text color for the term and description
var elem = document.getElementById(myhash1);
elem.style.color = 'blue';
elem = document.getElementById(myhash2);
elem.style.color = 'blue';
});
</script>
This works. client clicks link on client side (example.com#tesla) and goes right to the term. the term and the description are highlighted in blue by JavaScript for quick reading .. all other entries left in black..
i know this question is asked many times, but non of them having right solution. i am using ajax to get the response from PHP Page. After getting the response i want to use the value in PHP variable. Below code is getting result but i am confused with the usage of it.
below is my index.php
function getLocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function geoSuccess(position) {
var glat = position.coords.latitude;
var glng = position.coords.longitude;
//alert("lat:" + glat + " lng:" + glng);
geocoding(glat,glng);
}
function geoError() {
alert("Geocoder failed.");
}
function geocoding(glat,glng){
$.ajax({
type:'POST',
url:'geolocation.php',
data:'latitude='+glat+'&longitude='+glng,
success:function(result){
if(result){
$("#locationg").val(result);
$("#htmllocation").html(result);
}
}
});
}
geolocation.php
<?php
session_start();
if(!empty($_POST['latitude']) && !empty($_POST['longitude'])){
//Send request and receive json data by latitude and longitude
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($_POST['latitude']).','.trim($_POST['longitude']).'&sensor=false';
$json = #file_get_contents($url);
$data = json_decode($json);
$status = $data->status;
if($status=="OK"){
//Get address from json data
$location = $data->results[0]->formatted_address;
//$location = $data->results[0]->address_components;
for($j=0;$j<count($data->results[0]->address_components);$j++){
$cn=array($data->results[0]->address_components[$j]->types[0]);
if(in_array("locality", $cn))
{
$city= $data->results[0]->address_components[$j]->long_name;
}
}
}else{
echo 'No Location';
}
echo $city;
}
?>
index.php
<?php
$city='<span id="htmllocation"></span>';
?>
when i echo $city i am getting city name but in inspect elements its showing like
<span id="htmllocation">Visakhapatnam</span>
issue is that i can not use this in MYSQL because it in html format, and i just want to get only the city name nothing else.
i hope my issue is clear, please leave a comment if not clear.
The user locates example.com/index.php, it displays a webpage.
You get the user's location from JS.
You send it back to the server, and get the addresses of that location.
Then you want to access the addresses from index.php
Is that correct? If so, you can't do it. Things not work like that. Webservers uses request-response modells. When your php finishes, the server kills the process, ei. $city and everything else are destroied. After it, you get the user's location. If you want something from the server again, you must send a new request, because index.php's process is no longer available. This is impossible to get the city's name before you get it from the client, and you can't get the location from the client at the moment he first requests index.php, neither you can access an already-non-running process.
All you need to do is run your SQL query inside geolocation.php. When you get the result from Google, then fetch the data from your database. There $city doesn't contain any HTML codes, only the plain city name. Then send back some data related to that city to the user, and display it.
initially start session in PHP using
sessionstart()
method. then add this code after above code.
First set session using Jquery as below:
$.session.set("yoursessioname", "storevalue");
then try to get this session variable in PHP as below:
$city = $_SESSION['yoursessioname'];
I haven't tried it yet. I Hope it helps. :)
Use PHP in built function strip_tags to remove HTML tags from your statement to get only City in variable like below:
$city = strip_tags('<span id="htmllocation">Visakhapatnam</span>');
// Output will be Visakhapatnam only
I am currently able to refresh a div on my website using jquery with php. This works well to a point. The issue is that the data being refreshed currently is an entire table. The code being used in the header is as follows:
<!-- DIV REFRESH START -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
var auto_refresh = setInterval(
function()
{
$('#datatable').fadeOut('slow').load('data/table.php').fadeIn("slow");
}, 10000);
</script>
<!-- DIV REFRESH END -->
As you can see, it is refreshing a specific div with a specific page. I'm very novice with jquery and java based coding in general as I'm sure will be evident in this question.
Is it possible to do the following:
The table is actually created in a php function due to the the fact that the number of rows changes all the time. Is it possible to have it refresh the function specifically rather than a page that is just calling the function?
The table currently refreshes completely. This is just to update one figure on each row. It would be much cleaner to have it only refresh each figure on the row but due to the flexible nature of the table and the fact that it is part of a function would this be possible? If so, how would it be possible? I know I could have each div on each row to have a unique div name which I could then take into account in the script section at the top of the page but would that not require having every possible div name added with the same code repeated?
Though I know it is possible to have the item refresh based on when something in the database changes rather than by a time delay but what would be the best way given the requirements listed above?
I could be way off and it's a simple answer to each question but I appreciate any and all input.
Thanks!
p.s. if it helps, the function I'm currently using to create the table is the following (I know it can be made to function much cleaner but it is a bit of a learning project):
function portalTable($venueId, $eventId)
{
echo "<table class='basic-table'><tr class='th'><th>Portal Name</th><th>Scanned</th></tr>";
$grandTotals = array();
$portalSql = mysql_query("SELECT * FROM portal WHERE id_venue = $venueId");
while ($portalRow = mysql_fetch_array($portalSql))
{
$portalId = $portalRow['id_portal'];
$portalName = $portalRow['name_portal'];
if($portalId&1) {$gray = "dg";} else {$gray = "lg";}
$sql = mysql_query("SELECT * FROM scan WHERE id_event = $eventId AND id_portal = $portalId");
while ($row = mysql_fetch_array($sql))
{
$scanTotal = $row['total_scan'];
echo "<tr class='$gray'><td>$portalName</td><td>$scanTotal</td></tr>";
$grandTotals[] = $scanTotal;
}
}
$totals = array_sum($grandTotals);
echo "<tr class='basic-table-total'><td>Total</td><td>$totals</td></tr>";
// total failed scans
$sql = mysql_query("SELECT total_errors FROM errors WHERE id_event = $eventId");
while ($row = mysql_fetch_array($sql))
{
$totalErrors = $row['total_errors'];
echo "<tr class='basic-table-total'><th>Total Rejected Scans</th><th>$totalErrors</th></tr>";
}
echo "</table>";
}
$('div.myDiv').each(function(i, obj) {
$(obj).load('myURL.php');
});
That what you're looking for?
As for the large amount of data being sent? Don't send raw HTML!
Instead, use parseJSON in jQuery and json_encode in your PHP script to send a (much) smaller amount of data to the user, which can then be used by the client to make the table.
Handling the decoded JSON data is relatively simple in JavaScript. Once it has been decoded, it is now an accessible object. You can use an iterator (jQuery does this well).
$.each(myJSON, function(i, val) {
$('body').append(val + "<br />");
});
I have a specific array that php needs to access and write to a file. I also want to be able to call the php to get the array info back. I use JSON.strigify to store the array in a string, but i cant figure out how to send it to a server with php. I have very little php experience and i tried:
<script language="javascript">
var COMMENTS_FOR_DISPLAY = new Array('Have fun with this code: Chris');
// Adds a new comment, name pair to the Array feeding textualizer.
function add_comment() {
// Retrieve values and add them to Array.
var new_comment = $('#kwote').val();
var new_name = $('#name').val();
COMMENTS_FOR_DISPLAY.push(new_comment + ': ' + new_name);
// Reset <input> fields.
$('#kwote').val('');
$('#name').val('');
var arrayAsString = JSON.stringify(COMMENTS_FOR_DISPLAY);
}
$(document).ready(function() {
var txt = $('#txtlzr'); // The container in which to render the list
var options = {
duration: 5, // Time (ms) each blurb will remain on screen
rearrangeDuration: 5, // Time a character takes to reach its position
effect: 'random', // Animation effect the characters use to appear
centered: true // Centers the text relative to its container
}
txt.textualizer(COMMENTS_FOR_DISPLAY); // textualize it!
txt.textualizer('start'); // start
});
</script>
in main.php i put:
<?php
$kwoteString = $_GET["arrayAsString"];
echo $kwoteString;
?>
I used echo to see if i was getting any output,but i wasn't. It could be a very simple fix, maybe im missing a header or something telling my html document to read main.php?? any help would be appreciated!
Use jquery with
$.post(url,params);
there are many tutorials around the web and stack overflow itself.
Here the doc:
http://api.jquery.com/jQuery.post/
you can add a hiddenField and set the string to the hidden field.
php code will read the value from hidden field.