I have a webpage that has a form to insert vendor data, once inserted the company name is the placed into a select box. when the company is selected a table is called with all the vendor information.
My problem is the
the vendor_email is called from a php script, is there a way to make the value of the id insert into a mailto: function.
<tbody id="records">
<td id="vendor_company"></td>
<td id="vendor_rep"></td>
<td id="vendor_email"></td>
</tbody>
<div class="row" id="no_records"><div class="col-sm-4">Plese select vendor name to view details</div></div>
here is my php and js code
<?php
include_once("Database/db_connect.php");
if($_REQUEST['empid']) {
$sql = "SELECT id, companyName, repName, venderEmail FROM vender_contact
WHERE id='".$_REQUEST['empid']."'";
$resultset = mysqli_query($conn, $sql) or die("database error:".
mysqli_error($conn));
$data = array();
while( $rows = mysqli_fetch_assoc($resultset) ) {
$data = $rows;
}
echo json_encode($data);
} else {
echo 0;
}
?>
my js code
$(document).ready(function(){
// code to get all records from table via select box
$("#vendors_data").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url:"getVendor.php",
dataType: "json",
data: dataString,
cache: false,
success: function(vendorData) {
if(vendorData) {
$("#heading").show();
$("#no_records").hide();
$("#vendor_company").text(vendorData.companyName);
$("#vendor_rep").text(vendorData.repName);
$("#vendor_email").text(vendorData.venderEmail);
$("#records").show();
} else {
$("#heading").hide();
$("#records").hide();
$("#no_records").show();
}
}
});
})
});
It's absolutely possible! You simply need to use .html() instead of .text().
Note that the mailto comes on the href attribute, which is unique to the <a> tag. As such, you'll want to place your inside of your <td id="vendor_email"></td>:
$("#vendor_email").html("<a href='mailto:" + vendorData.vendorEmail + "'>" + vendorData.vendorEmail + "</a>");
Which will render as something like:
vendorData = {};
vendorData.vendorEmail = 'test#test.com';
$("#vendor_email").html("<a href='mailto:" + vendorData.vendorEmail + "'>" + vendorData.vendorEmail + "</a>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="vendor_email"></div>
In addition to this, please be aware that your MySQLi is vulnerable to SQL injection. You should use prepared statements, and also ensure that your database user only has the required privileges in order to prevent this.
You can refer to this post for further information on how to prevent SQL injection in PHP :)
Hope this helps!
By using jQuery's .html() method you can insert html like so:
$( '#vendor_email' ).html( '' + vendorData.vendorEmail + '' );
By the way, I couldn't help but notice that you've spelled vendor as "vender" in venderEmail.
Related
In my DB i have created a table named "coursePlaces" in which i have 7 columns and a number of rows.
Loading the php-file course.php I connects to the db and selects data from the table "coursePlaces" using it to echo a number of buttons with different id and value each:
<?php
/* CONNECTION TO DB */
require 'includes/dbh.inc.php';
/* ACCESS COURSE AND GRADE VAR FROM URL WITH GET */
$course = $_GET['course'];
$grade = $_GET['grade'];
/* SELECTS DATA FROM TABLE AND ECHOES BUTTONS WITH DIFFERENT ID AND VALUE DEPENDING ON TABLE CONTENT */
$sql = "SELECT * FROM coursePlaces WHERE grade='$grade' AND course='$course'";
$result = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '">';
}
/* CONVERTS VAR TO USE IN JQUERY SCRIPT */
echo '<script>';
echo 'var grade = ' . json_encode($grade) . ';';
echo 'var course = ' . json_encode($course) . ';';
echo '</script>';
?>
<script src="includes/global.inc.js"></script>
<!-- DIV TO ECHO OUTPUT FROM PLACE.INC.PHP -->
<div class="selectedPlace" id="selectedPlace"></div>
When clicking one of the buttons the value should be send to the file "global.inc.js" In which i have placed a script used to listen for clicks:
$('input#$row['placeName']').on('click', function() {
var place = $('input#place-$row['placeName']').val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});
My problem is, that I don't know what the name of the button id is - since it is created from a varchar in a database table. How do i bring this information over into my .js file, so the script posts individual value from button no matter what button the user presses on the courses.php.
Use jQuery to set your variable with Ajax ( method POST ).
Try to change code as below:
$('input[type="submit"]').on('click', function() {
var place = $(this).val();
if (place !='') {
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
});
set on click attribute when you echo your inputs:
echo sprintf('<input type="submit" id="place-%s" value="%s" onclick="yourfunction("%s", "%s", "%s") >', $row['placeName'], $row['placeName'], $grade, $course);
and separate this yourfunction function:
function yourfunction(place, grade, course){
$.post('includes/place.inc.php', {place: place, grade: grade, course: course }, function(data) {
$('div#selectedPlace').text(data);
});
}
You should use a generic click handler instead of the one you are using.
If all button have one common class you can listen to the click of all.
Add class inputBtn to following:
echo '<input type="submit" id="place-' . $row['placeName'] . '" value="' . $row['placeName'] . '" class="inputBtn">';
Change
$('input#$row['placeName']').on('click', function() {
to
$('.inputBtn').on('click', function() {
var btnID = $(this).prop('id');
var spltID = btnID.split('-'); //split from the - & spltID[1] will contain the part that you required.
}
This code is written like just for the sake of clarity. It is possible to make it more optimal like split() function can be called on btnID to reduce code line.
I'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#comment_part").html(html);
window.location.reload();
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
//header("Location:csair.php");
die();
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
There are 3 main problems in your code:
You are not returning anything from insert.php via ajax.
You don't need to replace the whole comment_part, just add the new comment to it.
Why are you reloading the page? I thought that the whole purpose of using Ajax was to have a dynamic content.
In your ajax:
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
Within insert.php you need to return the new comment html:
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
Please note that you currently don't have any error handling, so when you return die('comment is not set....') it will be displayed as well as a new comment.
You can return a better structured response using json_encode() but that is outside the scope of this question.
You're using jQuery.html() which is replacing everything in your element with your "html" contents. Try using jQuery.append() instead.
I'm facing an issue to get the value of td when a link is clicked
search_code.php
echo "<table class='table table-hover'>";
echo "<tr><th>Institute ID</th><th>Institute Name</th><th>State</th><th>District</th><th>City</th><th>General Seats</th><th>Reserved Seats</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td id='instid'>".$row["collegeUniqueId"]."</td><td id='instname'><a href='#' onClick='getCourses(".$row["collegeUniqueId"].");'>".$row["name"]."</a></td><td>".$row["state"]."</td><td>".$row["district"]."</td><td>".$row["city"]."</td><td>".$row["openSeat"]."</td><td>".$row["reservedSeat"]."</td></tr>";
}
echo "</table>";
and in search.php
<script>
$(document).ready(function(){
$('#search').click(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'search_code.php?state=' + $('#state').val() + '&district=' + $('#district').val(),
success: function(institute){
$('#institute').html(institute);
}
});
});
function getCourses(id) {
$id = id;
$.ajax({
type: 'POST',
url: 'courses.php?courseid=' + id,
success: function(courses){
$('#courses').html(courses);
}
});
}
});
</script>
You haven't shown the HTML that gets produced, but if the "ID" value is anything other than a number, you need to put it in quotes:
echo "...onClick='getCourses(\"".$row["collegeUniqueId"]."\");'>...";
// --------------------------^^---------------------------^^
Side note: You'll also want to deal with those repeated id values the loop creates (assuming there's ever more than one row in the result set).
Side note 2: You're falling prey to The Horror of Implicit Globals in your getCourses function: You never declare the $id variable. You can just remove it, you're not using it for anything.
ID in HTML needs to be unique you can't have multiple elements with same ID.
There are at least 2 ways to fix it:
Use class attribute and use data-id attribute to get ID of particular row
In your PHP you can generate id with ROW id <td id='instid-".$row["collegeUniqueId"]."'>
I try to make a query from database to get the list of users based on their country using php/mysql and jquery.
I have a mysql query that extracts the countries form database in a select options field. After this, i put a jquery code to automatically get the table with users based on the selected country. This is how jquery code looks like:
<script>
$( "#tara" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += "<table class='table table-bordered table-striped'>" +
"<thead><tr><th><p><?php echo _('Tara');?></p></th></tr></thead>" +
"<tbody>" +
"<?php
$variabilatara = 182;
$test = mysql_query("SELECT * FROM utilizatori WHERE idt='$variabilatara'") ?>" +
"<?php while($row=mysql_fetch_object($test))
{
echo "<tr>";
echo "<td><p>$row->nume</p></td>";
echo "</tr>";
}
?>" + $( this ).val() + " ";
});
$( "#testare" ).html( str );
})
.change();
</script>
My question is: How to put the $( this ).val() into php instead of $variabilatara, so it will looks something like: $variabilatara = $( this ).val(); and the sql query will modify on change of selected country. Thank you!
What you are trying to do is called AJAX. Sounds complicated, but it really isn't. See these examples for a simplistic explanation. Do not just look at them -- copy/paste to your server and make them work. Change the values. See how it works - really very simple.
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
Your code is a bit difficult for me to follow, but should be refactored something like this. (I am unsure where strTara figures in the code, but I'm sure you will be able to figure it out from here).
javascript/jQuery:
var strTara = <?php echo _('Tara');?>
$( "#tara" ).change(function () {
selVal = $(this).val();
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'variabilatara=' + selVal,
success: function(data){
var tblHead = "
<table class='table table-bordered table-striped'>
<thead><tr><th><p>strTara</p></th></tr></thead><tbody>
";
$( "#testare" ).html( tblHead + data );
}
});
});
another_php_file.php: (your PHP AJAX processor file)
<?php
$var = $_POST['variabilatara'];
$out = '';
$result = mysql_query("SELECT * FROM utilizatori WHERE idt='$variabilatara'") or die(mysql_error());
while($row=mysql_fetch_object($result)){
$out .= "<tr>";
$out .= "<td><p>" .$row->nume. "</p></td>"; //<== fixed
$out .= "</tr>";
}
$out .= '</tbody></table>'; //<== fixed
echo $out;
?>
Hi I have a simple ajax search that returns the results in a table. I can extract the XML and display it fine but what I cannot do is get the index number of the data (var Rows) .
When a user clicks the returned result I believe I would need this in order to retrieve all the data in order to use IE $("name:eq(1)",data).text();. Can anyone help me please and I hope this makes sense !!, thanks
My Jquery code is here
$(document).ready(function(){
$.ajax({
type: "GET",
url: "search_action.php?" + string ,
dataType: "xml",
success: disxml ,
});
})
}
function disxml(data){
dv = $('#crmbox')
$(data).find('list').each(function() {
var name = $(this).find('name').text();
var cus_id = $(this).find('mid').text();
var rows = $(this).eq() ;
display = display + "(" + rows + ")" + " Name :" + name + " ID :" + cus_id + " <br>" ;
})
dv.html(r);
};
here is the php that generates my xml
echo '<results>' ;
while($row = mysql_fetch_array($result)) {
$name = $row['name'] ;
$major_id = $row['address1'] ;
echo '<list>' ;
echo '<name>';
echo $name;
echo '</name>';
echo '<mid>';
echo $major_id ;
echo '</mid>';
echo '</list>' ;
} ;
echo '</results>' ;
the extra tag is the close of an earlier function - no relevence to question
It sounds like you want the index you're currently at, in which case use the first parameter passed to the .each() callback, like this:
$(data).find('list').each(function(row) {
var name = $(this).find('name').text();
var cus_id = $(this).find('mid').text();
//row is the index, starting at 0