How to get dynamically changing value from external url in PHP? - javascript

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);

Related

How to dynamically pass an array of values to a <select> field in Contact Form 7?

According to the official Contact Form 7 docs, it is possible to pass a a default value to CF7 from the shortcode, in this way:
// field in CF7 in Wordpress admin area
[email* destination-email default:shortcode_attr]
// shortcode in a Wordpress php template
[contact-form-7 id="123" title="Contact Form" destination-email="xxxxxx#example.com"]
// function in functions.php
add_filter( 'shortcode_atts_wpcf7', 'custom_shortcode_atts_wpcf7_filter', 10, 3 );
function custom_shortcode_atts_wpcf7_filter( $out, $pairs, $atts ) {
$my_attr = 'destination-email';
if ( isset( $atts[$my_attr] ) ) {
$out[$my_attr] = $atts[$my_attr];
}
return $out;
}
This works for a simple text field, but I need to pass an array of values to a <select> field and use them as <option>s inside it; I've tried to modify a bit this code, but apparently it isn't working, or at least I've not been able to.
Is it possible to use the shortcode to send dynamic data to CF7 even if not a single plain text like this?
If not, I'm open to every other kind of solution, even if it involves another method, or some additional plugin; is there some other way to dynamically send an array of values to <select> fields in Contact Form 7?
These values are data queried from the database (such as post names, custom fields, and so on), so they need to come from php first even if there is a solution that involves javascript.
Here's an example of a form tag I've used for getting US States. This is a <select> generated from an array. This is probably more along the lines of what you want to do.
You can see that I also use the usermeta billing_state to pre-select the choice.
With that said, you should also be able to use this same method to create a select tag that performs any WP_Query and puts the results into an option tag.
<?php
add_action('wpcf7_init', function (){
wpcf7_add_form_tag( array('dd_states', 'dd_states*'), 'cf7_state_dropdown' , true );
});
function cf7_state_dropdown($tag) {
$tag = new WPCF7_FormTag( $tag );
$atts = array();
$validation_error = wpcf7_get_validation_error( $tag->type );
$class = wpcf7_form_controls_class( $tag->type );
if ( $validation_error ) {
$class .= ' wpcf7-not-valid';
}
$atts['class'] = $tag->get_class_option( $class );
$atts['aria-required'] = 'true';
$atts['aria-invalid'] = $validation_error ? 'true' : 'false';
$atts = wpcf7_format_atts( $atts );
// Get User ID and Billing State from DB
$userid = get_current_user_id();
$user_state = get_user_meta($userid, 'billing_state', true);
$states = array ( 'FL'=>'Florida','AL'=>'Alabama','AK'=>'Alaska','AZ'=>'Arizona','AR'=>'Arkansas','CA'=>'California','CO'=>'Colorado','CT'=>'Connecticut','DE'=>'Delaware','DC'=>'District of Columbia','GA'=>'Georgia','HI'=>'Hawaii','ID'=>'Idaho','IL'=>'Illinois','IN'=>'Indiana','IA'=>'Iowa','KS'=>'Kansas','KY'=>'Kentucky','LA'=>'Louisiana','ME'=>'Maine','MD'=>'Maryland','MA'=>'Massachusetts','MI'=>'Michigan','MN'=>'Minnesota','MS'=>'Mississippi','MO'=>'Missouri','MT'=>'Montana','NE'=>'Nebraska','NV'=>'Nevada','NH'=>'New Hampshire','NJ'=>'New Jersey','NM'=>'New Mexico','NY'=>'New York','NC'=>'North Carolina','ND'=>'North Dakota','OH'=>'Ohio','OK'=>'Oklahoma','OR'=>'Oregon','PA'=>'Pennsylvania','RI'=>'Rhode Island','SC'=>'South Carolina','SD'=>'South Dakota','TN'=>'Tennessee','TX'=>'Texas','UT'=>'Utah','VT'=>'Vermont','VA'=>'Virginia','WA'=>'Washington','WV'=>'West Virginia','WI'=>'Wisconsin','WY'=>'Wyoming');
$output = '<span class="wpcf7-form-control-wrap '.sanitize_html_class( $tag->name ).'"><select name="state" id="state" '.$atts.'>';
$output .= "<option value=\"\"> - - Choose State - - </option>";
foreach ($states as $abbrev=>$state){
$selected = ($user_state == $abbrev) ? ' selected="selected"' : '';
$output .= '<option value="'.$abbrev.'"'. $selected .'>'.$state.'</option>';
}
$output .= "</select></span>";
$output .= $validation_error;
return $output;
}

Get text area value as php variable

I have a text area field and I want to get value as variable so that I can use these variable to fetch data from mysql.
<?
$sms = $_POST['message'];
$whatIWant = substr($sms, strpos($sms, "#") + 1);
echo $whatIWant;
?>
this is a image of textarea
I tried these code but it's not output as I want.
How can I retrieve variables from this input value? Thanks
You can try something like:
$str = 'Hello #Fahim#. Im from #Mazegeek,Inc#. My phone no is #011111#';
preg_match_all('/(?<=#).*?(?=#)/', $str, $m);
print_r($m);
let me know if it works.

Format the content and display media

I have a textarea where I can enter the content:
<textarea name="content" placeholder="Content"></textarea>
The type of the content column in the DB is Text.
So I could add text there and then insert that text to the DB:
$stmt = $conn->prepare('INSERT INTO content VALUES(?)');
$stmt->execute( [$content] );
Then I show that content some where on my website:
$stmt = $conn->prepare('SELECT content FROM posts');
$stmt->execute();
$results = $stmt->fetchAll();
foreach( $results as $result ){
echo '<div>'. $result .'</div>';
}
But that content is then showed as a plain text, So if I entered:
$content = "This content contains a URL http://example.com";
I get: This content contains a URL http://example.com, So the link is not shown as a link, But a plain text.
Also if I added an image:
$content = "http://example.com/images/img.jpg";
Or a video:
$content = "http://example.com/images/video.mp4";
Or a video from Youtube.
So what should I do?
Should I use PHP or Javascript to check if the content contains a URL/image/video, Then add the related html elements to that URL?
I would not recommend using an editor like CKEditor just to wrap some URLs in markup, as others have shockingly suggested. That is a very lazy and expensive (not necessarily price but size of files and number of requests) way of solving a simple task.
The following solution is untested and the regex patterns were taken from external sources, so I unfortunately can't guarantee their correctness. Try it yourself and test, test, test.
EXAMPLE
// your string
$content = "This is the content https://example.com/images/image1.jpg";
// find all URLs in $content and add matches to $matches array
$regex = "#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#";
preg_match_all($regex, $content, $matches);
// loop through $matches array
foreach ($matches as $match) {
// check each item in array and use regex to determine type
if (preg_match('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $match)) {
$markup = '<img src="'.$match.'">';
} else {
$markup = ''.$match.'';
}
// now replace the $match'ed URL in $content with the right $markup
str_replace($match, $markup, $content);
}
DOCS
preg_match_all: http://php.net/manual/en/function.preg-match-all.php
preg_match: http://php.net/manual/en/function.preg-match.php
str_replace: http://php.net/manual/en/function.str-replace.php

Get embedded values in javascript function on HTML Page

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?

Error when sending html source from javascript to PHP

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.

Categories