PHP function ignoring an if statement - javascript

Due to one agent wanting his website url on the functionality that I worked on a month ago I ended up having to make some minor changes. I have two function PHP pages that run a very similar script but I had to make two based of two value sets. What they echo onto the page with AJAX is exactly the same and this is where it gets a little weird...
The first script I did was successful but I needed to make a if elseif else statement so everyone agent didn't have a link that went no where. After fiddling around with this statement I was able to get just the one agent to have his website URL on there. Once I had that done I was under the impression that it would be smoothing sailing from there..it was not...
I used the exact same statement for both of their scripts and only one works. The only thing that differs from them is what value it is receiving and that I use JavaScript + AJAX for the first one (Which works) and then decided to learn jQuery + AJAX to do the next one. Before this they all worked and it is the exact code for both besides the use of JavaScript/jQuery (which is the same language) and one uses GET while the other uses POST
I also get no errors or anything while the function is running. The agent's name is Sam Fiorentino that is the only one with a website url. I went into the console for the second search, the radio buttons, and it shows the company name outside of the anchor tag which is the root of the problem. Why would one display it correctly while the other doesn't?
First PHP (Works)
while ($stmt->fetch()) { // Gets results from the database
echo "<div class='agentcon'>" . "<span class='agentn'>" . "<strong>". $First_Name . " " . $Last_Name . " " . $Suffix . "</strong>" . "</span>" . "" . "<span class='email'>" . "Send an e-mail to" . " " . $First_Name . "</span>" . "" ."<div class='floathr'></div>";
if ($Company == NULL) {
echo "<p>";
}
elseif ($Website == NULL) {
echo "<p>" . "<strong>" .$Company . "</strong>" . "<br>";
}
else {
echo "<p>" . "<strong>" . "<a target='blank' href=" .$Website . ">" .$Company . "</a>" . "</strong>" . "<br>";
}
Second PHP (Doesn't Work)
while ($stmt->fetch()) { // Gets results from the database
echo "<div class='agentcon'>" . "<span class='agentn'>" . "<strong>".$First_Name . " " .$Last_Name . " " . $Suffix . "</strong>" . "</span>" . "" . "<span class='email'>" . "Send an e-mail to" . " " .$First_Name . "</span>" . "" ."<div class='floathr'></div>";
if ($Company == NULL) {
echo "<p>";
}
elseif ($Website == NULL) {
echo "<p>" . "<strong>" .$Company . "</strong>" . "<br>";
}
else {
echo "<p>" . "<strong>" . "<a target='blank' href=" .$Website . ">" .$Company . "</a>" . "</strong>" . "<br>";
}
SQL + Binded code (First/Working one)
$sql="SELECT First_Name, Last_Name, Suffix, Email, Company, WorkAddress1, WorkCity, WorkStateProvince, WorkZipCode, Work_Phone, Fax, Ancillary, SmallGroup, IndividualPlans, LongTermCare, Medicare, LargeGroup, TPASelfInsured, CertifiedForPPACA, Website FROM `roster` WHERE Last_Name = '".$q."' OR Company = '".$q."' OR WorkCity = '".$q."' OR WorkZipCode = '".$q."' ORDER BY Last_Name ASC";
if(!$stmt = $con->Prepare($sql))
{
die;
}else{
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($First_Name, $Last_Name, $Suffix, $Email, $Company, $WorkAddress1, $WorkCity, $WorkStateProvince, $WorkZipCode, $Work_Phone, $Fax, $Ancillary, $SmallGroup, $IndividualPlans, $LongTermCare, $Medicare, $LargeGroup, $TPASelfInsured, $CertifiedForPPACA, $Website);
$rows = $stmt->num_rows;
SQL + Binded code (Not working one)
$poststr = $_POST['expertise']; //get our post data
if(count($poststr) > 1){ //count to make sure we have an array
$expertise = implode(" AND ",$_POST['expertise']); //implode the array using AND as glue
}
else{ //otherwise if it is only one no need for implode
$expertise = implode("",array($poststr));
}
//here is our string for prepared statement
$sql = "SELECT First_Name, Last_Name, Suffix, Email, Company, WorkAddress1, WorkCity, WorkStateProvince, WorkZipCode, Work_Phone, Fax, Ancillary, SmallGroup, IndividualPlans, LongTermCare, Medicare, LargeGroup, TPASelfInsured, CertifiedForPPACA, Website FROM roster WHERE ".$expertise." = 1 ORDER BY Last_Name ASC";
if(!$stmt = $con->Prepare($sql))
{
die;
}else{
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($First_Name, $Last_Name, $Suffix, $Email, $Company, $WorkAddress1, $WorkCity, $WorkStateProvince, $WorkZipCode, $Work_Phone, $Fax, $Ancillary, $SmallGroup, $IndividualPlans, $LongTermCare, $Medicare, $LargeGroup, $TPASelfInsured, $CertifiedForPPACA, $Website);
$rows = $stmt->num_rows;
Javascript + AJAX (First one/Working one)
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("bodyA").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("bodyA").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","process.php?q="+str,true);
xmlhttp.send();
}
</script>
jQuery + AJAX (Second one/Not working)
$('input').on('click', function() { //Pulls data based on radial input
var value = $(this).val();
$.ajax({
type: 'POST',
datatype: "html",
data: {
expertise: value
},
url: "expertise.php",
success: function (data) {
$('#bodyA').html(data);
}
});
});
Any idea?
Live Site

"<a target='blank' href=" .$Website . ">"
This is your problem: You do not have quotes around your url. It outputs like this:
<a href=http://whatever.com/path>Company</a>
You need to add quotes like this:
"<a target='blank' href='" .$Website . "'>"
The url looks like this!
<a target='blank' href=http://www.samfiorentino.com/>Sam Fiorentino & Associates</a>
It needs quotes. The ending / in the URL is ending the <a>.
The reason why the first one works but the second one doesn't:
innerHTML lets the browser interpret the html.
$(...) is interpreted by jQuery, which does some fancy things for browser compatibility, but sometimes has drawbacks. Some browsers attempt to fix bad markup, and sometimes the browser does a bad job of it. jQuery makes them all mostly act the same.
See this jsfiddle for comparison: http://jsfiddle.net/Rk7SQ/
<p>Browser rendering:</p>
<p><a target='blank' href=http://www.samfiorentino.com/>Sam Fiorentino & Associates</a></p>
<p>jQuery rendering:</p>
<p id="jqrender"></p>
$(function() {
$('#jqrender').html("<a target='blank' href=http://www.samfiorentino.com/>Sam Fiorentino & Associates</a>");
});
You can see that they are different.

Related

Passing value to other page by clicking a list item

I am new at web programming and JavaScript.
I have a model page that show all the details of a request let 's say. And Before that page, what the user sees is a list with all the requests he have made. The this is, I want somehow to passe the ID of that clicked request, save it somewhere and pass to the other page and in there, by ID e shows all the details of that previously clicked request.
Here is my code:
<div class="list-group">
<?php
$id_utilizador = $_SESSION["id_utilizador"];
if(isset($_POST["por_aprovar"])){
$url = "http://localhost/myslim_aluguer_viaturas/api/requisicoes/fase1/" . $id_utilizador;
$json = file_get_contents($url);
$obj = json_decode($json);
if($obj->status == true){
$array = $obj->data;
foreach($array as $requisicao){
echo "<a href='requisicao.php' name = 'requisicao" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
}
} else {
echo "Não existem resultados a apresentar.";
}
?>
I don 't know what to do. thank you for your time!!!
What you are looking for is a url query string aka get parameters. In your code change this:
echo "<a href='requisicao.php' name = 'requisicao" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
To this:
echo "<a href='requisicao.php?theid=" . $requisicao->requisicao->id . "' class='list-group-item'>" . $requisicao->nome_condutor . " | " . $requisicao->requisicao->deslocacao . " | " . $requisicao->descricao_viatura . " | " . $requisicao->requisicao->data_requisicao . "</a>";
And on requisicao.php you will obtain the value using php's super global variable $_GET[] which will be something like this:
if(isset($_GET['theid']) && $_GET['theid'] != ''){
$the_id = $_GET['theid'];
// do stuff with $the_id;
}
You can pass multiple values by adding additional parameters:
requisicao.php?theid=22&anothervar=something&var3=33
Also keep in mind the security implications when passing variables via query string parameters as users will be able to easily manipulate these variables, and they will be saved in access logs. Your application should have the logic to sanitize and insure that the values passed are valid.

Alert box not showing when action from php js php

I have a problem in showing the alert box. This code for the rating star.
rating.js
$(document).ready(function(){
$('.post li').mouseout(function(){
$(this).siblings().andSelf().removeClass('selected highlight')
}).mouseover(function(){
$(this).siblings().andSelf().removeClass('selected');
$(this).prevAll().andSelf().addClass('highlight');
})
$('.post li').click(function(){
$(this).prevAll().andSelf().addClass('selected');
var parent = $(this).parent();
var oldrate = $('li.selected:last', parent).index();
parent.data('rating',(oldrate+1))
data = new Object();
data.id = parent.data('id');
data.rating = parent.data('rating')
$.ajax({
url: "add_rating.php",// path of the file
data: data,
type: "POST",
success: function(data) {
}
});
})
/* reset rating */
jQuery('.post ul').mouseout(function(){
var rating = $(this).data('rating');
if( rating > 0) {
$('li:lt('+rating+')',this).addClass('selected');
}
})
})
add_rating.php
<?php
include("dbconnection.php");
session_start();
$myid = $_SESSION['id'];
// echo "".$myid;
$sql_notification ="SELECT * FROM table_user_skills where user_id='$myid' and rating=5";
$result = $conn->query($sql_notification);
$count = 0;
while ($row=$result->fetch_assoc()) {
if ($row['rating']==5) {
$count = $count +1;
}
}
// echo "Count: ".$count;
if(!empty($_POST["rating"]) && !empty($_POST["id"])) {
$myrate=$_POST["rating"];
if($count<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Less than 5");';
print '</script>';
} else if($myrate<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Rate Less than 5");';
print '</script>';
}else if($count>5){
print '<script type="text/javascript">';
print 'alert("Lpas 5 stars");';
print '</script>';
}
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE skills_id='" . $_POST["skills_id"] . "'";
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE user_id='" . $_POST["userid"] . "' and skills_id='" . $_POST["id"] . "' and category_id='" . $_POST["category"] . "'";
}
?>
My problem is that the alert box is not showing. I have to limit the number of 5 stars being updated. If anyone could help me figure out what's wrong with my code, I would appreciate it.
Look at the success callback function for your AJAX call - it's empty. You're having PHP print out the alert box code in the ajax call and then never doing anything with that output.
To make the alert show up, you would have to append the code your AJAX call returns to the DOM. However, it would probably be better to just return just the message and let the JavaScript code take care of raising the alert box. Just a simple alert(data) should do the trick.

Javascript: function doScan(code) links to php file for searching to mysql

I'm a newbie on php, javascript and ajax. I got this tutorial about How to Create a Search Feature with PHP and MySQL and it was a success after creating it.
Link: http://www.webreference.com/programming/php/search/index.html
Now I'm changing the index.html file and linked only to search_display.php file for just a simple price checker program. I was confuse on how to link the "code" result under Javascript function doScan(code) to search_display.php.
<script>
function doScan(code) //displays the value target after scanning.
{
divStatus.innerHTML = 'Scanned Code:<br> ' + code;
setTimeout("startScanner()", 1250);
}
</script>
I wanted to link "code" to search_display.php and this is the code:
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
//if(preg_match("/^[a-zA-Z]+/", $_POST['name'])){
$name=$_POST['name'];
//connect to the database
$db=mysql_connect("localhost", "root", "bbp0m") or die ('I cannot connect to the database because: ' . mysql_error());
//var_dump($db);
//-select the database to use
$mydb=mysql_select_db("price_checker");
//var_dump($mydb);
//-query the database table
$sql="SELECT * FROM stock_master WHERE gtin LIKE '%" . #$name . "%'";
//var_dump($sql);
//-run the query against the mysql query function
$result=mysql_query($sql);
//var_dump($result);
//-create while loop and loop through result set
while($row=mysql_fetch_array($result)){
$itemcode=$row['itemcode'];
$desc1=$row['desc1'];
$desc2=$row['desc2'];
$uom=$row['uom'];
$gtin=$row['gtin'];
$retailprice=$row['retailprice'];
//-display the result of the array
echo "<ul>\n";
echo "<li>" . "" .$itemcode . " " . $desc1 . " " . $desc2 . " " . $uom . " " . $gtin . " " . $retailprice . "</li>\n";
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
//}
?>
Any ideas how to link it and if possible I would like to put everything into index.html?
Bert

Running php from user onclick

I'm not sure how well i'll be able to explain this, but here goes.
I have a website for attractions. Let's say that one of my categories is Historical villages.
When the user opens the Historical villages page he gets a list of villages displayed from the database. The way I display them is: Name plus a picture of the attraction.
What I want to do is unable the user to click on of the villages (by making the name and picture a clickable link) and the user to be redirected to a page that will run a php script that will display more information from the database about the selected village. That way I will only have one page for all attractions that will display different information every time a user selects something different, instead of hardcoding all the pages.
This is my code displaying the lits of villages:
$sql = "SELECT `Name`, `Location`, `Description`, `Airport`, `imglink`, `pagelink` "
. "FROM `attractions` "
. "WHERE `Category`='HistV'";
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['Name'];
echo "<img src='" . $row['imglink'] . "'>";
}
Do any of you have any suggestions on how to make this output a link and the make it run the PHP to show the users selection?
Your while condition changed to like this,
while ($row = mysql_fetch_assoc($result)) {
/* For example ,
$row['pagelink'] must contains the pagelink as belowed here
/viewVillage.php?village_id=1
/viewVillage.php?village_id=2 and so on. */
echo "<a href='" . $row['pagelink'] . "'>"
. $row['Name'] .
. "<img src='" . $row['imglink'] . "'>
</a>";
}
This will generate your list of villages like this,
<a href="/viewVillage.php?village_id=1">
Village name 1
Village Image 1
</a>
<a href="/viewVillage.php?village_id=2">
Village name 2
Village Image 2
</a>
<a href="/viewVillage.php?village_id=3">
Village name 3
Village Image 3
</a>
.....
When you click on any of the link, it will redirected to viewVillage.php page. Now you can get the particular village using $_GET['village_id']
viewVillage.php
if(isset($_GET['village_id']]) && $_SERVER['REQUEST_METHOD'] == 'GET' ) {
$villageId = $_GET['village_id'];
// Then do your stuff over here
}
On your current page
while ($row = mysql_fetch_assoc($result)) {
/* For example ,
$row['pagelink'] should be a village id */
echo "<a href='/attractions.php?village=" . $row['pagelink'] . "'>"
. $row['Name'] .
. "<img src='" . $row['imglink'] . "'>
</a>";
}
Now it would print something like
Vilage Name <img src="urltoimage">
When you click on this link you will be sent to a file called "attractions.php"
Create this file in the same directory and it should have the following php in it
<?php
$villageId = $_GET['village']; //this gets the id of the village from the url and stores
//it in a variable
//now that you have the id of the village, perform your sql lookup here
//of course you will have to fill this is, as I don't know your actual table fields and names
$sql = "SELECT * FROM Attractions WHERE villageID = `$villageID`";
//now perform the query, loop through and print out your results
?>
Does this make sense?

Change src of element loaded with AJAX

I'm trying to alter the src of imgs loaded via. AJAX, wherein the <select> and <option> elements used to control the function are also loaded by AJAX.
I'm trying to do this in order to change the size of Flickr images on the page.
I've tried loading the element, and calling an existing function to update it, but of course the <select> option doesn't exist on document.ready() and thus returns null when I try to get it.
I've also tried loading a new <script type='text/javascript'></script> in the PHP file I'm using for my XML response, but although this shows on the page it obviously isn't picked up as a source.
How can I tell the Document to 're-ready' itself, or acknowledge new sources?
Here's my code as it stands:
Making the request
function makeRequest (url, userID, searchString, selectedLicense) {
event.preventDefault();
var formData = new FormData();
formData.append("userID", userID);
formData.append("searchString", searchString);
formData.append("selectedLicense", selectedLicense);
var xmlRequest = new XMLHttpRequest();
xmlRequest.open("POST", url, true);
xmlRequest.send(formData);
xmlRequest.onreadystatechange=function()
{
if (xmlRequest.readyState===4 && xmlRequest.status===200) {
document.getElementById("working...").innerHTML="<p style='background-color:#BCED91; width:200px; text-align:center;'>Done!</p>";
document.getElementById("results").innerHTML=xmlRequest.responseText;
} else {
document.getElementById("results").innerHTML="<p>Ready State: " + xmlRequest.readyState + "</p> <p>Status Code: " + xmlRequest.status + "</p>";
}
}
}
The PHP
//more code before
$resultString = $resultString . "<script type='text/javascript'>"
. "function sizeChanged(i, select) {
var sel = getSelectedOptionValue(select);
var imgURL = document.getElementById(i.toString());
alert(imgURL);
}"
. "</script>";
//main loop
foreach ($XML->photos->photo as $photo):
$resultString = $resultString . '<div class="photoBox"' . photoBox($photoCounter) . "> <p>" . $photoCounter . ". " . $photo['title'] . "" . "</p>"
. " <p>" . "<img id='" . $photoCounter . "' src=\"http://farm" . $photo['farm'] . $imgURL . "/" . $photo['server'] . "/" . $photo['id'] . "_" . $photo['secret'] . "_" . $size . "\" alt=\"" . $photo['title'] . "\">" . "</p>"
. "<select form='addInformationForm' id='selectSize" . $photoCounter . "' onChange='return sizeChanged(" . $photoCounter . ", selectSize" . $photoCounter . ");'>"
. "<option value='n'>Small (320)</option>"
. "<option value='z' selected='selected'>Medium (640)</option>"
. "<option value='h'>Large (1600)</option>"
. "</select>"
. "</div>";
$photoCounter++;
endforeach;
//more code here
echo $resultString;
The HTML Output (Example)
<div class="photoBox" style="background-color:#FFFFFF">
<p>1. Killip's Adirondack Travelog, page 20</p>
<p><img id="1" src="http://farm9.staticflickr.com//8184/8427833074_2f7e22e7ce_z.jpg" alt="Killip's Adirondack Travelog, page 20"></p>
<select form="addInformationForm" id="selectSize1" onChange="return sizeChanged(1, selectSize1);">
<option value="n">Small (320)</option>
<option value="z" selected="selected">Medium (640)</option>
<option value="h">Large (1600)</option></select>
</div>
Any advice much appreciated!
NOTE: This code is for an internal tool, not a client-facing website.
The <select> doesn't exists at onload, but it does when you create it:
var res = document.getElementById("results");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.readyState===4 && xmlRequest.status===200) {
document.getElementById("working...").innerHTML="<p style='background-color:#BCED91; width:200px; text-align:center;'>Done!</p>";
res.innerHTML = xmlRequest.responseText;
var select = res.getElementsByTagName('select')[0];
/* Use select here */
} else {
res.innerHTML="<p>Ready State: " + xmlRequest.readyState + "</p> <p>Status Code: " + xmlRequest.status + "</p>";
}
};
Note that the <img> element should be available too, but you won't know its dimensions because it won't be downloaded. If you want to wait until it's loaded, you can add a load event listener.

Categories