Change src of element loaded with AJAX - javascript

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.

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.

Trying to pass two variables in JavaScript popup

I'm calling the script below, now I need to be able to send two values to test23.php like
myFunction20(url,url2)
Can someone please help?
<script>
function myFunction20(url) {window.open('test23.php?id=' + url, "_blank", "toolbar=no,scrollbars=no,resizable=no,top=70,left=50,width=1200,height=500");}</script>
PHP Code
echo "<td>" .'<a href= javascript:myFunction20("'.$row['Account_Number'].'","'.$row['Account_Number'].'")>'.$row['Name'].'</a>' . "</td>";
Just add a second key/value pair to the querystring:
function myFunction20(url) {
window.open('test23.php?id=' + url + "&SECOND_KEY=" + "SECOND_KEY_VALUE",
"_blank",
"toolbar=no, scrollbars=no, resizable=no, top=70, left=50, width=1200, height=500");
}
you should wrap up the PHP variables in quotes and pass it your JS function
<?php
$parameter1 = "'" . $row['Account_Number'] . "'";
$parameter2 = "'" . $row['Account_Number'] . "'";
echo
'<td>
<a href= javascript:myFunction20(' . $ip . ',' . $id . ')>' . $row["Name"] . '</a>
</td>';
Your JS function
<script>
function myFunction20(url, url2) {
window.open('test23.php?id=' + url + '&' + url2, "_blank", "toolbar=no,scrollbars=no,resizable=no,top=70,left=50,width=1200,height=500");
}
</script>

JS sequential calling of function fails

