ajax php form validation not working - javascript

I have written a php file and jquery to retrieve data from a database and validate on a textfield blur event to check the typed value is whether available or not. Below are my code:
On form php:
<script>
$("#catname").blur(function() {
$.post("./scripts/checkavailability.php", {
nameava: $("#catname").val(),
}, function(data) {
alert(data);
});
var setr = "<?php
include './scripts/checkavailability.php';
$dbava = getfromdb("name", "tbl_category");
$avams = check($txtval, $dbava, "$name");
echo $avams;
?>";
$("#jinx").html(setr);
});
</script>
checkavalilability.php :
<?php
if (isset($_POST['nameava'])) {
$txtval = mysql_real_escape_string($_POST['nameava']);
}
function getfromdb($field, $table) {
$avres = mysql_query("SELECT `" . $field . "` FROM `" . $table . "`");
return $avres;
}
function check($curval, $qres, $s_field) {
while ($a_row = mysql_fetch_array($qres)) {
$dbval = $a_row[$s_field];
if ($curval == $dbval) {
return "This value is taken";
break;
} else {
return "This value is available";
}
}
}
?>
Note: catname is the textfield id and jinx is the div id.

I think you are trying something like this:
jQuery:
<script>
$("#catname").blur(function() {
$.post("./scripts/checkavailability.php", {
nameava: $("#catname").val(),
}, function(data) {
alert(data);
$("#jinx").html(data);
});
});
</script>
PHP:
<?php
function getfromdb($field, $table) {
$avres = mysql_query("SELECT `" . $field . "` FROM `" . $table . "`");
return $avres;
}
function check($curval, $qres, $s_field) {
while ($a_row = mysql_fetch_array($qres)) {
$dbval = $a_row[$s_field];
if ($curval == $dbval) {
return "This value is taken";
//break;
} else {
return "This value is available";
}
}
}
if (isset($_POST['nameava'])) {
$txtval = mysql_real_escape_string($_POST['nameava']);
$dbava = getfromdb("name", "tbl_category");
$avams = check($txtval, $dbava, "name");
echo $avams;
}
exit();
?>

Related

Condition in each function is outputting same set of results for all records

