This is my fiddle http://jsfiddle.net/x06Lr919/4/
$.getJSON('http://google.com/search?&q=hi&callback=?',
function(data) {
console.log(data);
$("#target").html(data.contents);
});
I would like to fetch the whole HTML of "http://google.com/search&q=hi" as string of this webpage. I know of this website : www.whateverorigin.org that lets me do it but I don't want to use any other external websites for this purposes.
I know, we have to use JSONP, and hence I've added the callback.
I'm unable to understand the type of data that is returned. Tried JSON.stringify but wasn't helpful.
You could scrape like this:
<?php
function searchGoogle($query, $pages = 1){
$r = array();
for($i=0,$n=0; $i<$pages; $i++,$n+=10){
$doc = new DOMDocument;
#$doc->loadHTMLFile('https://www.google.com/search?q='.urlencode($query)."&start=$n");
$c = $doc->getElementsByTagName('cite');
foreach($c as $e){
if($e->hasAttribute('class') && $e->getAttribute('class') === '_Rm'){
array_push($r, $e->nodeValue);
}
}
}
echo json_encode($r);
}
/* on your JavaScript page
$.post('thisURL.php', {search:'Anything you want to search here.', pages:2}, function(urlsArray){
// handle urlsArray here
});
*/
if(isset($_POST['search'], $_POST['pages'])){
searchGoogle($_POST['search'], $_POST['pages']); // 20 results
}
?>
Related
I have some PHP and JavaScript that works by PHP updating a MySQL database, and then outputting the updated code onto the page without a hard refersh using the JavaScript fetch() method. This code works, and although I understand the fundamentals (and the vast majority) of the code below, there is a part of if it I can't quite get my head around.
a) In this PHP snippet (full code further down) the database is queried and then set as the JSON data type:
header('Content-type: application/json');
$board_row['board_name'];
echo json_encode($board_row);
exit;
It only seems to output $board_row['board_name'] but in the JavaScript code (also shown futher down) both the json.board_name and json.board_id are used to output data onto the page, not just the value from the $board_row['board_name'] value?
b) In the line echo json_encode($board_row); where is this actually echoed? I've only ever used echo to directly output data into a specific HTML element in the past. Is this just echoed in the headers so the JSON can then be accessed in the JavaScript code?
c) When outputting database values in PHP I always wrap them in htmlspecialchars(), the JSON code in this example doesn't seem to be going through an equivalent process for security reasons?
PHP
if (isset($_POST['submit-board-name'])) {
$create_board_name = $_POST['create-board-name'];
try {
// insert into database
$createBoardSQL = "
INSERT INTO boards (board_name, user_id)
VALUES (:board_name, :user_id )
";
$bstmt = $connection->prepare($createBoardSQL);
$bstmt->execute([
':board_name' => $create_board_name,
':user_id' => $db_id
]);
// ----- fetch as JSON
if(isset($_POST['json_response'])) {
$board_stmt = $connection->prepare("
SELECT * FROM `boards` WHERE `user_id` = :user_id
AND `board_name` = :board_name
ORDER BY `board_id` DESC");
$board_stmt -> execute([
':user_id' => $db_id,
':board_name' => $create_board_name
]);
$board_row = $board_stmt->fetch();
header('Content-type: application/json');
$board_row['board_name'];
echo json_encode($board_row);
exit;
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
JavaScript
let boardModuleForm = document.querySelector('.board-module-form');
// URL details
let myURL = new URL(window.location.href),
pagePath = myURL.pathname;
if (boardModuleForm) {
boardModuleForm.addEventListener('submit', function (e) {
if (e.submitter && e.submitter.classList.contains('js-fetch-button')) {
e.preventDefault();
var formData = new FormData(this);
formData.set(e.submitter.name, e.submitter.value);
formData.set('json_response', 'yes');
fetch (pagePath, {
method: 'post',
body: formData
})
.then(function(response) {
if (response.status === 200) {
response.json().then(function(json){
const newBoardName = json.board_name,
boardId = json.board_id;
const newButton = `
<button name="board-name" type="submit">
<span>${newBoardName}</span>
<span style="margin:0" class="add-icon flex">+</span>
</button>
<input class="board-id-value" type="hidden" value="${boardId}">
`
// add new button from above onto page
document.querySelector('.board-list').insertAdjacentHTML('afterbegin', newButton);
});
}
})
.catch(function(error) {
console.error(error);
})
}
})
}
I have about 60 landing pages that use different phone numbers on them. I am using a combination of WordPress and Advanced Custom Fields to place the phone numbers on their respective pages.
I am being asked to show a <div> based on the landing page URL that will not only show the phone number assigned to that page, but, keep showing the <div> (and phone number) regardless of what page the user navigates to on the website.
I have found little to no support on how to make the <div> remain visible throughout the entire session until the user closes the window.
I am thinking that this will somehow revolve around a cookie and Dynamic Number Insertion but I have no real progress to speak of. Should this be done using PHP or JS? Does a plugin exist that would allow for this on WordPress? I'm open to all suggestions.
Please try this code. Like #John C mentioned, WP Engine doesn't recommend Cookie nor PHP Session for the sake of performance and security. This is pure JavaScript code, and I think this will solve your problem.
Code in your Post/Page template file:
<div id="phone-number"></div>
<?php if( get_field('phone_number') ): ?>
<script type="text/javascript">
let phone_number = "<?php the_field('phone_number'); ?>";
</script>
<?php endif; ?>
Code in your theme JavaScript file:
<script type="text/javascript">
// in the case of the div data is persistent on the same site
// let storage = localStorage;
// in the case of the div data is persistent in the same tab, but not in new tab
let storage = sessionStorage;
let key = "phone_number"; // storage key
var global_phone_number = storage.getItem(key);
// check if storage data is set before
if (null === global_phone_number) {
// if not set the data on page into storage
global_phone_number = phone_number ? phone_number : '';
storage.setItem(key, global_phone_number);
}
document.getElementById('phone-number').innerHTML = global_phone_number;
</script>
You should use PHP and capture the session.
(untested code warning)
add_action('wp_footer', 'dynamic_phone_div');
function dynamic_phone_div() {
session_start;
if(isset($_SESSION['phone_div']) ? $phone_div = $_SESSION['phone_div'] :
$phone_div = '';
if($phone_div != '') {
echo '<div class="that_div_thing">';
echo $phone_div;
echo '</div>';
} else {
$_SESSION['phone_div'] = 123456789;
echo '<div class="that_div_thing">';
echo '123456789';
echo '</div>';
}
}
This is only raw logic. I am not sure where your div is (header/footer/page) - depending on where it is you should either use a hook (header/footer) or code it into a template (page/post).
The session will be destroyed after the user closes the tab/window.
I would probably do this with client side session storage. Providing all pages open in the same tab, the value will remain for the session, then be removed.
PHP code (in your functions.php file?) would be something like this:
function phone_script() {
$params = array(
'phone_number' => null, // Insert logic for current number. Can stay null if this is running on a non-landing page
'is_landing_page' => false // Change to true/false based on is current page a landing one or not
);
$params = json_encode( $params );
echo <<< EOT
<script>
let settings = $params;
document.addEventListener("DOMContentLoaded", function() {
if( settings.is_landing_page ) {
window.sessionStorage.setItem( 'phone-number', settings.phone_number );
} else {
settings.phone_number = window.sessionStorage.getItem( 'phone-number' );
}
if( settings.phone_number ) {
let div = document.createElement('div');
div.classList.add('phone-div');
// or add inline style
// div.style.cssText = 'position:fixed'; //etc
// Some logic here to actually add the number and any other content to the div
div.innerHTML = `The Phone number is: ${settings.phone_number}`;
document.body.appendChild(div);
}
});
</script>
EOT;
}
add_action( 'wp_footer', 'phone_script');
Note that the EOT; line MUST have no leading or trailing spaces.
The above is untested.
Hello I am using spout to run some excel reports. I have a user interface where they input date, model, and other information then I do a GET to send it to a php script where I run a query and then put all the results into an excel file like this:
ini_set('max_execution_time', 600); //300 seconds = 5 minutes
require_once 'spout-2.7.2/src/Spout/Autoloader/autoload.php'; // don't forget to change the path!
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
$reportDate=date("Ymd_hhmmss");
$filename="combined_report".$reportDate.".xlsx";
include ("../log/connectionToDb.php");
$conn = connectionSQL();
//provide error if connection fails
if (!$conn) {
echo "An error occurred.\n";
exit;
}
//connected successfully to db. Do not echo anything otherwise it will not show up on dropdown.
else {
//echo "connected";
}
//From date and to date static in case not provided by user
$fromDate = $_GET['convertedFrom'];
$toDate = $_GET['convertedTo'];
$line= $_GET['selectedLine'];
$model_num=$_GET['modelNumber'];
$writer = WriterFactory::create(Type::XLSX);
ob_start();
$writer->openToBrowser($filename);
$sheet = $writer->getCurrentSheet();
$sheet->setName('Production Data');
$rowCount = 2;
$flag=false;
$production = "query";
//echo memory_get_usage() ;
$result1 = sqlsrv_query($conn, $production);
if($result1 === FALSE){
die(print_r(sqlsrv_errors(), TRUE));
}
do{
if(!$flag) {
$headerRow = ['line', 'Work order','Model number', 'Revision','Serial number','Lpn','Date created','Date completed'];
$writer->addRow($headerRow);
$flag = true;
}
else{
$reportRow = [$row['line'], $row['work_order'], $row['model_num'], $row['revision'],$row['serial_num'],$row['LPN'],$row['date_created'],$row['date_completed']];
$writer->addRow($reportRow);
$rowCount++;
}
}
while ($row = sqlsrv_fetch_array($result1));
$writer->close();
$xlsData = ob_get_contents();
ob_clean();
$response = array(
'op' => 'ok',
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($xlsData)
);
}
die(json_encode($response));
Then on the AJAX call I have the following:
$.ajax({
url: 'modelData/excel-export.php',
method: "GET",
data: {'modelNumber':modelNumber,'convertedFrom':converted_from_UTC,'convertedTo':converted_to_UTC,'selectedLine':selectedLine},
dataType:'json',
success: function(fileCreated){
}
}).done(function(data){
console.log(local);
var $a = $("<a>");
$a.attr("href",data.file);
$("body").append($a);
$a.attr("download","combined_report_"+local+".xlsx");
$a[0].click();
$a.remove();
});
now if I run this in Firefox everything works I am able to download up to 4 months of data which is >60,000 records this has no problem. If I run this in google chrome I cannot download more than 1 week about 20,000 records and U get a "download failed -network error" I was using PHPExcel but then found out it didn't support too many records so I switched to spout but I find the same issue only in google chrome but I don't understand where this limitation is coming from. I have read multiple posts and I have tried setting headers, lengths etc but nothing has worked also I chatted with a spout forum and they said none of the headers were necessary but they were still unable to help me.
I think this question Download failed - network error in google chrome but working in firefox may be going close to the same direction as my issue.
Also I have tried running incognito mode chrome I have tried disabling all extensions
As a side note...The firefox download appears to work fine but we don't "support" firefox so it would be hard for customers to go to multiple browsers specially when they're not tech savy
Any help will be greatly appreciated! :)
I was able to solve this issue by doing the following:
JS
window.open("modelData/excel-export.php?modelNumber="+modelNumber+"&convertedFrom="+converted_from_UTC+"&convertedTo="+converted_to_UTC+"&selectedLine="+selectedLine,
'_blank'// <- This is what makes it open in a new window.
);
then on the PHP side:
ini_set('max_execution_time', 600); //300 seconds = 5 minutes
require_once 'spout-2.7.2/src/Spout/Autoloader/autoload.php'; // don't forget to change the path!
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
$reportDate=date("Ymd_hhmmss");
$filename="combined_report".$reportDate.".xlsx";
include ("../log/connectionToDb.php");
$conn = connectionSQL();
//provide error if connection fails
if (!$conn) {
echo "An error occurred.\n";
exit;
}
//connected successfully to db. Do not echo anything otherwise it will not show up on dropdown.
else {
//echo "connected";
}
//From date and to date static in case not provided by user
$fromDate = $_GET['convertedFrom'];
$toDate = $_GET['convertedTo'];
$line= $_GET['selectedLine'];
$model_num=$_GET['modelNumber'];
$writer = WriterFactory::create(Type::XLSX);
$writer->openToBrowser($filename);
$sheet = $writer->getCurrentSheet();
$sheet->setName('Production Data');
$rowCount = 2;
$flag=false;
$production = "query";
//echo memory_get_usage() ;
$result1 = sqlsrv_query($conn, $production);
if($result1 === FALSE){
die(print_r(sqlsrv_errors(), TRUE));
}
do{
if(!$flag) {
$headerRow = ['line', 'Work order','Model number', 'Revision','Serial number','Lpn','Date created','Date completed'];
$writer->addRow($headerRow);
$flag = true;
}
else{
$reportRow = [$row['line'], $row['work_order'], $row['model_num'], $row['revision'],$row['serial_num'],$row['LPN'],$row['date_created'],$row['date_completed']];
$writer->addRow($reportRow);
$rowCount++;
}
}
while ($row = sqlsrv_fetch_array($result1));
$writer->close();
The library I am using just doesn't work very well with AJAX so this approach solved my issue. Thanks for all the help :)
I used Blob Javascript for the same problem.
this link maybe help someone :
Blob
I'm trying to add ajax autosave to my settings page in plugin and made this code:
<?php
function cfgeo_settings_javascript() { ?>
<script type="text/javascript" >
(function($){
$(document).ready(function(){
$("input[id^='cf_geo_'], select[id^='cf_geo_'], textarea[id^='cf_geo_']").on("change keyup", function(){
var This = $(this),
name = This.attr("name"),
value = This.val(),
data = {};
data['action'] = 'cfgeo_settings';
data[name] = value;
console.log(data);
console.log(ajaxurl);
$.post(ajaxurl, data).done(function(returns){
console.log(returns);
});
});
});
}(window.jQuery));
</script> <?php
}
add_action( 'admin_footer', 'cfgeo_settings_javascript');
function cfgeo_settings_callback() {
global $wpdb; // this is how you get access to the database
var_dump($_POST);
if (isset($_POST)) {
// Do the saving
$front_page_elements = array();
$updates=array();
foreach($_POST as $key=>$val){
if($key != 'cfgeo_settings')
update_option($key, esc_attr($val));
}
echo 'true';
}
else
echo 'false';
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_cfgeo_settings', 'cfgeo_settings_callback');
?>
I find problem that everytime I want to send this simple ajax request I get 0 what is realy enoying.
Here is Console Log when I try to made some change in select option box:
Object {action: "cfgeo_settings", cf_geo_enable_ssl: "true"}
admin.php?page=cf-geoplugin-settings:1733 /wp-admin/admin-ajax.php
admin.php?page=cf-geoplugin-settings:1736 0
What's wrong in my ajax call or PHP script?
I need to mention that both codes are in the one PHP file.
You should have to follow guideline of WordPress ajax method by this admin ajax reference. Please follow this.
https://codex.wordpress.org/AJAX_in_Plugins
Here is a working example with notes included in the comments, there are a lot of don't does in your code and this example addresses those concerns in the code comments.
https://gist.github.com/topdown/23070e48bfed00640bd190edaf6662dc
Not sure if this is possible but here goes, I have a basic PDO query that stores the results in a array.
<?php
// configuration
$dbtype = "";
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$title = 'PHP AJAX';
// query
$sql = "SELECT * FROM thankyou";
$q = $conn->prepare($sql);
$q->execute(array($title));
$q->setFetchMode(PDO::FETCH_BOTH);
// fetch
while($r = $q->fetch()){
echo"<br>";
print_r ($r);
}
?>
Now the bit I can't get my head around, I have also never used JavaScript. Can I rotate through the results to show one at a time for 5-10 seconds then show another? It can be random or in order, I'm not fussed. I found this, which works, but can't figure out how to get the array into it. I am aware one is client side and one is server side.
<script type="text/javascript">
var rotatingTextElement;
var rotatingText = new Array();
var ctr = 0;
function initRotateText() {
rotatingTextElement = document.getElementById("textToChange");
rotatingText[0] = rotatingTextElement.innerHTML; // store the content that's already on the page
rotatingText[1] = "need to write PDO array here";
setInterval(rotateText, 5000);
}
function rotateText() {
ctr++;
if(ctr >= rotatingText.length) {
ctr = 0;
}
rotatingTextElement.innerHTML = rotatingText[ctr];
}
window.onload = initRotateText;
</script>
and this is were the results are shown
<span id="textToChange">this is were the result is displayed</span>
If I need to do it a totally different way, it's not a problem if someone can point me in the correct direction.
If you're not so familiar with JavaScript, I also suggest using some JS library for the task. In fact, Prototype.js has a class exactly for this purpose: http://prototypejs.org/doc/latest/ajax/Ajax/PeriodicalUpdater/index.html
A working example: http://www.tutorialspoint.com/prototype/prototype_ajax_periodicalupdater.htm
i decided to use AJAX to call a seprate PHP page in the end and works fine this is the updated page.
<script type="text/javascript">
$(function() {
getStatus();
});
function getStatus() {
$('div#status').load('thankyou.php')//Thankyou being the page the query is on
setTimeout("getStatus()",5000);//refreshes every 5 seconds
}
</script>
The query itself is a standard PDO
$query = $db->query("SELECT * FROM `thankyou` ORDER BY RAND() LIMIT 1
Thanks for the pointers all.