Here i am getting my Error Messages from a separate page and i am displaying it in a a div called #stage_error
$('#stage_error').html(error_string);
So, the errors will be displayed like this
The bus no field is required.
The comp id field is required.
The total seats field is required.
But what i want is to display the errors in its respective div's
i.e., the Bus no should be displayed near the div <div id='busno'> like this.
How can i do that ?
Json :
{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
Update :
Script for request and showing error :
<script>
$(document).ready(function() {
$("#driver").click(function(event) {
var BusNo = $("#BusNo").val();
var CompID = $("#CompID").val();
var TotalSeats = $("#TotalSeats").val();
var _token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
},
function(data) {
if (data != '') {
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
});
$('#stage_error').html(error_string);
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
</script>
Laravel Controller :
public function managebusregister()
{
$BusNo = Input::get('BusNo');
$CompID = Input::get('CompID');
$TotalSeats = Input::get('TotalSeats');
$data = Input::except(array('_token')) ;
$rule = array(
'BusNo' => 'required|unique:company_bus',
'CompID' => 'required',
'TotalSeats' => 'required|max:50'
) ;
$validator = Validator::make($data,$rule);
if ($validator->fails())
{
$messages = $validator->messages();
return json_encode($validator->messages()); //php encoded value
}
else
{
DB::insert('insert into company_bus (BusNo, CompID, TotalSeats) values (?, ?, ?)',
array($BusNo, $CompID, $TotalSeats));
return '';
}
}
Html Code :
<div id="stage_error" style="color:red;font-size:15px"></div>
<div id="stage_success" style="color:green;font-size:20px"></div>
and beyond that i have each field input boxes,
<input type="text" id="BusNo" name="BusNo"/>
<input type="text" id="CompID" name="CompID"/>
How can i throw error messages near the respective fields
Below is the approach: Observe I've added spans with error after text boxes.
CSS
<style>
.error { color:red; font-size:15px; }
</style>
Html
<input type="text" id="BusNo" name="BusNo" /><span class="error"></span>
<input type="text" id="CompID" name="CompID" /><span class="error"></span>
JavaScript I did some changes as per the jQuery standard, it should work well, if you're not interested then you can ignore all the changes but can take only below mentioned if logic block.
The error display added in if (!data) {...}
$(function () {
$(document).on("click", "#driver", function (event) {
var BusNo = $("#BusNo").val(),
CompID = $("#CompID").val(),
TotalSeats = $("#TotalSeats").val(),
_token = $("#_token").val();
$.post("managebus_register", {
_token: _token,
BusNo: BusNo,
CompID: CompID,
TotalSeats: TotalSeats
}).done(function (data) {
$("span.error").empty();//All previous error messages cleared here.
if (!data) {
var obj = JSON.parse(data);
//obj = {"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}
$.each(obj, function (entry) {
var targetSelector='';
if (entry == "busno") {
targetSelector = "#BusNo";
}
if (entry == "Comp Id") {
targetSelector = "#CompID";
}
if(targetSelector) //Here we're setting error message for respective field
$(targetSelector).next("span.error").html(obj[entry]);
});
} else {
$('#stage_success').text('Resistered Succesfully');
$("#stage_error").hide();
}
});
});
});
you can try like this:
var json = JSON.parse('{"busno":["Bus No field is required"],"Comp Id":["Comp Id is required."]}');
// alert(json['busno']);
$("#busno").html(json.busno);// like this for others also.
change here:
obj = JSON.parse(data);
var error_string = '';
$.each(obj, function(entry) {
error_string += obj[entry] + '<br/>';
if(entry == 'busno'){
$("#busno").html(obj[entry]);// like this for others also.
}
if(entry == 'Comp Id'){
$("#compid").html(obj[entry]);// like this for others also.
}
});
$('#stage_error').html(error_string);
Related
So I'm trying to build a JS script that allows me to automatically enroll in courses in uni once they're available, and what I've gotten so far is filling the boxes with course IDs and then clicking submit but then I realized using ajax to post would be a better way than simulating a click.
The problem is, the returned html after a post is just a normal html with no success msg on enrolling neither failure. Here is my code:
const courses = ['56895', '56712', '56812']
function findnewreg() {
var index = 0
courses.forEach(element => {
index++;
var ind = "crn_id" + index;
document.getElementById(ind).value = element
form = document.getElementById(ind).form
});
var regbtn = document.getElementsByName('REG_BTN')
regbtn.forEach(element =>{
if(element.value=='تنفيذ التغييرات'){
//element.click();//<form action="/PROD/xwckcoms.P_Regs" method="post" onSubmit="return checkSubmit()">
submitForm()
console.log("clicked")
document.addEventListener("DOMContentLoaded", function(event){
if (document.body.textContent.includes("لقد قمت بإجراء العديد من المحاولات لتسجيل هذا الفصل الدراسي، اتصل بمكتب التسجيل للحصول على مساعدة. ")) {
console.log('⛔️ error retrying...');
//history.back();
findnewreg()
}else{
console.log('✅ success');
}});
}
})
}
function submitForm(){
var form = form = document.getElementById("crn_id1").form
var href = '/PROD/xwckcoms.P_Regs'//form.getAttribute("action");
var formData = {};
jQuery(form)?.find("input[type=text]").each(function (index, node) {
console.log(index, node)
formData[node.name] = node.value;
});
// formData = jQuery(form).serialize() //also tried this, same result
jQuery.post(href, formData).done(function (data) {
prompt('DATA:' , data)
findnewreg();
});
}
findnewreg();
I'm trying to show an alert every time customer is trying to add variant quantity that is bigger than available quantity. When that's happens I see 422 response from add.js -
{status: 422, message: "Cart Error",…}
description: "All 1 Black Basic High Waisted Briefs - black / 1 are in your cart."
message: "Cart Error"
status: 422
I need to display the description for customers, how that is possible?
Here is my code -
var shopifyAjaxAddURL = '/cart/add.js';
var shopifyAjaxCartURL = '/cart.js';
var shopifyAjaxStorePageURL = '/search';
$(document).on('submit', 'form[action="/cart/add"]:not(.noAJAX, .feedback-go_to_cart)', function(e) {
var $form = $(this);
//Add to cart
$.post(shopifyAjaxAddURL, $form.serialize(), function(itemData) {
//Enable add button
$btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }});
setTimeout(function(){
//Not added, show message
if(typeof(data) != 'undefined' && typeof(data.status) != 'undefined') {
var jsonRes = $.parseJSON(data.responseText);
window.showQuickPopup(jsonRes.description, $btn);
} else {
//Some unknown error? Disable ajax and submit the old-fashioned way.
$form.addClass('noAJAX');
$form.submit();
}
});
Your code seems bit buggy. Possible solution could be, check if the status is 422 and send the customer an alert message.
if( itemData.status === 422 ) { alert('Quantity not available in the inventory') }
Full code might look like:
var shopifyAjaxAddURL = '/cart/add.js';
var shopifyAjaxCartURL = '/cart.js';
var shopifyAjaxStorePageURL = '/search';
$(document).on('submit', 'form[action="/cart/add"]:not(.noAJAX, .feedback-go_to_cart)', function (e) {
var $form = $(this);
//Add to cart
$.post(shopifyAjaxAddURL, $form.serialize(), function (itemData) {
if( itemData.status === 422 ) { alert('Quantity not available in the inventory') }
else {
//Enable add button
$btn.html(theme.icons.tick + ' ' + {{ 'products.product.added_to_cart' | t | json }});
setTimeout(function () {
//Not added, show message
if (typeof (data) != 'undefined' && typeof (data.status) != 'undefined') {
var jsonRes = $.parseJSON(data.responseText);
window.showQuickPopup(jsonRes.description, $btn);
} else {
//Some unknown error? Disable ajax and submit the old-fashioned way.
$form.addClass('noAJAX');
$form.submit();
}
}
});
I have chat on Socket.IO, MySQL, PHP. Everything is working good, but i need download and diplay messages history when you update the page.
php code:
<script>var USER = {"id":"<?php echo $_SESSION['steamid']?>","login":"<?php echo $_SESSION['personaname']?>","image":"<?php echo $_SESSION['avatarmedium']?>","hash":"<?php echo md5($_SESSION['steamid']) ?>"};</script>
js site code:
var messageTpl = _.template($("#chat-message").html());
function sendMessage(text) {
socket.emit('message', {user: USER, message: text});
}
var lastUser = null;
function addMessage(data, checkLast) {
var a = $("#chatScroll")[0];
var isScrollDown = (a.offsetHeight + a.scrollTop) == a.scrollHeight;
if (checkLast && lastUser && lastUser.id == data.user.id) {
$('.chatMessage').last().find('.body').append('<br/>' + _.escape(data.message))
}
else {
console.log(data);
data.user.url = 'http://steamcommunity.com/profiles/' + data.user.id;
data.user.image = 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/' + _.escape(data.user.image).replace('_medium', '');
var html = messageTpl(data);
$('#messages').append(html);
if ($('.chatMessage').length > 100) {
$('.chatMessage').eq(0).remove();
}
}
lastUser = data.user;
if (isScrollDown) a.scrollTop = a.scrollHeight;
$("#chatScroll").perfectScrollbar();
}
socket.on('online', function(data) {
$('#online').text(data.online);
});
socket.on('chat-message', function(data) {
addMessage(data, true);
});
socket.on('chat-history', _.once(function(data) {
$("#chatScroll").perfectScrollbar();
if (data) _.each(data, addMessage);
}));
function addMessage works good, but with socket.on('chat-history') i got error
Uncaught TypeError: Cannot read property 'id' of undefined
js server code:
connection.query('SELECT * FROM cs_chat ORDER BY id DESC LIMIT 50', function(error, rows) {
if(!error) {
var user = [];
rows.forEach(function (data) {
user.push(data);
});
console.log(user);
socket.emit('chat-history', {user: JSON.stringify(user)});
} else {
console.log(error.message);
}
});
when you refresh the page - all last messages lost
console.log server js rows.forEach below.
[{"id":668,"message_text":"3qwe","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:15.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":667,"message_text":"12312","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:14.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":666,"message_text":"213123","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:14.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":665,"message_text":"cvb","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":664,"message_text":"cvb","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":663,"message_text":"g","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":662,"message_text":"gdf","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":661,"message_text":"df","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"}]
I have 5 regions: Region1, Region2, Region3, Region4, Region5.
Within each region is a number of Proctors (for testing): For Region1 -- Mary, Jack, and Mark
When a student takes a test, a generated email is sent to all the Proctors in that Region. This is currently handled by a JSON file. I'd like for it to be handled by a table in the database. Here is the code related to gathering the information from the JSON file:
function get_region_proctors($region) {
global $CFG;
$rval = array();
$json_raw = file_get_contents($CFG->dirroot . DIRECTORY_SEPARATOR . 'jca' . DIRECTORY_SEPARATOR . 'data.json');
if (empty($json_raw)) {
throw new Exception("Unable to get json from data.json");
}
$json_data = json_decode($json_raw);
foreach($json_data->proctors as $p) {
if ($p->region == $region) {
$rval[] = $p;
}
}
return $rval;
}
Here is what the JSON file looks like:
{
"proctors" : [
{
"region" : "Region1",
"name" : "Mary Edwards",
"email" : "medwards#example.com"
},
{
"region" : "Region1",
"name" : "Jack Phillips",
"email" : "jphillips#example.com"
},
{
"region" : "Region1",
"name" : "Mark Jensen",
"email" : "mjensen#example.com"
}
]
}
The question is: how do I get the code to look at a database (array) instead of the DATA.JSON file?
EDIT:
After I used the code suggested below, I found that when I went to view or edit the Proctor list there was a javascript file that seems to do the following:
Once a Proctor is chosen, the javascript automatically sets the Region. Here's the script (I am not a javascript pro):
var proctors = [];
$(function () {
//disable region sel as proctor sel will control
$('#id_profile_field_Region').attr('disabled', 'disabled');
$('#mform1').submit(function () {
//need to reenable so php will note changes
$('#id_profile_field_Region').attr('disabled', false);
})
$.getJSON('../jca/data.json', function(json) {
proctors = json.proctors;
}).error(function() { alert("There was an error loading json. "); });
$('#id_profile_field_Proctor').change(function () {
newProctorSelected($(this).find("option:selected").text());
})
});
function newProctorSelected(pName) {
//find proctor object from json
var p = null;
for (var i = 0; i < proctors.length; i++) {
if (proctors[i].name === pName) {
p = proctors[i];
break;
}
}
if (p) {
//set the value of region based on region name of proctor
$('#id_profile_field_Region option').each(function() {
if($(this).text() === p.region) {
this.selected = true;
return;
}
});
}
else {
alert("proctor not found");
}
}
I keep getting the error message "There was an error loading JSON". Is there a way to replicate this function in PHP?
If you have a table called mdl_local_proctors with id, region, name, email
Then just use
function get_region_proctors($region) {
global $DB;
return $DB->get_records('local_proctors', array('region' => $region));
}
I'm trying to perform a search of database when user enters a persons name into textbox. The texboxes are dynamic, so whenever the user enters a number into the "No. of firemen on scene" textbox as seen in the snap shot below, the same amount of textboxes appear in the fieldset below under("List of firemen on scene").
However, my problem is that whenever I'm trying to perform the search, the search is only performed on the first textbox and not on the others. Could anyone assist me as to highlighting and/or explaining what the problem(s) may be?
occurrence.php
<label>List of Firemen On Scene</label><br>
<div class="NewlyCreatedSelectBoxes" name="firemen_list"></div>
search.php
<?php
require('connectdb.php');
if(isset($_POST['search_term']))
{
$search_term = mysql_real_escape_string(htmlentities($_POST['search_term']));
if(!empty($search_term))
{
$search = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName` FROM `firefighterinfo` WHERE `firstName` LIKE '%$search_term%'");
$result_count = mysql_num_rows($search);
$suffix = ($result_count != 1) ? 's' : '';
echo '<p>Your search for ', $search_term, ' returned ', $result_count, ' result', $suffix, '</p>';
while($results_row = mysql_fetch_assoc($search))
{
echo '<p>', $results_row['firstName'], ' ', $results_row['middleName'], ' ', $results_row['lastName'], '</p>';
}
}
}
?>
search.js
function firemanAddingTextBoxes() {
var NumOfText = $("#NumOfTextBoxes").val();
$('.NewlyCreatedSelectBoxes').empty();
var txtBox = "";
for (i = 0; i < NumOfText; i++) {
txtBox += '<input type="text" name="fireman[]" id="search" required/><br>';
}
$('.NewlyCreatedSelectBoxes').append(txtBox);
$('#search').keyup(function () {
var search_term = $(this).val();
$('#search_results').html('Searching database...');
if (search_term !== '') {
$.post('php/fireman_search.php', { search_term: search_term }, function (data) {
$('#search_results').html(data);
});
} else {
$('#search_results').html('Not Found');
}
});
return false;
}
Since the other field is dynamic, you'll need to use event delegation on the search inputs. Also, you're adding elements with duplicate ID's, which is bad. ID's have to be unique, just use classes for this:
for (i = 0; i < NumOfText; i++) {
txtBox += '<input type="text" name="fireman[]" class="search" required/><br>';
}
Change:
$('#search').keyup(function () {
To:
$(".NewlyCreatedSelectBoxes").on("keyup", ".search", function() {