Get input value from parent document - php

I'm using CURL to scrape a website like this:
<?php
$url = "http://www.bbc.com/news/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
$curl_scraped_page = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.bbc.com/news/$2$3', $curl_scraped_page);
echo $curl_scraped_page;
?>
As you can see the URL is set for BBC news. However, I would like the URL to be a variable instead. The variable would have to be the value of parent.document. In JQuery for example I would do this:
var value = $("input", parent.document.body).val();
How do I set something like that in PHP? I have Googled but I couldn't find anything about parent.document in PHP.

PHP is a server-side scripting language and therefore has no access to the current HTML page. It is processed before the HTML is sent to the client's browser, therefore parent.document doesn't even exist at the time the script is being processed.
If you would like to pass data from an HTML page to a PHP script, you can do so using an HTML <form> or through JavaScript/JQuery AJAX requests.
For example, the following code will pass the value of input to the PHP script:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function pass(){
var value = $("input", parent.document.body).val();
$.ajax({
type: "POST",
url: "myscript.php",
data: { mydata: value }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
</head>
<body>
<input type="text" />
<button onclick="pass();return false;">Pass Value</button>
</body>
</html>
And the revised script (myscript.php):
<?php
$url = isset($_POST['mydata']) ? $_POST['mydata'] : '';
$curl_scraped_page = '';
if(!empty($url)){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
$curl_scraped_page = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1'.$url.'$2$3', $curl_scraped_page);
}
echo $curl_scraped_page;
?>
I would recommend using $(id) to retrieve the value of an <input> instead of $("input",context).
E.g.
var value = $('#txt').val();
And in the HTML:
<input type="text" id="txt" />
For more info on JQuery.ajax see here.

Related

Attempting to stimulate page to produce server sent event with POST data from another page not working

When I open update.php on its own (with self supplied test vars), it sends the SSE to testsse.php just fine and there are no issues (Everything I need to be printed is showing up in inspect element), However, I am trying to have POST data from another page (In this case mootssetest.php) get received by update.php so it may send out the SSE containing the data. I am not sure what I am doing wrong, but this test rig is not working. Guidance would be appreciated.
testsse.php (front end page meant to receive SSE and print)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Using Server-Sent Events</title>
<script>
window.onload = function() {
var link = new EventSource("update.php");
var antispam;
var inputthing = event.data;
var splitted;
link.onmessage = function(event) {
inputthing = event.data;
splitted = inputthing.split(" ");
if (splitted[0] != antispam && splitted[1] == <?php echo $page; ?>) {
document.getElementById("livemsg").innerHTML += "<div id=\"post-" + splitted[0] + "\" class=\"reply\">" + "</div>";
antispam = splitted[0];
};
};
};
</script>
</head>
<body>
<div id="livemsg">
<!--Server response will be inserted here-->
</div>
</body>
</html>
update.php (SSE sender, post receiver)
<?php
$data = json_decode(file_get_contents('php://input'), true);
$postnum = $data[0];
$bread = $data[1];
postnum = 32;
bread = 4;
function liveupdate($postnum, $bread)
{
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
echo "data: " . $postnum . " " . $bread . "\n\n";
flush();
}
liveupdate($postnum, $bread);
?>
mootssetest.php (POST sender)
function httppost($postnum, $bread)
{
$url = "http://localhost/update.php";
$data = array($postnum, $bread);
$curl = curl_init($url);
$jsondata = json_encode($data);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $jsondata );
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
httppost(420, 4);
?>
(For context, I am trying to have this print a new post in some forum software every time a function is called without refreshing the page for the user)
you haven't included the event in your window.onload() function, please fix it first and try again.

Is it possible to POST data to a link inside while loop using PHP? [duplicate]

This question already has answers here:
How do I send a POST request with PHP?
(18 answers)
POST data to a URL in PHP
(3 answers)
Closed 4 years ago.
I am using basic PHP & AJAX and I want to post data that i have selected from mysql database to a link online and fetch the response sent back to be used in update other information. I am using AJAX to post the data, but i cannot fetch the data sent back to use to update information.
Is it possible to just use PHP directly? how can it be done? What is the best way ?
Code:
$sql = $conn->query("SELECT * FROM hospitals");
if($sql){
// $json_array = array();
while($row = $sql->fetch_assoc()){
$output = '{"h_code": "' . $row['h_code'] . '", "h_name": "' . $row['h_name'] . '"}';
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
url: 'http://example.com/api/link',
method: 'POST',
data: <?php echo $output; ?>,
success: function(data){
console.log(data);
}
});
</script>
<?php
$update = $conn->query("UPDATE hospital SET h_online_id= ");
}
}
the response from AJAX call 'data' returns value from online database which i want to update a column from in the local database.
You have to be careful here... PHP is server side and JavaScript Client (You would write that Javascript Code to the page X times!) Why don't you use CURL for this?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://example.com/api/link");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"postvar1=value1&postvar2=value2&postvar3=value3"); // modify $output
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
// Further processing ...
if ($server_output == "OK") { ... } else { ... }

Ajax return values

I am trying to figure out how to send back a value to the Ajax popup box. Currently, the value that gets returned is just the JSON that comes back from the API call. I would much rather use jsondecode to pull out a specific value and have that return, or... lets not even get that complex. I just want to set a variable equal to some message such as "API GET complete" and return that to the Ajax box. This will also help with troubleshooting so I can return a variable to see if things are working. As I said, currently the Ajax popup just displays the JSON that comes back from the API call. This is my first time working with both Ajax and curl_setopt so if you can please make recommendations with examples, that would be fantastic! Thank you!
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'auto.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
alert(response);
});
});
});
</script>
</head>
<body>
<input type="submit" class="button" name="test" value="Test" />
</body>
</html>
auto.php
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'Test':
Test();
break;
case 'to_the_n':
to_the_n();
break;
}
}
function Test() {
$ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=MYTAG');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer MYTOKEN','Content-Type: application/json'));
$result = curl_exec($ch);
$message = "Yay it worked" //Send this message back to Ajax popup, not the API reply
exit;
}
?>
* UPDATE *
* UPDATE *
You can just echo the value from php and it will be alerted in the Ajax success function.
echo 'Yay it worked!! ';
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'Test':
if(Test() == true) {
echo('yay it worked!! ');
exit;
}
break;
case 'to_the_n':
to_the_n();
break;
}
}
function Test() {
$ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=MYTAG');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer MYTOKEN','Content-Type: application/json'));
$result = curl_exec($ch);
return true;
}
?>