I need to exicute one JS function after another sequencually. I can exicute these functions individually and they work but when I put them in a sequence I only get the openPatient() and the openMessage() does not exicute. My JS functions
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
My function call:
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
This function call exists in this process:
<?php
// Generate a table row for each pending portal request or message.
// This logic merges requests with messages by date.
$v1 = each($result['list']);
$v2 = each($result['messages']);
while ($v1 || $v2) {
echo " <tr class='detail' bgcolor='#ddddff'>\n";
if (!$v2 || $v1 && $v1[1]['datetime'] < $v2[1]['datetime']) {
$postid = $v1[1]['postid'];
$ptname = patientNameFromLogin($v1[1]['user']);
// Get the portal request data.
if (!$postid) die(xlt('Request ID is missing!'));
$result2 = cms_portal_call(array('action' => 'getpost', 'postid' => $postid));
if ($result2['errmsg']) {
die(text($result2['errmsg']));
}
// Look up the patient in OpenEMR.
$ptid = lookup_openemr_patient($result2['post']['user']);
echo " <td>" . text($v1[1]['user']) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;' onclick=\"openPatient()\">" .text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient().then(openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
"))\">" . text($v1[1]['datetime']) . "</td>\n";
echo " <td>" . text($v1[1]['type' ]) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_req_cb[" .
attr($postid) . "]' value='" . attr($postid) . "' /></td>\n";
$v1 = each($result['list']);
}
else {
$messageid = $v2[1]['messageid'];
$ptname = patientNameFromLogin($v2[1]['user']);
echo " <td>" . text($v2[1]['user']) . "</td>\n";
echo " <td>" . text($ptname ) . "</td>\n";
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openMessage(" .
"'" . addslashes($messageid) . "'" .
")\">" . text($v2[1]['datetime']) . "</td>\n";
echo " <td>" . text($v2[1]['user'] == $v2[1]['fromuser'] ?
xl('Message from patient') : xl('Message to patient')) . "</td>\n";
echo " <td align='center'><input type='checkbox' name='form_msg_cb[" .
attr($messageid) . "]' value='" . attr($messageid) . "' /></td>\n";
$v2 = each($result['messages']);
}
echo " </tr>\n";
}
?>
I am thinking part of the problem may be that openPatient() opens in another window. Perhaps it is loosing focus. Any tips to fix this would be appreciated.
EDIT:
What I have tried and helps is adding return this; to openPatient():
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
This then executes the next function but the next function executes too soon. it needs to wait for openPatient() to fully load before executing openMessage(). I have tried adding setTimeout( wait, 1000 ); but then openMessage() does not execute at all.
The solution:
The call:
echo " <td style='cursor:pointer;color:blue;'";
echo " onclick=\"openPatient();setTimeout(function(){openRequest(" .
"'" . addslashes($postid) . "'," .
"'" . addslashes($v1[1]['type']) . "'" .
")}, 2500);\">" . text($v1[1]['datetime']) . "</td>\n";
The functions:
function openPatient() {
myRestoreSession();
opener.top.RTop.document.location.href = '../patient_file/summary/demographics.php?set_pid=<?php echo attr($ptid); ?>';
return this;
}
function openMessage(messageid) {
myRestoreSession();
document.location.href = 'upload_form.php?messageid=' + messageid;
}
Keys to success: return this; and the use of the anonymous function with setTimeout in the call.
Posts that helped:
What does "return this" do within a javascript function?
setTimeout delay not working

Adding comments into database with PHP (Using AJAX to prevent page reload)

I'm trying to make a comments system which adds to the database using PHP and AJAX without having to reload the page (if I reload the page it will pick another film suggestion at random).
At the moment it doesn't seem to work - when I click "Submit comment" it reloads the page (loading a different film) and nothing is inserted to the database.
I'd also like to be able to have the comment appear in the comments section below after submission if possible.
Thanks for your help
yourfilm.php (the process page that displays a film, specified by options selected on a form on the previous page)
<?php //recaptcha_process.php
require_once("php/checklog.php");
require_once('php/functions.php');
require_once('php/db_connect.php');
include_once("php/home_start_logged.php");
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
}else{
//CODE TO QUERY DATABASE TO GO HERE
//Capture form data, if anything was submitted
if (isset($_POST['genreList']) && ($_POST['genreList'] != '')){
$genre = clean_string($db_server, $_POST['genreList']);
//create the SQL query
$query = "SELECT * FROM films WHERE genreID=$genre ";
//$endquery = " AND (";
$endquery = "";
$orFlag = false;
if (isset($_POST['streamingCheckbox1']) && ($_POST['streamingCheckbox1'] != '')){
$endquery .= " netflix IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox2']) && ($_POST['streamingCheckbox2'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " lovefilmInstant IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox3']) && ($_POST['streamingCheckbox3'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " blinkbox IS NOT NULL";
}
if($endquery != "") $query .= " AND (" . $endquery . ")";
$query .= " ORDER BY (SELECT FLOOR(MAX(filmID) * RAND()) FROM films) LIMIT 0,1;";
//query the database
mysqli_select_db($db_server, $db_database);
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) . $query);
//if there are any rows, print out the contents
if ($row = mysqli_fetch_array($result)) {
//Whether to display links or not for purchase and streaming
if ($row['netflix'] == null){
$netflixLink = "";
}else{
$netflixLink = "<a href='" . $row['netflix'] . "'>" . "<img class='streamingLogo' src='images/netflix_logo.jpg' alt='Watch on Netflix'></a>";
}
if ($row['lovefilmInstant'] == null){
$lovefilmLink = "";
}else{
$lovefilmLink = "<a href='" . $row['lovefilmInstant'] . "'>" . "<img class='streamingLogo' src='images/Lovefilm_logo.jpg' alt='Watch on LoveFilm'></a>";
}
if ($row['blinkbox'] == null){
$blinkboxLink = "";
}else{
$blinkboxLink = "<a href='" . $row['blinkbox'] . "'>" . "<img class='streamingLogo' src='images/blinkbox_logo.jpg' alt='Watch on Blinkbox'></a>";
}
if ($row['itunes'] == null){
$iTunesLink = "";
}else{
$iTunesLink = "<a href='" . $row['itunes'] . "'>" . "<img class='streamingLogo' src='images/itunes_logo.jpg' alt='Buy now on iTunes'></a>";
}
if ($row['googlePlay'] == null){
$googleplayLink = "";
}else{
$googleplayLink = "<a href='" . $row['googlePlay'] . "'>" . "<img class='streamingLogo' src='images/googleplay_logo.jpg' alt='Buy now on Google Play'></a>";
}
if ($row['amazon'] == null){
$amazonLink = "";
}else{
$amazonLink = "<a href='" . $row['amazon'] . "'>" . "<img class='streamingLogo' src='images/amazon_logo.jpg' alt='Buy now on Amazon'></a>";
}
//Body content for film
$str_result = "<section>
<div class='sectionColumnThird'>
<img class='poster' src='images/posters/" . $row['poster'] . ".jpg'>
</div>
<div class='sectionColumnTwoThirds'>
<h2>" . $row['filmName'] . "</h2>
<p class='filmDate'>(" . $row['filmYear'] . ")</p>
<a class='formButton' href='#comments'>Jump to comments</a>
</div>
</section>
<section>
<h3>Not interested?</h3>
<a class='formButton' href='#yourfilm.php'>Find another film</a>
</section>
<section>
<h3>Rating</h3>
<p><span class='bold'>IMDB:</span> " . $row['ratingIMDB'] . "</p>
<p><span class='bold'>Rotten Tomatoes:</span> " . $row['ratingRottenTomatoes'] . "</p>
<p><span class='bold'>Metacritic:</span> " . $row['ratingMetacritic'] . "</p>
</section>
<section>
<h3>Synopsis</h3>
<p>" . $row['synopsis'] . "</p>
</section>
<section>
<h3>Trailer</h3>
<div class='videoWrapper'>
<iframe src='//www.youtube.com/embed/" . $row['trailer'] . " ' frameborder='0' allowfullscreen></iframe>
</div>
</section>
<section>
<h3>Cast & Crew</h3>
<p><span class='bold'>Director:</span> " . $row['director'] . "</p>
<p><span class='bold'>Writers:</span> " . $row['writer'] . "</p>
<p><span class='bold'>Cast:</span> " . $row['cast'] . "</p>
</section>
<section>
<h3>Details</h3>
<p><span class='bold'>Certificate:</span> " . $row['certificate'] . "</p>
<p><span class='bold'>Country:</span> " . $row['country'] . "</p>
<p><span class='bold'>Language:</span> " . $row['language'] . "</p>
</section>
<section>
<h3>Streaming Services</h3>"
. $netflixLink . $lovefilmLink . $blinkboxLink ."
</section>
<section>
<h3>Buy now</h3>"
. $iTunesLink . $googleplayLink . $amazonLink ."
</section>
<section>
<form id='frmFilmComments' action='yourfilm.php' method='post'>
<a id='comments' class='anchor'></a><h3>Comments</h3>
<p><span class='bold'>Did you like " . $row['filmName'] ."?</span></p>
<select class='selectbox' name='yesornoList'>
<option value='Yes'>Yes</option>
<option value='No'>No</option>
</select>
<p id='commentResult'></p>
<p><span class='bold'>Provide your feedback here:</span></p>
<textarea id='commentBox' class='insertComment' rows='2' cols='30' name='comment'></textarea><br>
<input class='formButton' type='submit' id='submitComment' name='submitComment' value='Submit comment' />
</form>";
$filmID=$row['filmID'];
mysqli_free_result($result);
//Print out Like it - Comments
$likeitQuery = "SELECT * FROM comments
JOIN users on users.userID = comments.userID
WHERE likeit='Yes' AND filmID=$filmID";
$likeitResult = mysqli_query($db_server, $likeitQuery);
if (!$likeitResult) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($likeitResult)){
$str_likedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
. $row['comment'] . "<br>
▲(" . $row['upvotes'] . ") ǀ ▼ (" . $row['downvotes'] . ")</p>";
}
mysqli_free_result($likeitResult);
$likedcomments = "<div class='half subSection'>
<h4>Liked it</h4>"
. $str_likedcomments .
"</div>";
//Print out disike it - Comments
$dislikeitQuery = "SELECT * FROM comments
JOIN users on users.userID = comments.userID
WHERE likeit='No' AND filmID=$filmID";
$dislikeitResult = mysqli_query($db_server, $dislikeitQuery);
if (!$dislikeitResult) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($dislikeitResult)){
$str_dislikedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
. $row['comment'] . "<br>
▲(" . $row['upvotes'] . ") ǀ ▼ (" . $row['downvotes'] . ")</p>";
}
mysqli_free_result($dislikeitResult);
$dislikedcomments = "<div class='half subSection'>
<h4>Disliked it</h4>"
. $str_dislikedcomments .
"</div>";
}else{
$str_result = "<section><h3>Sorry</h3><p>We couldn't find any films that match your terms. </br> <a href='home.php'>Please try again.</a></p></section>";
}
}else{
$str_result = "<section><h3>Sorry</h3><p>No genre was chosen.</br><a href='home.php'>Please try again.</a></p></section>";
}
$message = $str_result . $likedcomments . $dislikedcomments . "<section/>";
}
//Comments
$userID = $_SESSION['userID'];
$likeit = $_POST['yesornoList'];
$comment = clean_string($db_server, $_POST['commentBox']);
//Get any submitted comments and insert
if ($comment != '') {
$query = "INSERT INTO comments (userID, filmID, comment, likeit) VALUES ($userID, $filmID, $comment)";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
$message = "Thanks for your comment!";
}
require_once('php/db_close.php');
?>
<div id="top" class="content container headerMargin">
<div class="content wrapper">
<?php echo $message; ?>
</div>
</div>
<?php
require_once('php/home_end.php');
?>
addCommentAJAX.js
$("#submitComment").click( function() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
});
$("#frmFilmComments").submit( function() {
return false;
});
function clearInput() {
$("#frmFilmComments :input").each( function() {
$(this).val('');
});
}
home_start_logged.php is simply a header template, I won't post it all but it contains:
<script src="js/addCommentAJAX.js" type="text/javascript"></script>
EDIT: Added more specific info about the error (see above).
there is not enough data to make an exact solution, but i see two problems :
1 - you are not preventing the default form submit in your submit function event.preventDefautlt() or just change the input type attribut in your form to button rather than submit
2 - if you wan't the comment that the user just sent to show up then you can use the function append() to make it show at the end of the comment section this is the fastest way to do this rather than waiting for it to show from the database
So what is probably happening here is that you haven't used event.preventDefault() This will stop your submit button from reloading the page, which will allow your ajax code and your code posting the comment to finally get run.
http://api.jquery.com/event.preventdefault/
The idea behind preventDefault is that it stops the submit button from doing its default behavior, which is submitting a form and reloading the page.
can you change this
$("#submitComment").click( function() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
});
to
function onclicksth() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
}
and change submitComment type to button? There is a better way to do this too:
//rough code including the submit and post data
$('form.frmFilmComments').on('submit', function() {
if(confirm('Do u want to input that field')){
fields-=1;
var obj = $(this),
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
$("#hdnlstcount").val(fields);
//console.log(fields);
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response2) {
//do sth with success response
}
});
return false; //disable refresh
clearInput();
}
});

PHP function ignoring an if statement

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.

Categories