If condition not working in server - javascript

If condition to equal two string values in javascript is not working in server, but its working in localhost. Given below is my code.
var res_id = $(this).attr('name');
var fld_id = $(this).attr('id');
var ans = $('#'+fld_id).attr('value');
//var mod_id = $('#mod_id').attr('value');
//alert(typeof(ans));
$.post("multiple_check_answer.php", { resid: res_id, answ: ans}, function(data){
//alert(typeof data);
if(ans==data)
{
//alert(data);
$('#span_'+res_id+'_'+ans).css({'color':'green', 'font-weight':'bold'});
}
else
{
$('#span_'+res_id+'_'+ans).css({'color':'red', 'font-weight':'bold'});
$('#span_'+res_id+'_'+data).css({'color':'green', 'font-weight':'bold'});
}
});
for ex. if ans and data values are A but its showing red color.

Here is the new code which is working fine. Changed data value to integer.
$("input[type=radio]").click(function(){
var res_id = $(this).attr('name');
var fld_id = $(this).attr('id');
var ans = $('#'+fld_id).attr('value');
//var mod_id = $('#mod_id').attr('value');
//alert(ans);
$.post("multiple_check_answer.php", { resid: res_id, answ: ans}, function(data){
//alert(data);
if(data==1)
{
//alert(data);
$('#span_'+res_id+'_'+ans).css({'color':'green', 'font-weight':'bold'});
//$('#dis_msg'+res_id).html('<strong style="color:green">Your Answer is Correct</strong>');
}
else
{
$('#span_'+res_id+'_'+ans).css({'color':'red', 'font-weight':'bold'});
$('#span_'+res_id+'_'+data).css({'color':'green', 'font-weight':'bold'});
//$('#dis_msg'+res_id).html('<strong style="color:red">Your Answer is In-Correct</strong>');
}
});
});

Related

Unable to see the source of the problem with the code for sending data to PHP file

I am very sorry to appear much ignorant but I have experienced this problem for long and I am now completely unable to understand why my JQuery function is not working.
I need this code to send data to PHP file which I am sure its working. I have tried to code everything with php but I have found there are place that I will have to include ajax.
$(document).ready(function(){
$('#sending').on('submit', function(event){
event.preventDefault();
if(($('#receiver_id1').val() == '0') && ($('#receiver_id2').val() == '0') && ($('#receiver_id3').val() == '0'))
{
alert("Please fill in the recipient!");
return false;
}
else if($.trim($("#message").val()) == '')
{
alert("You cannot send an empty message.");
return false;
}
else if($('#subject').val() == '')
{
var retVal = confirm("Are you sure to send a message without a subject?");
if( retVal == true ) {
var receiver_id1 = $('#receiver_id1').val();
var receiver_id2 = $('#receiver_id2').val();
var receiver_id3 = $('#receiver_id3').val();
var receiver_name1 = $('#receiver_id1').text();
var receiver_name2 = $('#receiver_id2').text();
var receiver_name3 = $('#receiver_id3').text();
var from_user_name = '<?php echo $from_user_name;?>';
var from_user_id = '<?php echo $from_user_id;?>';
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url:"messaging.php",
type:"POST",
data:{receiver_id1:receiver_id1, receiver_id2:receiver_id2, receiver_id3:receiver_id3, receiver_name1:receiver_name1, receiver_name2:receiver_name2, receiver_name3:receiver_name3, subject:subject, message:message},
success:function(data)
{
$('#receiver_id1').val("0");
$('#receiver_id2').val("0");
$('#receiver_id3').val("0");
$('#subject').val("");
$('#message').val("");
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
type:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#popup').modal("show");
}
});
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
} else {
return false;
}
} else
{
var receiver_id1 = $('#receiver_id1').val();
var receiver_id2 = $('#receiver_id2').val();
var receiver_id3 = $('#receiver_id3').val();
var receiver_name1 = $('#receiver_id1').text();
var receiver_name2 = $('#receiver_id2').text();
var receiver_name3 = $('#receiver_id3').text();
var from_user_name = '<?php echo $from_user_name;?>';
var from_user_id = '<?php echo $from_user_id;?>';
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url:"messaging.php",
type:"POST",
data:{receiver_id1:receiver_id1, receiver_id2:receiver_id2, receiver_id3:receiver_id3, receiver_name1:receiver_name1, receiver_name2:receiver_name2, receiver_name3:receiver_name3, from_user_name:from_user_name, from_user_id:from_user_id, subject:subject, message:message},
success:function(data)
{
$('#receiver_id1').val("0");
$('#receiver_id2').val("0");
$('#receiver_id3').val("0");
$('#subject').val("");
$('#message').val("");
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
method:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#popup').modal("show");
}
});
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
}
});
});
I really need help. I absolutely need this script to work. Thanks in advance.