Trying to Form auto fill by using jquery - ajax and php-curl

I've a php webapp where i can create invoices and add clients. for my own convenience i try to implement a feature that when i type in VAT number of a customer the "other" details (like adres, phone number, company name etc.) should auto-fill, load up.
so to achieve this i've put a fa-search-icon next to vat input bar. Whenever someone fills in the vat number and clicks the search icon, jquery handlers an ajax request to a specific php file where i curl a site with the companies vat number. I'm saving the curled page to a html file (the outputis html). The html file containes needed details like adres, phone number etc.
Update NOTE: the values (phone, adres, name) are in html entities format, for example: & # 75; P & #32; & # 68; eco& # 114;
ive put spaced between &# else the code would auto reform to (when you remove all the spaces)KP Decor, so above in html entities KP Decor is written.
i'm not a really pro in this so my question is actually how can i take those values and pass on to my addclient form.
HTML side:
<div class="col-md-8">
<input type="text" id="btwnr" name="client_tax_number" class="form-control" placeholder="<?php _e('placeholder_tax_number'); ?>" />
</div>
<div class="control-label col-md-1">
<i class="fa fa-search fa-2x" id="btwopvragen"></i>
</div>
jquery part:
<script>
$(document).ready(function(){
$("#btwopvragen").click(function(){
var btwnrVal = $("#btwnr").val();
$.ajax({
type: "GET",
url: "https://www.example.com/FOLDER/FOLDER/btwopvragen.php",
data: {btwnrVal},
success: function() {
$("#bedrijfsnaam").load(
"http://www.domain.eu/map/540806177.html #StatNameLabel");
}
});
});
});
</script>
php part btwopvragen.php:
<?php
$btwnrVal = $_GET['btwnrVal'];
// $btwnrVal = "09999999"; MANUEL TEST
$curlUrl = "https://trendstop.knack.be/nl/detail/".$btwnrVal;
// create curl resource
$ch = curl_init();
//opening text File
$fp = fopen($btwnrVal, "w");
// set url
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_FILE, $fp);
//whether to include the header in the curl, set to false.
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
//save output to File
fwrite($fp, $output);
// close curl resource to free up system resources
curl_close($ch);
//closes the txt File
fclose($fp);
//prints the output
// echo $output;
?>
You need something like the below:
$.ajax({
url:'https://www.example.com/FOLDER/FOLDER/btwopvragen.php',
dataType:'json',
success:function(data) {
$("#btwopvragen").val(data.btw.opvragen);
}
})
This assumes that you have an element with the ID btwopvrageb.
You also don't need type: GET as it's the default.

script not showing any alert

here i am supposed to call a web service in php and the return json of the web service is stored in a variable called $response,then i am passing that json to javascript ,here i am parsing the json and depending on the type of the employee and each type have differebt attributes i am alerting all ,when i have did the same function in another page for testing it was working where i have given value to var txt='' by hardcoding , when i have integrated the php web service with the one i havew tried nothing is having ,i am confused there is no error showing with javascript console.
<?php
session_start();
$regid=$_SESSION['product_registration_id'];
//echo $regid;
$details=array(
'product_registration_id'=> "$regid");
//coverting the vlaues collected from form into json
//calling the web service
$url='webservice url';
$data=$details;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($details));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response= curl_exec($ch);
echo ("The Server Response is:" .$response);
curl_close($ch);
json_decode($response);
$json_a=json_decode($response,true);
echo $json_a[expired];
echo $json_a[account_detail][0];
?>
</div>
<script>
var txt = '<?php echo $response ?>';
alert(txt);
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.type);
if(counter.type=="0")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="1")
{
alert(counter.user_name);
alert(counter.name);
alert(counter.password);
alert(counter.email_id);
}
if(counter.type=="2")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.opr_code);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="3")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.machine_type);
alert(counter.activate_status);
alert(counter.machine_name);
alert(counter.entrance_exit_name);
alert(counter.entrance_or_exit);
alert(counter.loc_name);
alert(counter.activation_code);
}
}
</script>
if you want the php array to be an array in javascript you must:
<?php echo json_encode($response) ?>
this does not need to be parsed in javascript, it will already be an array because the echo will return something in the likings of {'message': 'hellew world'} of ['value1','value2'] which in javascript is an array or an object definition.
So remove the parsing in javascript.
If response contains a quote you will get a js syntax error. Nothing from there on will be processed. So... no alerts. Check the response. Escape the quotes.

Categories