Related
I'm working on a tagging part on a site similar to Facebook. The idea is that whenever someone types # in the post area, a drop down menu appears containing all of his friends. He then picks who he wants to tag and clicks on that person's profile. I have a javascript function which detects when # is pressed, and then calls another js function which then in turn sends an ajax request to a php file for the list. And this part works great.
So when the user clicks on someone from their friend list, I set it up so that an href part containing the friend's username is extracted from the php file as plain text, and then displayed as a text string right after the # character in the post area (I prevented following to the profile after clicking with return: false). So, for example, when someone wants to choose John Smith, he presses #, the list appears, he picks John Smith, clicks on his profile, the list disappears, and then the username appears after #, like this: #john_smith
Now the trouble is that I would want to make john_smith after # into a hyperlink that would lead to John Smith's profile, instead of it being just plain text. And I've been really struggling to find a solution. Any help would be much appreciated.
Thanks a lot! :)
**//php ajax file**
<?php
$userLoggedIn = $_POST['userLoggedIn'];
$userLoggedIn = new User($con, $userLoggedIn);
$rez = array();
$rez = $userLoggedIn->getFriendArray();
if ($rez != ",") {
$no_commas = explode(",", $rez);
foreach ($no_commas as $key => $value) {
$friend = mysqli_query($con, "SELECT first_name, last_name, username, profile_pic FROM users WHERE username='$value'");
$row = mysqli_fetch_assoc($friend);
echo "<div class='displayTag'>
<a href=" . $row['username'] . " id='grabLink'>
<div>
<img src='" . $row['profile_pic'] . "'>
</div>
<div>
" . $row['first_name'] . " " . $row['last_name'] . "
<p style='margin: 0;'></p>
<p id='grey'></p>
</div>
</a>
</div>";
}
}
else {
echo "<br><p id='ynf'>You have no friends. Please add someone</p>";
}
**//js functions**
function userTag(user) { // for ajax
$.post("includes/handlers/ajax_user_tag.php", {userLoggedIn:user},
function(data){
$('.tag_results').html(data);
});
}
function textTag() { // for extracting href and placing # and username anywhere in the post area
$('.displayTag a').click(function(a){
var x = $(this).attr('href');
var y = $(this).prop('href');
var $txt = jQuery("#post_text");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
$txt.val(textAreaTxt.substring(0, caretPos) + x + textAreaTxt.substring(caretPos) );
$('.tag_results').html("");
return false;
});
}
**//js code**
$("#post_text").keydown(function (e) { // listens for #
if(e.which == 50)
userTag('<?php echo $userLoggedIn; ?>');
if(e.which != 50)
$('.tag_results').html("");
});
$('.tag_results').hover(function(e) { //calls textTag function on hover
textTag();
});
**//Empty div populated by ajax results**
<div class="tag_results">
</div>
EDIT:
I found out what the problem was, purely by accident. In the file with the php classes, strip_tags was used for all posts. So what I wanted to do was practically impossible with that turned on. Now it's working as it should. Thanks everyone for help! :)
I don't believe that your click event is capturing the click, because your php is dynamically creating the list element. Also your function, textTag() doesn't actually apply the event until that function is run, so it could be creating issues. Change your JS to -
$(document).on('click', '.displayTag a', function() {
var href = $(this).attr('href');
//other code applying href to new anchor tag in proper format
});
First I would change a little bit the PHP response in order to make it easier to get the firend's full name.
**//php ajax file**
<?php
$userLoggedIn = $_POST['userLoggedIn'];
$userLoggedIn = new User($con, $userLoggedIn);
$rez = array();
$rez = $userLoggedIn->getFriendArray();
if ($rez != ",") {
$no_commas = explode(",", $rez);
foreach ($no_commas as $key => $value) {
$friend = mysqli_query($con, "SELECT first_name, last_name, username, profile_pic FROM users WHERE username='$value'");
$row = mysqli_fetch_assoc($friend);
echo "<div class='displayTag'>
<a href=" . $row['username'] . " id='grabLink'>
<div>
<img src='" . $row['profile_pic'] . "'>
</div>
<div class='fullname'>
" . $row['first_name'] . " " . $row['last_name'] . "
<p style='margin: 0;'></p>
<p id='grey'></p>
</div>
</a>
</div>";
}
}
else {
echo "<br><p id='ynf'>You have no friends. Please add someone</p>";
}
Then I would modify the JS function
function textTag() { // for extracting href and placing # and username anywhere in the post area
$('.displayTag a').click(function(a){
var fullname = $(this).find('.fullname').text();
var x = ''+fullname +'';
var y = $(this).prop('href');
var $txt = jQuery("#post_text");
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
$txt.html(textAreaTxt.substring(0, caretPos) + x + textAreaTxt.substring(caretPos) );
$('.tag_results').html("");
return false;
});
}
Please bear with me; trying my best to learn more Ajax. I am trying to Validate whether the Name of Event field in my form already exists in my table, but only if both were created by the same User. For example, if User 1 already has an event called Event1, the validation would check if there was a duplicate event name ONLY under User1.
I have the following snippet in a PHP/HTML form:
<div>Event Name: </div>
<input type="text" name="eventname" id="eventname" onblur="checkeventname()" onkeyup="restrict('eventname')" size="50" maxlength="75" />
<span id="eventnamestatus"></span>
This is my checkeventname function:
function checkeventname(){
var nameofevent = _("eventname").value;
if(nameofevent != ""){
_("eventnamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "eventcreationpage.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("eventnamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+nameofevent);
}
}
And here is the Ajax I put at the top of the page, which I am having trouble with:
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["eventnamecheck"])){
include_once("php_includes/db_conx.php");
$eventname = preg_replace('#[^a-z0-9]#i', '', $_POST['eventname']);
$sql = "SELECT id FROM users WHERE eventname='$eventname' && eventcreator='$eventcreator' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$eventname_check = mysqli_num_rows($query);
if ($eventname_check < 1) {
echo '<strong style="color:#009900;">' . $eventname . ' is not a duplicate name</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $eventname . ' is an event name already under your name</strong>';
exit();
}
}
?>
The webpage itself has the user variable carried over (eventcreationpage.php$eventcreator=User1) I am trying to send over the $eventcreator variable, which would be the User in this case, but I'm not quite sure how to do so.
Set
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
to show that this request will send form data. Next, on your server, you may use $_POST["userid"] to get the userid if you specified it via
ajax.send("userid=" + userid);
To send both userid and eventid, you may use
ajax.send("userid=" + userid + "&eventid=" + eventid);
If you get the userid only from PHP, you could render it into script. That would look like this:
ajax.send("userid=<?php echo $eventcreator; ?>&eventid=" + eventid);
which injects the user's name into the string. Make sure it is properly escaped though, if you allow special characters for user names though.
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?
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.
I am using a third party shopping cart that sends a registration form to a .cgi script.
I want to send information from that form to me, and the customer via a jQuery $.get() function call.
The $.get calls a registration.mail.php script.
The problem is that the form submitting seems to cancel out the ajax call before the ajax call can be completed.
I can think of some inelegant solutions, and I have decided, because I'm about to travel, to use a counter and make the user click 'Register' twice. This solution hurts my soul obviously.
Here's the Javascript, that lives in the footer:
<script type="text/javascript">
var getsuccess = false;
$(document).ready(function() {
$('form#registerWholesale').bind('submit', function() {
$email = $('#email').val();
$username = $('#contactname').val();
$company = $('#company').val();
$phone = $('#billphone1').val();
$message = "A new customer has registered at the wholesale website. \n ";
$message += "They have the username of: " + $username + ". \n";
$message += "Their company is: " + $company + ". \n";
$message += "Their email is: " + $email + ". \n";
$message += "Their phone is: " + $phone + ". \n";
$message += "Please help them ASAP. You can access the back end of the site at: http://location of website admin backend";
$.get('/mail.php', {from: 'orders#OurCompany.com', message: $message, email: $email, username: $username, company: $company}, function(data, textStatus, xhr) {
getsuccess = true;
});
if (getsuccess) {
return true;
}else{
return false;
}
});
</script>
And here is the registration.mail.php code.
<?php
//Vendor email (to us)
$to = "ouremail#OurCompany.com";
$subject = "URGENT--New Registration--URGENT";
$message = htmlentities($_GET['message'], ENT_QUOTES, 'UTF-8');
//$message = $_GET['message'];
$from = htmlentities($_GET['from'], ENT_QUOTES, 'UTF-8');
//$from = trim($_GET['from']);
$headers = "From: $from";
mail($to,$subject,$message,$headers);
//echo "Mail Sent.";
//Customer email (to them)
$to_cust = htmlentities($_GET['email'], ENT_QUOTES, 'UTF-8');
$subject_cust = 'OurCompany Online Wholesale Account Request Recieved';
$message_cust = "Thank you for you interest in OurCompany's new wholesale website. \n\n
We have received your request to create an account. In order to obtain a wholesale account, a OurCompany representative must verify your account information and details by telephone. OurCompany will contact you within 1 business day at the telephone number that we have on file, or feel free to give us a call at 1-xxx-xxx-xxxx anytime if you would like a more rapid approval. \n\n
Thanks Again ~ OurCompany";
$headers_cust = "From: orders#OurCompany.com";
mail($to_cust,$subject_cust,$message_cust,$headers_cust)
?>
Thank you!
Your Ajax get handler sets up an asynchronous callback. In other words, this piece of code:
$.get('/mail.php', {from: 'orders#OurCompany.com', message: $message, email: $email, username: $username, company: $company}, function(data, textStatus, xhr) {
getsuccess = true; <---- THIS
});
The "THIS" line is only called when the Ajax call returns a result. Since you are sending an actual email, it may take a long time.
So, by the time you run this:
if (getsuccess) {
return true;
}else{
return false;
}
The Ajax call has never completed, and this always returns false.
You should basically just decide whether you want to submit the form with Ajax or not, and only use one of those. If you want to do Ajax, the Submit event handler should always return False.
EDIT: I did not realize that the mail sending and form submitting are two different actions, and two separate server calls. (You are not showing the rest of your app, but this is the idea that I get from other answers.) This is bad design that may lead to inconsistent results and bad data. You should redesign your app so that both of these things are handled on server side in the same place, so that the web app only makes one call, no matter if this one call is by Ajax or regular form submit.
One solution is to bind the event to the button click , prevent the default action of the click so the form does not submit, then finally submit the form in the .get callback.
N.B As Jaanus suggests you should really look at the app design and send the mail and save the cart in the same call. What happens if the email gets sent then the form submission action fails?
$(document).ready(function() {
$('#yourSubmitButton').click( function(ev) {
//prevent form submission
ev.preventDefault();
$email = $('#email').val();
$username = $('#contactname').val();
$company = $('#company').val();
$phone = $('#billphone1').val();
$message = "A new customer has registered at the wholesale website. \n ";
$message += "They have the username of: " + $username + ". \n";
$message += "Their company is: " + $company + ". \n";
$message += "Their email is: " + $email + ". \n";
$message += "Their phone is: " + $phone + ". \n";
$message += "Please help them ASAP. You can access the back end of the site at: http://location of website admin backend";
$.get('/mail.php', {from: 'orders#OurCompany.com', message: $message, email: $email, username: $username, company: $company}, function(data, textStatus, xhr) {
//all is well, submit the form
$('#yourForm').submit()
});
});
At the very least, rather than make them click twice, why dont you make the success callback of the $.get submit the form again for them?
$('form#registerWholesale').bind('submit', function() {
if (getsuccess) {
return true;
} else {
$email = $('#email').val();
$username = $('#contactname').val();
$company = $('#company').val();
$phone = $('#billphone1').val();
$message = "A new customer has registered at the wholesale website. \n ";
$message += "They have the username of: " + $username + ". \n";
$message += "Their company is: " + $company + ". \n";
$message += "Their email is: " + $email + ". \n";
$message += "Their phone is: " + $phone + ". \n";
$message += "Please help them ASAP. You can access the back end of the site at: http://location of website admin backend";
$.get('/mail.php', {from: 'orders#OurCompany.com', message: $message, email: $email, username: $username, company: $company}, function(data, textStatus, xhr) {
getsuccess = true;
$('form#registerWholesale').submit();
});
return false;
}
});
Have you tried putting the ajax call in a function, and hooking the onSubmit of the form?
onsubmit="myajaxcallFunc(); return true;"
This is commonly used to stop the submission, with return false, but in this case it may do what you want.
The callback you're passing to $.get will be evaluated after the AJAX request. Since AJAX is asynchronous, your code will continue to evaluate in the mean time, which means your if-condition with the two return-statements will always evaluate before the AJAX callback is called.
What you want to do is for the submit listener to always return false, and in the AJAX callback, you conditionally trigger $('form#registerWholesale').submit();
Of course there's a design consideration here as well: you may want the e-mail sending and wholesale registration to be atomical. If the mail is sent, you always want the stuff that happens in form submit to happen as well, right? In that case you want to move either the email sending to the form postback, or the wholesale registration to the AJAX callback, so it's all handled in one step.