Why is my instant search not working? - javascript

onlythebestoftheweb.x10.mx/test search/search.html Whats wrong with the code? Try typing anything in there without clicking enter. It used to work... I dont know what the issues are on line 3 and 31. Heres links.xml and livesearch.php
onlythebestoftheweb.x10.mx/test search/links.xml
onlythebestoftheweb.x10.mx/test search/livesearch.php
Php code
<?php
$xmlDoc=new DOMDocument();
$xmlDoc->load("links.xml");
$x=$xmlDoc->getElementsByTagName('link');
//get the q parameter from URL
$q=$_GET["q"];
//lookup all links from the xml file if length of q>0
if (strlen($q)>0)
{
$hint="";
for($i=0; $i<($x->length); $i++)
{
$y=$x->item($i)->getElementsByTagName('title');
$z=$x->item($i)->getElementsByTagName('url');
if ($y->item(0)->nodeType==1)
{
//find a link matching the search text
if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q))
{
if ($hint=="")
{
$hint="<a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
else
{
$hint=$hint . "<br /><a href='" .
$z->item(0)->childNodes->item(0)->nodeValue .
"' target='_blank'>" .
$y->item(0)->childNodes->item(0)->nodeValue . "</a>";
}
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint=="")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>

You're missing an opening <link> tag between lines 27 and 28 of links.xml.
Chrome provides a helpful error for me if I go to: http://onlythebestoftheweb.x10.mx/test%20search/links.xml

Related

AJAX won't call the PHP file when using $.post()

I have been trying to export a search result to an Excel file (type .xls), before this, I have been using purely PHP and it works.
However, my client requests to have "live search" effect, so I have to shift to AJAX.
Here is the starting point: User clicks "Export" button, and in the javascript (in the main php file viewdata.php):
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js'></script>
....
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$.post("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
cbXDate is an input field of type date to let user choose a date from whence to export the data, and cbsearch is a text input field to include a search keyword. console commands are added to see where the code execution has went through.
in the export_contact.php:
<?php
echo '<script> console.log("Export PHP activated."); </script>';
?>
I removed the PHP MySQL data selection code just to debug the problem (full source code below).
Problem is: export_contacts.php is never called. The "Export PHP activated" message never popped up in the console. The console only displayed the data values and "Completed", i.e. export_contacts.php was never called.
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Complete
Out of curiosity, I replaced $.post(...) with $("#export_div").load(...) and the console message showed up:
$(document).ready(function () {
var guid = <?php echo $guid ?>;
var date = document.getElementById("cbXDate").value;
var key = document.getElementById("cbsearch").value;
console.log("GUID: '" + guid + "', Date: '" + date + "' Key: '" + key + "'");
$("#export_div").load("export_contacts.php",
{ sGuid: guid, sDate: date, sKey: key },
function () { console.log("Complete"); } );
});
Output:
GUID: '0001', Date: '2021-08-01' Key: 'Jo'
Export PHP activated.
Complete
But this is not what I want, I want to write the output to a file, not display them in a div in the webpage. However, the data shown in the "export_div" div is correct, but the header part is not running, I know the quirkyness in header() calls, but I didn't output anything before the header() calls (unless output from the calling viewdata.php file also count?), here is the full export_contacts.php source code:
<?php
include("./php/auth.php");
$guid = $_POST['sGuid'];
$date = $_POST['sDate'];
$skey = $_POST['sKey'];
$searchKey = $_POST['sKey'];
if($searchKey == "")
{
$skey = "'%'";
}
else
{
$skey = "'%".$searchKey."%'";
}
$sql = "SELECT *, FROM_UNIXTIME(ROUND((date / 1000), 0) + 46800) AS date
FROM contacts
WHERE owner = '$guid' AND contact <> ''
AND (contact LIKE $skey OR name LIKE $skey) ";
if(!empty($date))
{
"AND date >= '$date' ";
}
$sql .= "ORDER BY contact;";
if($result = mysqli_query($link, $sql))
{
$columnHeader = '';
$columnHeader = "Owner" . "\t" . "Contact" . "\t" . "Name" . "\t" . "SaveDate" . "\t";
$setData = '';
while($rows = mysqli_fetch_assoc($result))
{
$rowData = '';
foreach ($rows as $value)
{
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
// in case of .load() used,
// code works up until this point
// code doesn't work since here...
header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=contact_".$guid.".xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
// until here
// this will show in console in case of .load() used
echo '<script> console.log("Export PHP activated."); </script>';
die();
}
else
{
echo "<script>window.alert('ERROR: '".mysqli_error($link).")</script>";
}
include("./php/cleanup.php");
?>
This code is working in the pure PHP version. I don't know why this header() part isn't working in here, could be due to its output got redirected to the div?
To make things clear, my question is: "Why $.post(...) isn't calling the PHP file, while $("#export_div").load(...) did?".
The header() part is just a sub question, and is fine if it's ignored.
As Kmoser pointed out, I was doing things wrong. None of the tutorial sites I visited did mention that $.post() will not return any result at all, while my php code is expecting the return of the search result and write them in a file in the header() calls.

Comma doesn't separate parameters

Trying to set up a WhatsApp button with a custom message, I've created a script in JavaScript to do that and calling it onclick.
I've tried moving quotation marks around but nothing works, this might be a silly issue but I just started with coding and can't get this to work, been trying since yesterday.
Here is my JavaScript code:
function sendSms(number, title) {
window.open('https://api.whatsapp.com/send?phone=' + number + '&text=' + 'hello' + title);
}
Here is my PHP code:
echo '<span class="ad-whatsapp" onclick="sendSms(\' '. $ad_wa .' , '. str_replace(" ", "%20", get_the_title()) . '\')"></span>';
It seems to be sending the whole content of the parenthesis as the number parameter instead of separating the 2.
function sendSms(number, title) {
window.open('https://api.whatsapp.com/send?phone=' + number + '&text=' + 'hello' + title);
}
echo '<span class="ad-whatsapp" onclick="sendSms(\' '. $ad_wa .'\' , \''. str_replace(" ", "%20", get_the_title()) . '\')">bb</span>';
Try using this JavaScript:
function sendSms(number, title) {
window.open(`https://api.whatsapp.com/send?phone=${number}&text=hello${title}`);
}
With this PHP:
<?php
$replaced = str_replace(" ", "%20", get_the_title());
echo '<span class="ad-whatsapp" onclick="sendSms(\'' . $ad_wa . '\', \'' . $replaced . '\')">SEND</span>';
?>
Good luck.
Try using this instead:
echo "<span class='ad-whatsapp' onclick=\"sendSms('".$ad_wa."' , '".str_replace(" ", "%20", $this->get_the_title())."')\">asdf</span>";

Iterating over different divs in Javascript and passing arguments to a script

Background
I am using PHP to created a list of voting sections. Each section is the same except for a unique number, which increases by 1 each time the PHP loops.
I use the PHP variable $n as a counter, and place that in the id attributes in several places in each section.
Current PHP/HTML:
echo "<div id='votesection'>";
echo "<h3 id='rating " . $n . "' style='display:block;'>" .
echo "<h3 id='ratingup " . $n . "' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 id='ratingdown " . $n . "' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote($n)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote($n)'></div>";
echo "</div>";
Goal
When a user clicks on an arrow down or arrow up, certain divs are hidden or displayed. Example, when the up arrow in my second section is clicked, my <h3 id='ratingup2'></h3> would change to visible.
Current JS
function upvote() {
// Script to hide rating, and rating down and display:block ratingup
// Will also need to execture php sql query to increment event rating by one for event by one
}
function downvote(){
// Same script but to show rating down and decrement rating
}
Should I pass every rating id to the script or is there an easier way to do this that I'm missing?
Passing the ID is the easiest way to do it with plain Javascript.
function upvote(n) {
document.getElementById('ratingup ' + n).style.display="block";
document.getElementById('ratingdown ' + n).style.display="none";
}
function downvote(n) {
document.getElementById('ratingup ' + n).style.display="none";
document.getElementById('ratingdown ' + n).style.display="block";
}
A way to do it without passing the ID would be to put classes on the rating DIVs, and pass this instead.
HTML:
echo "<div id='votesection'>";
echo "<h3 id='rating " . $n . "' style='display:block;'>" .
echo "<h3 class='ratingup' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 class='ratingdown' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote(this)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote(this)'></div>";
JS:
function upvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "block";
parent.querySelector(".ratingdown").style.display = "none";
}
function downvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "none";
parent.querySelector(".ratingdown").style.display = "block";
}
You can create only one wrapper with the id votesection_id and then do everything else with js/ajax
echo "<div id='votesection_" . $n . "'>";
echo "<h3 id='rating' style='display:block;'>" .
echo "<h3 id='ratingup' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 id='ratingdown' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote($n)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote($n)'></div>";
echo "</div>";
<script>
function upvote(id){
// 1. Go To the server with ajax do your stuff 2. return the current upvotes 3.replace the upvotes h3 text
}
function downvote(id){
// 1. Go To the server with ajax do your stuff 2. return the current downvotes 3.replace the downvotes h3 text
}
</script>
As #idioteque says in their comment, spaces in element IDs are not allowed. The best way to get this information into the document is probably with data attributes.
Also, multiple elements with the same id are not allowed, what you probably need in this case are classes. (I'm assuming this chunk of HTML will be repeated multiple times per page.)
Borrowing #Barmar's idea of passing this into the event handler, here's how I'd change the server code:
echo "<div class='votesection' data-rating-id=" . $n . ">";
echo "<h3 class='rating' style='display:block;'>" .
echo "<h3 class='ratingup' style='display:none;'>" . $ratingup . "</h3>\r\n";
echo "<h3 class='ratingdown' style='display:none;'>" . $ratingdown . "</h3>\r\n";
echo "<div class='arrow-down' onclick='downvote(this)'></div>\r\n";
echo "<div class='arrow-up' onclick='upvote(this)'></div>";
echo "</div>";
And the JS:
function upvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "block";
parent.querySelector(".ratingdown").style.display = "none";
var id = parent.dataset.ratingId;
// do your AJAX or whatever with id
}
function downvote(self) {
var parent = self.parentNode;
parent.querySelector(".ratingup").style.display = "none";
parent.querySelector(".ratingdown").style.display = "block";
var id = parent.dataset.ratingId;
// do your AJAX or whatever with id
}

Dynamically Adding Content to Text Fields Using Javascript

So here is my problem. I have the below set of javascript code and HTML.
What is supposed to happen is that as you click on various checkboxes in a form, the script is supposed to take the Value of the Checkbox you checked and fill in a text field below that has a similar "name" identifier. The below code works for all values but one. The one with a space in the value "Character Only" doesn't work. I tried to use the Javascript method .Replace(" ", "-") to accomplish replacing the space with a hyphen but it doesn't seem to work. Since the HTML is being dynamically created via a PHP loop, I can't just add in the needed values and hard code everything.
Is there a way to make
JSFiddle - The full program and HTML layout.
The Javascript (Click the JSFiddle link to see the entire result)
function autofill(ElementName) {
//window.alert('You got this: ' + ElementName);
if(document.getElementById('keyword-' + ElementName.toLowerCase()).checked == true) {
document.getElementById('keyword-entry-' + ElementName.toLowerCase()).value = document.getElementById('keyword-' + ElementName.toLowerCase()).value;
} else {
document.getElementById('keyword-entry-' + ElementName.toLowerCase()).value = '';
}
}
// window.alert('This value is: ' + document.getElementById('keyword-ally').value.toLowerCase() );
//--> </script>
The PHP being used to create the HTML elements for the above JScript
<?php
$keywords = array("Ally" , "Breaker" , "Character Only" , "Combo" , "Desperation" , "Item" , "Kick" , "Multiple" , "Powerful" , "Punch" , "Ranged" , "Reversal" , "Stance" , "Stun" , "Taunt" , "Terrain" , "Throw" , "Unique" , "Weapon");
$i =0;
foreach($keywords as $keyword_name) {
echo '<td style="width: 20%;">' . zen_draw_checkbox_field('ufs_keywords[]', $keyword_name, in_array($keyword_name, $pInfo->resources), '', 'id="keyword-' . str_replace(" ","-",strtolower($keyword_name)) . '"') . ' <label for="keyword-' . str_replace(" ","-",strtolower($keyword_name)) .'">' . $keyword_name . "</label><br />" . zen_draw_input_field('ufs_keywords_entry[]', '', 'id="keyword-entry-' . str_replace(" ","_",strtolower($keyword_name)) . '" style="width:100px; float: right;"') . "</td>" . "\n\n";
$i++;
echo ($i % 5 == 0 ? "</tr>\n\n<tr>" : "");
}
?>

Google Maps API - storing image URL and calling it

I've added an image URL to an entry in the mySQL database, and I want it do be displayed in the information window on my sidebar.
Here's what the part I'm fiddling around with:
downloadUrl("genxml.php", function(data) {
var xml = data.responseXML;
var locations = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < locations.length; i++) {
var name = locations[i].getAttribute("name");
var address = locations[i].getAttribute("address");
var type = locations[i].getAttribute("type");
var price = locations[i].getAttribute("price");
var img = locations[i].getAttribute("img");
var point = new google.maps.LatLng(
parseFloat(locations[i].getAttribute("lat")),
parseFloat(locations[i].getAttribute("lng")));
var html = "<div class=loc-img><img src=" + img + "/></div><div class=loc-name>" + name + "</div> <br/>" + address + "<br/>" + "<div class=loc-type>" + type + "</div><div id=loc-price>Price Rating:" + price + "</div>";
The bit at the bottom looks right to me, so I can't work out what's wrong.
The image is saved on the server, and the URL has been added to the img field of the entry, and there are no spelling errors. When the page loads, and the info window loads, this shows in the Inspector.
<img src="null/">
Here are the details of the column from phpMyAdmin, whcih I think could be causing the problem. varchar(120) latin1_swedish_ci, Null is set to no. I assumed that because it was a URL, varchar would be the appropriate choice.
Any thoughts?
EDIT: I am also having a similar issues with another field. I think it might be related. There's a 'price' field, set to int(5), and is simply a rating of 1 to 5. However, when the info window displays, it just says 'null'
I've actually managed to work out the problem.
Rather simple, yet easily overlooked!
When adding new fields to each item, you need to remember to register them in the XML converter that pulls the information from the database, and then converts it to a Maps-readable format (XML).
In my case, I had to go into genxml.php (as directed by the Maps documentation), and make it look like this:
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'type="' . $row['type'] . '" ';
echo 'price="' . $row['price'] . '" ';
echo 'img="' . $row['img'] . '" ';
echo '/>';
}
Hope that helps someone else!

Categories

Resources