I am performing a foreach loop and then sending that data. Then in my AJAX function I am outputting the information in the success function. This all works fine.
However, I just tweaked the code to include a new data-attribute. This data-attribute holds the $creator variable. It can be seen here:
$html .= '<div class="projectCont" data-current="'.$category.'" data-creator="'.$project_creator.'">';
The correct data is outputting.
What I am having issues with is adding the active class to the container - .projectCont when the data-attribute - data-creator is customer.
Right now it seems like only the last looped object is being checked and then whatever this is, the rest of the data is taking on.
For example: I have around 10 looped object being outputted. For testing purposes, I changed the creator to "Customer" for only one of these - the last one in the database. Now when all of these loop and output, every single record has the class that was added based on my condition in the success.
Does anyone know why this is happening? I nested this condition in the each function thinking that it would check and modify each individual record.
Condition in question (see JS for more code):
var projectCreator = $('.projectCont').data('creator');
if (projectCreator == 'Customer') {
$('.creatorIcon').addClass('active');
console.log("It should be showing");
} else {
$('.creatorIcon').removeClass('active');
}
JS:
success: function (data) {
//console.log(data);
if (data == null) {
alert("Unable to retrieve projects!");
alert(data);
} else {
var displayProjects = JSON.parse(data);
$wrapper.empty();
$(displayProjects).each(function() {
$wrapper.append(this.html);
//console.log(this.html);
var projectCreator = $('.projectCont').data('creator');
if (projectCreator == 'Customer') {
$('.creatorIcon').addClass('active');
console.log("It should be showing");
} else {
$('.creatorIcon').removeClass('active');
}
});
$wrapper.append(startBuilding);
}
PHP:
if ($projects_stmt = $con->prepare($projects_sql)) {
$projects_stmt->execute();
$project_rows = $projects_stmt->fetchAll(PDO::FETCH_ASSOC);
$proj_arr = array();
foreach ($project_rows as $project_row) {
$project_creator = $project_row['creator'];
$html = '';
$html .= '<div class="projectCont" data-current="'.$category.'" data-creator="'.$project_creator.'">';
$html .= '<div class="creatorIcon"><img src="/Projects/expand.png" alt="Customer Photo"></div>';
$html .= '</div>';
$data = array('id' => $project_row['id'], 'date' => $project_row['date_added'], 'html' => $html);
$proj_arr[] = $data;
}
}
echo json_encode($proj_arr);
More JS:
$('.categoryList').on('click', function (event) {
$('#projectsWrap').addClass('active'); //Once a category is selected the project wrap section will show
$wrapper = $('#projectGallery');
category = $(this).data('category');
//console.log(category);
$.ajax({
url: '/php/projectLoadTest.php',
type: 'POST',
data: {
'category': category
},
success: function (data) {
//console.log(data);
if (data == null) {
alert("Unable to retrieve projects!");
alert(data);
} else {
var displayProjects = JSON.parse(data);
$wrapper.empty();
$(displayProjects).each(function() {
$wrapper.append(this.html);
//console.log(this.html);
var projectCreator = $('.projectCont').data('creator');
if (projectCreator == 'Customer') {
$('.creatorIcon').addClass('active');
console.log("It should be showing");
} else {
$('.creatorIcon').removeClass('active');
}
});
$wrapper.append(startBuilding);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
alert('There are currently no project images for this selection');
}
});
//was here
});
I think you shouldn't mess with the JS in this case - you can do this class manipulation in your PHP:
if ( $projects_stmt = $con->prepare( $projects_sql ) ) {
$projects_stmt->execute();
$project_rows = $projects_stmt->fetchAll( PDO::FETCH_ASSOC );
$proj_arr = array();
foreach ( $project_rows as $project_row ) {
$project_creator = $project_row[ 'creator' ];
$html = '';
$html .= '<div class="projectCont" data-current="' . $category . '" data-creator="' . $project_creator . '">';
// setting the active string - if Customer -> ' active'
$is_active = ( $project_creator == 'Customer' ) ? ' active' : '';
$html .= '<div class="creatorIcon' . $is_active . '"><img src="/Projects/expand.png" alt="Customer Photo"></div>';
$html .= '</div>';
$data = array( 'id' => $project_row[ 'id' ], 'date' => $project_row[ 'date_added' ], 'html' => $html );
$proj_arr[] = $data;
} // foreach
} // if
echo json_encode( $proj_arr );

How to remove all html tags except last 5?

I set a php/javascript chat for my site, the problem is that I want to show only the last 5 messages, and then the older ones after 5 must disappear. These messages are entered in the pre . How can this be done? This is all the code I am using
$(document).ready(function(){
cometApi.start({node:"/", dev_id:/ })
cometApi.subscription("simplechat.newMessage", function(event){
$("#web_chat").append('<pre><b style="font-size:15px">'+HtmlEncode(event.data.name)+'</b>: '+HtmlEncode(event.data.text)+'</pre>')
})
})
function HtmlEncode(s)
{
var el = document.createElement("div");
el.innerText = el.textContent = s;
s = el.innerHTML;
return s;
}
function send()
{
var name = $('#name').val();
var text = $('#text').val();
$.ajax({
url: "/fileadmin/chat/chat.php",
type: "POST",
data:"text="+encodeURIComponent(text)+"&name="+encodeURIComponent(name)
});
}
PHPCODE:
$comet = mysqli_connect($host, $user, $password, "/");
if(mysqli_errno($comet))
{
echo "Error:".mysqli_error($link);
}
$msg = Array( "name" => $_POST["name"], "text" => $_POST["text"] );
$msg = json_encode($msg);
$msg = mysqli_real_escape_string($comet, $msg);
$query = "INSERT INTO pipes_messages (name, event, message)" .
"VALUES('simplechat', 'newMessage', '".$msg."')";
mysqli_query($comet, $query);
if(mysqli_errno($comet))
{
echo "Error:".mysqli_error($comet);
}
else
{
echo "ok";
}
You might use a nifty little css selector and then remove them on every newMessage event like this:
cometApi.subscription("simplechat.newMessage", function(event){
$("#web_chat").append('<pre><b style="font-size:15px">'+HtmlEncode(event.data.name)+'</b>: '+HtmlEncode(event.data.text)+'</pre>')
$('#web_chat > pre:nth-last-child(n+6)').remove()
})

The location which i have selected in search bar should reflect in mydealers.php page

I have implemented autocomplete search bar for my website. I will select location in the index.php page. The selected location from index.php page has to reflect to mydealers.php page also. but its not happening. instead it's showing some other location name.
Html Code
<div style=margin-left:500px;margin-top:-40px;width:500px>
<?php
echo " <select data-live-search='true' data-live-search-style='startsWith' class='selectpicker' id='locName'>";
$stmt = $conn->prepare('SELECT LocationName From arealistmain');
$stmt->execute();
while($row = $stmt->fetch()) {
echo " <option>" .$row['LocationName'] . "</option>";
}
echo "</select>";
?>
</div>
Java Script
<!--AutoComplete Search bar-->
$(function() {
$("#locName").autocomplete({
minLength: 1,
function(event) {
var value = event.getAttribute('value')
var locName = document.getElementById("locName").value;
if (value.includes('&')) {
value = value.replace("&", "%26");
}
if (locName == "") {
alert("Please Select your Location");
} else {
window.location = "http://www.citycontact.in/MyDealers.php?id="+value+"&locName="+locName;
}
return false;
}
});
});
<!--Auto Complete For Categories-->
function Demo(anchor) {
var value = anchor.getAttribute('value')
var locName=document.getElementById("locName").value;
if(value.includes('&')){
value = value.replace("&", "%26");
}
if(locName==""){
alert("Please Select your Location");
} else {
window.location = "http://www.citycontact.in/MyDealers.php?id="+value+"&locName="+locName;
}
}

Change & into & when show on json

So i have problem whit symbols "&", here my code on javascript
$("#shipCurr").change(function(){
var curr = $(this).val();
$("#shipPO").empty();
if(curr != "")
{
$("#shipPO").prop('disabled',false);
$.ajax
({
type: "POST",
url: host+"buypo/ListPOShippDoc",
data:{
'curr':curr
},
cache: false,
success:function(data)
{
console.log($("#shipPO").html(data));
}
});
}
else
{
$("#shipPO").prop('disabled',true);
}
// console.log("test");
});
and on php code
public function ListPOShippDoc()
{
$currency = $_POST['curr'];
$fullName = $_SESSION['fullName'];
$PONo = $this->shippDoc->ListPO($fullName,$currency)['items'];
$option .= '<option value=""></option>';
while ($val = $PONo->fetch_assoc()) {
$option .= '<option value="'.utf8_decode($val['PONo']).'">'.utf8_decode($val['PONo']).'</option>';
}
echo $option;
}
My problem is,if the PONo value like H&M-000762-001 it show on my html into H&M-000762-001.
How do i get wrong in here? Wy it show H&M-000762-001 not H&M-000762-001? Any idea?
I try utf8_decode() utf8_encode() is still same result H&M-000762-001.
function convertSymbol($value)
{
$value = mb_convert_encoding($value, "ISO-8859-1", "UTF-8");
$ampersandval = str_replace("&", "&", $value);
return $ampersandval;
}
?>
/* mb_convert_encoding this function is used to Convert ISO to UTF-8 */
Using str_replace function we can convert &amp to &

dependand dropdown filter in codeigniter using javascript

my database table
course subject is my table name
course subject
-----------------
bsc1 s1
bsc1 s2
bsc2 s3
if i select bsc1 it need to display only subject (s1,s2),if i select bsc2 it need to display only subject (s3) i.e it should corresponding values from MySQL database,please any one help me to rectify this problem. i tried i con't able to rectify.
In controller:
function studentupdate()
{
$data = array();
$exam_name = $this->input->post('exam_name');
$course_name = $this->input->post('course_name');
if($query = $this->student_model->get_exam_data())
{
$data['exam_data'] = $query;
}
if($query = $this->student_model->get_records($exam_name))
{
$data['records'] = $query;
}
if($query = $this->student_model->get_course_code_records($exam_name))
{
$data['course_records'] = $query;
}
if($query = $this->student_model->get_all_coursesubject_records($course_name))
{
$data['all_coursesubject_records'] = $query;
}
$this->load->view('student_detail_view', $data);
}
In model:
function get_all_coursesubject_records($course_name)
{
$this->db->distinct();
$this->db->select('subject_code');
$this->db->where('course_code',$course_name);
$query = $this->db->get('coursesubject');
return $query->result();
}
In view:
function get_subjectdetailsforupdate(index){
alert ("enter first inside");
var course_name = jQuery('#course_code_id'+index).val();
alert("course_name"+course_name);
var exam_name = jQuery('#exam_name_id').val();
alert("course_name"+course_name);
var ssubject_code = jQuery('#subject_code_id'+index).val();
alert("course_name"+course_name);
jQuery.ajax({
data: 'exam_name='+exam_name+'&course_name=' + course_name,
type: 'POST',
url: 'student_site/subjectfilter',
success: function(data){
console.log(data);
jQuery('#subject_code_id'+index).empty().append(data);
}
});
}
<?php
$js = 'class="dropdown_class" id="course_code_id'.$row->id.'" onChange="get_subjectdetailsforupdate()" ';
$js_name = 'course_code_id'.$row->id;
echo form_dropdown($js_name, $data, $row->course_code, $js);
?>
</td>
<td>
<?php
$js = 'class="dropdown_class" id="subject_code_id'.$row->id.'"';
$js_name = 'subject_code_id'.$row->id;
echo form_dropdown($js_name, $subject_data, $row->subject_code, $js);
?>

Categories