jQuery consolidate code into one function

Is it possible to consolidate the two sections of code below. If you look at each section you will notice they are almost identical. I have another 3 or 4 sections of code which are also identical. I'm wondering if there's a neater way for me to use the same code?
$("#agencies").on("click", ".applyClick", function(event) {
event.stopPropagation();
event.preventDefault();
var target = $(this);
var currentParent = $(this).closest('tr');
var id = currentParent.attr('id');
var items = $("input,select,textarea", currentParent);
var strData = items.serialize() + '&id=' + id;
$.post("agencies.php", strData, function(data) {
var data = $.parseJSON(data);
if(data.redirect_location){
window.location = data.redirect_location;
}
else{
var type = data.type;
var result = $.map(data, function(val,index) {
if(index != 'type'){
var str = val;
}
return str;
}).join("<br>");
if(type == 'error'){
alert(result);
}
else{
$("div#messages").html('<div class="'+ type +'-message">' + result + '</div>').slideDown("slow");
closeRow('quit', target);
}
}
});
});
$("#builders").on("click", ".applyClick", function(event) {
event.stopPropagation();
event.preventDefault();
var target = $(this);
var currentParent = $(this).closest('tr');
var id = currentParent.attr('id');
var items = $("input,select,textarea", currentParent);
var strData = items.serialize() + '&id=' + id;
$.post("builders.php", strData, function(data) {
var data = $.parseJSON(data);
if(data.redirect_location){
window.location = data.redirect_location;
}
else{
var type = data.type;
var result = $.map(data, function(val,index) {
if(index != 'type'){
var str = val;
}
return str;
}).join("<br>");
if(type == 'error'){
alert(result);
}
else{
$("div#messages").html('<div class="'+ type +'-message">' + result + '</div>').slideDown("slow");
closeRow('quit', target);
}
}
});
});
I will recomend to add attribute to your buttons like this
<input type="button" data-url="agencies" id="agencies" />
<input type="button" data-url="builders.php" id="builders" />
and same code like this
$("#agencies, #builders").on("click", ".applyClick", function(event) {
var url = $(this).attr('data-url');
....
$.post(url, strData, function(data) {
...
...
});
This question is in the margins of Code Review and SO.
The only difference between the two handlers appears to be the .post URL, and that appears to be derivable from the ID of the click target.
So do a little string handling to build the URL and attach your modified function as click handler to both elements :
$("#agencies, #builders").on("click", ".applyClick", function(event) {
...
$.post(this.id + '.php', strData, function(data) {
...
}

Explanation of phantomjs code

I was asked to work on web crawler using phantomjs. However, as I read through the example, I was puzzled by some of the code:
Is this a loop? $("table[id^='post']").each(function(index)
What does this line of code mean? var entry = $(this);
How is the id captured? var id = entry.attr('id').substring(4);
This line var poster = entry.find('a.bigusername'); tries to get a username from the page. Is there a tutorial on how to make use of entry.find to scrap data off the page?
page.open(url1, function (status) {
// Check for page load success
if (status !== "success") {
console.log("Unable to access network");
phantom.exit(231);
} else {
if (page.injectJs("../lib/jquery-2.1.0.min.js") && page.injectJs("../lib/moment-with-langs.js") && page.injectJs("../lib/sugar.js") && page.injectJs("../lib/url.js")){
allResults = page.evaluate(function(url) {
var arr = [];
var title = $("meta[property='og:title']").attr('content');
title = title.trim();
$("table[id^='post']").each(function(index){
var entry = $(this);
var id = entry.attr('id').substring(4);
var poster = entry.find('a.bigusername');
poster = poster.text().trim();
var text = entry.find("div[id^='post_message_']");
//remove quotes of other posts
text.find(".quote").remove();
text.find("div[style='margin:20px; margin-top:5px; ']").remove();
text.find(".bbcode_container").remove();
text = text.text().trim();
var postDate = entry.find("td.thead");
postDate = postDate.first().text().trim();
var postUrl = entry.find("a[id^='postcount']");
if (postUrl){
postUrl = postUrl.attr('href');
postUrl = URL.resolve(url, postUrl);
}
else{
postUrl = url;
}
if (postDate.indexOf('Yesterday') >= 0){
postDate = Date.create(postDate).format('{yyyy}-{MM}-{dd} {HH}:{mm}');
}
else if (postDate.indexOf('Today') >= 0){
postDate = Date.create(postDate).format('{yyyy}-{MM}-{dd} {HH}:{mm}');
}
else{
var d = moment(postDate, 'DD-MM-YYYY, hh:mm A');
postDate = d.format('YYYY-MM-DD HH:mm');
}
var obj = {'id': id, 'title': title, 'poster': poster, 'text': text, 'url': postUrl, 'post_date' : postDate, 'location': 'Singapore', 'country': 'SG'};
arr.push(obj);
});
return arr;
}, url);
console.log("##START##");
console.log(JSON.stringify(allResults, undefined, 4));
console.log("##END##");
console.log("##URL=" + url);
fs.write("../cache/" + encodeURIComponent(url), page.content, "w");
phantom.exit();
}
}
});
Is this a loop? $("table[id^='post']").each(function(index)?
Yes
What does this line of code mean? var entry = $(this);
It assigns a jQuery object to variable entry
How is the id captured? var id = entry.attr('id').substring(4);
It uses jQuery which has attr() function.

fuzzy search (fuse.js) using XML instead of JSON

Is it possible to use like fuse.js with an XML document instead of JSON? As it is now I only have an XML document with data and hope that I shouldn't make a new version as well for JSON.
Hope someone can help me out which direction I can/should go.
Kind regards,
Niels
Found the solution myself. Instead of the example with JSON placed on http://kiro.me/projects/fuse.html, here is the version with an XML call instead :)
$(function() {
function start(books) {
var $inputSearch = $('#hero-search'),
$results = $('#results ul'),
$authorCheckbox = $('#value'),
$titleCheckbox = $('#typeId'),
$caseCheckbox = $('#case'),
searchAuthors = true,
searchTitles = false,
isCaseSensitive = false,
fuse;
function search() {
$results.empty();
$.each(r, function(i, val) {
$resultShops.append('<li class="result-item"><span><img src="' + this.statusId + '" /></span> ' + this.value + '</li>');
});
}
function createFuse() {
var keys = [];
if (searchAuthors) {
keys.push('value');
}
if (searchTitles) {
keys.push('typeId');
}
fuse = new Fuse(books, {
keys: keys,
caseSensitive: isCaseSensitive
});
}
$inputSearch.on('keyup', search);
createFuse();
}
$.ajax({
type: 'GET',
dataType: 'xml',
url: 'xml-document/document.xml',
success: function(response) {
var suggestions = [];
$(response).find("searchResults").children().each(function(i, elm) {
var name = $(elm).find('name').text();
var url = $(elm).find('url').text();
var description = $(elm).find('description').text();
var statusId = $(elm).find('status').text();
var typeId = $(elm).find('type').text();
var result = {};
result.value = name;
result.url = url;
result.description = description;
result.statusId = statusId;
result.typeId = typeId;
suggestions.push(result);
});
start(suggestions);
},
error: function(response) {
console.log('failure',response);
}
});
});

Illegal invocation when using toArray

I don't have very much to my code but I seem to be getting Illegal invocation with my order variable - works fine and shows in console.log if I comment it out
$('body').on("click", "#brands_by_category_submit_btn", function (e) {
e.preventDefault();
var self = $(this);
var order = $(".order").toArray();
var id = $("#manID").data("id");
var brand_name = $("#brand_name").data("id");
var data = grabData(true);
if(data.length)
{
var data_array = {
id : id,
brand_name : brand_name,
cat_id : data,
order : order,
state : 1
};
var url = $("#brands_by_category_submit_btn").data("url");
//console.log(data_array);
ajaxCall(url, data_array);
alert("Categories Updated");
}
});
AjaxCall:
function ajaxCall(url, data_array, div_id, callback_fn) {
return $.ajax({
type:'POST',
url:url,
beforeSend: function(){
$("#" + div_id).html("<img src='http://www.#.co.nz/files/large/ajax-loader.gif' alt='Loading..' title='Loading..'/>");
},
data:data_array,
complete:function (data) {
$("#" + div_id).html(data.responseText);
if(callback_fn != null)
{
eval(callback_fn + '()');
}
}
});
}
Your problem is that you're converting an array of HTML elements into POST data which simply isn't possible. You should instead loop through your elements and grab their .text() property:
var self = $(this);
var order = []; //or "new Array()". Whatever you prefer for readability
$(".order").each(function() {
order.push($(this).text());
});
var id = $("#manID").data("id");
var brand_name = $("#brand_name").data("id");
var data = grabData(true);

Categories

Resources