I am using php and trying to fetch a value in a javascript function.
The javascript in the HTML page is the following:
<script type="text/javascript">
function show(q)
{
if(q.length > 0)
{
if(q.indexOf("tid") > -1)
{
location.href = "map.jsp?" + q;
}
else
{
location.href = "listmap.jsp?" + q;
}
}
return false;
}
$(function() {
$("#map").goMap({
latitude: -35.331415
,longitude: 149.131851
,maptype: 'ROADMAP'
,scrollwheel: false
,zoom: 11
,markers: [ {latitude: -35.192103,longitude: 149.332313,icon: 'images/m/marker1.png',html: {content: 'Loading...', ajax: 'mapinfo.jsp?sid=9057'}}]
I need to get the values of (3rd and 4th lines in second function) the latitude and longitude which are: -35.331415 and 149.131851
I'm just not sure how to access the individual values...
EDIT: I AM USING PHP to save these values in variables then later write them to a csv file
Currently i'm using this code (here's a snippit) to get everything else on other pages
<?php
$ch = curl_init("http://pvoutput.org/listmap.jsp?sid=312");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$cl = curl_exec($ch);
$dom = new DOMDocument();
#$dom ->loadHTML($cl);
$Lat_data = $dom -> getElementsByTagName("script");
print_r($Lat_data -> item(1) );
EDIT 2:
I fixed all the problems by doing this:
$Lat_data = $dom -> getElementsByTagName("script");
$content =$Lat_data -> item(10) -> textContent;
$regex = "/latitude: ([^\b,]*)/";
if (preg_match( $regex , $content , $values )) {
echo $values[1];
$regex2 = "/longitude: ([^\b,]*)/";
}
if (preg_match($regex2, $content, $values2)) {
echo $values2[1];
}
You managed to get the script node. Now you want its content (the javascript code)
$content = $Lat_data -> item(1) -> textContent
Once you got the content you can parse it using regex expression to get what you want
$regex = "/latitude: ([^\b\n]*)(.|\n)*,longitude: ([^\b\n,]*)/";
if (preg_match($regex, $content, $values)) {
echo 'latitude: ' . $values[0];
echo 'longitue: ' . $values[2];
}
regex explanation (test here):
finds "latitude: "
then we get the first group (), [^\b\n]* means anything but blackspace or newline characters
get anything between latitude value and ',longitude: '
next find ",longitude: "
third group just as the previous one. I added ',' so that if there is not blank between the longitude and ', maptype' it still works.
this regex explanation is getting a little messy, check the test link to more detailed explanation.
I have not tested it so there might be some syntax error but the idea is there ;)
Would it not be more efficient to implement a bit of ajax to submit the Longitude and Latitude from your js file to your php file?
Related
I have a php function which simply returns a value, I want to assign that value to a variable in my javascript code in my frontend page.
email_data() function in functions.php:
function email_data()
{
$a = 0;
$form_to_DB = WPCF7_Submission::get_instance();
if ( $form_to_DB )
$formData = $form_to_DB->get_posted_data();
$type = implode(',', $formData['type']);
$type = $type . ' ' . $formData['type-other'];
$place = implode(',', $formData['place']);
$place = $place . ' ' . $formData['place-other'];
$Postcode = $formData['Postcode'];
$date = $formData['date'];
$location_long = $formData['cf7-location-lng'];
$location_lat = $formData['cf7-location-lat'];
$location_litter = $formData['cf7-location-url'];
$location_litter = $formData['location-340'];
$comment = $formData['comment'];
if ($formData != null)
{
echo "Hi there! I want to report illegal dumping which consists of $type at $place area. The coordinates of the dumping are Lat: $location_lat, Long: $location_long.";
}
else
{
echo "Please fill the above form first!"
}
return $a;
}
I have some html and javascript code on one of my pages which I am using to display a form. Now, I want the variable returned by the php code to be saved in a JS variable. I have tried doing so many things but nothing works out, I am a newbie in WordPress dev sorry.
Check out wp_localize_script. It allows you to pass PHP variables to the browser, where your javascript can then read.
I'm trying to get a quantity value from external link, but I can't see this value until particular colour or size is selected (selection on that website works using JavaScript void(0) ).
Is it possible to trigger a link somehow and get the value after? Any suggestions?
However I know how to get a static value from url, see below:
$url = 'http://www.website.com/page.html';
$content = file_get_contents($url);
$first_step = explode( '<span id="quantity">' , $content );
$second_step = explode("</span>" , $first_step[1] );
echo $second_step[0];
Maybe solution, you can to split the process into two parts :
get all elements with regexp
preg_match_all('/<span [^>]+>/i',$content , $match);
print_r($match);
search attrs array of the result
$spans = array();
foreach( $match as $tag)
{
preg_match_all('/(id)=("[^"]*")/i',$tag, $spans[$tag]);
}
print_r($spans);
I have following code which is working in localhost in windows. But in the server same code fails.
It's the if condition which is not getting executed write even if data==found; I checked the returned data value which is found but cant figure out why the code is not executing properly
function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "ajaxcheck.php",
data:'tran_id='+$("#tran_id").val(),
type: "POST",
success:function(data){
console.log(data);
//var x=data;
$("#loaderIcon").hide();
//console.log((data=="found"));
if(data=="found")
{
$("#singlebutton").prop('disabled', false);
console.log("fail");
$("#tran_id-status").html("Found");
}
else
{
console.log(data);
$("#singlebutton").prop('disabled', true);
$("#tran_id-status").html("");
console.log("ss");
}
},
error:function (){}
});
}
Here is ajaxcheck.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$space=" ";
if(!empty($_POST["tran_id"])) {
$result = mysql_query("SELECT count(*) FROM bank WHERE tran_id ='" . $space.$_POST["tran_id"] . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0) {
// echo "<span class='status-not-available' id=\"stat\"name=\"stat\" value=\"ok\"> Transaction Details Found.</span>";
echo"found";
}else{
//echo "<span class='status-available' id = \"stat\" name =\"stat\"value=\"not\"> (Enter Valid transaction id to submit)</span>";
echo"notfound";
}
}
?>
The issue is that your data variable is coming back with a new line character. There are two solutions to this 1. trim the returned value. 2. figure out why the php is serving a new line.
Solution 1:
if(data.trim()=="found")
This uses the JS trim function, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim.
Solution 2:
Try removing the ?> from the end of your PHP file (the PHP file will still be valid). This way if there are extra lines after it they won't be served as output and the JS wont receive them.
From the manual:
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
What i'm trying to do is do display images from a directory and rotate every x seconds, in
this case 2 seconds.
I wrote this java script code and it works great but the image names are hard coded.
<script language="javascript" type="text/javascript">
img2 = new Image()
seconds = "2";
function imgOne()
{
setTimeout("imgTwo()", seconds * 1000);
}
function imgTwo()
{
document.myimg.src = "pics/WM/IMAGE02";
setTimeout("imgThree()", seconds * 1000);
}
function imgThree()
{
document.myimg.src = "pics/WM/IMAGE01";
setTimeout("imgOne()", seconds * 1000);
}
So I'm trying to use PHP to read the directory and create the javascript but am getting an internal server error. I'm using $p so it's img1 instead of imgOne so I can increase it. It loops thru and after the end loops back to 1. Any help is appreciated.
<?php
$files = glob('pics/WM/*.jpg');
echo
'
<script language="javascript" type="text/javascript">
img2 = new Image()
seconds = "2";
function img1()
{
setTimeout("img2()"), seconds * 1000);
}
'
$p=2;
for ($i=0; $i < count($files) $i++)
{
$image=$files[$i];
echo 'function img' .$p . '()'
echo '{'
echo 'document.myimg.src = "' .$image . '";'
$p++;
echo 'set Timeout(img"' .$p . '()", seconds * 1000); '
echo '}'
}
echo 'function img' .$p . '()'
echo '
{
document.img src="IMAGE01";
set Timeout("img1()", seconds * 1000);
}
</script> '
?>
the echostatements in your php scripts are missing the final ;. This should be the problem that causes the internal server error.
How to fix your implementation:
You should write something like
// using multiple echo statements
echo "..... your string ... ";
echo $p;
echo "--- something else ----";
// or you can concatenate strings with .
echo ".... your string ... " . $p . "---- something else ----";
Similar but safer and clearer PHP implementation:
Printing out Javascript code via PHP could be error prone, therefore I would recommend to use output big parts of text outside PHP code, like this
Some text where p = <?php echo $p; ?> is printed out.
How to improve the Javascript part:
Load all images at once
This is not related on the specific question, but simplifies your solution. Regarding your own project (rotating images), as suggested in the comments there are many reusable javascript components you can use (firstly using some javascript libraries, e.g. jQuery). But if you want to develop this feature by yourself, keep in mind that changing the src attribute of an image tells the browser to download it from scratch, resulting in glitches. To solve this issue, you may insert many <img> elements and than display it one at the time (using css styling directives).
Iterate over the images using one timed function
Furthermore, you could simplify your javascript code: instead of using a different function to display each image you can use global variables (i.e. window.my_rotate_current_img_id) or better clojures to select and show the current image:
// 1. Declare an array of img tags ID, identifying the different images
// Note that we are using PHP to generate the array - the implode function
// concatenates array items into a string separated by the first argument
// given
var images = [<?php echo '"' . implode('","', $images) . '"'; ?>];
// 2. Define a function that shows the correct image
function hide_first_and_show_second(first, second){ ... }
// img_num is the number of images to rotate
var update_img = function(idx){
return function(){
hide_idx = idx;
show_idx = (idx + 1) % img_num;
hide_first_and_show_second(hide_idx, show_idx);
}
};
setInterval(update_img(0), 1000);
This are possible (and useful) improvements of your solution for this problem. Hope i clarified.
I am using the following to encode the html source of a ckeditor in a web application.
var updateString = app.getValue('wysiwygHomePage');
var encodedString = encodeURIComponent(updateString);
alert(encodedString);
app.httpRequest("www.xxxx.com/techy/savealldata.php", "GET", function(data, error, httpResponse){
alert(data);
},
{
"updateType":"homePage","updateString":encodedString}, "String", {}, {});
}
Then at the PHP end I am using :
<?php
$updateType = $_GET["updateType"];
$updateString = $_GET["updateString"];
$updateString2 = urldecode($updateString);
echo 'success here '.$updateType .' '.$updateString2 ;
?>
I am adding some coloured tex and the html source for this is:
<p>
<span style="color: rgb(255, 140, 0);">123</span><br />
</p>
<p>
This works okay until I cut and paste more than 32 times.
I then just get error returned from the PHP call.
I presume there are to many chars arriving at the PHP end ???
Any ideas why this is happening ?
Mr WARBY.
UPDATED PHP Code.
<?php
include 'dbdata.php';
$updateType = $_POST["updateType"];
$updateString = $_POST["updateString"];
$updateString2 = urldecode($updateString);
//echo 'success here '.$updateType .' '.$updateString2 ;
if($updateType === 'homePage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 12";
//echo $query5;
echo 'Home Page Updated 2';
mysql_query($query5);
}
if($updateType === 'instructionPage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 13";
echo 'Instruction Page Updated 2';
mysql_query($query5);
}
if($updateType === 'FAQPage')
{
$query5 = "UPDATE pageText SET HTML= "."'".$updateString2."'"." WHERE ID = 14";
echo 'FAQ Page Updated';
mysql_query($query5);
}
?>
There are a lot of variables in play here. You need to change your debugging strategy. Instead of testing end to end each time try isolating each component.
In Javascript, call "app.getValue('wysiwygHomePage')", encode the string, decode the string, and put it right back in the editor. Do that in a loop until you can determine if the client-side is mangling anything.
If not, try encoding a complicated string in Javascript, sending it to a PHP script that decodes/re-encodes and echos it back. Do that in a loop several times.
If you still haven't found the problem try making a PHP script that takes a complicated string, INSERTS it, SELECTs it, UPDATEs it in a loop to see if you database encoding or escaping is affecting it.
If at any point you find the string changing when it shouldn't you've probably found your problem.