How to fix multiple appending in the div using jquery - javascript

I have problem regarding on appending a sample a href to the div or to the html elements, I have only 3 array response to my ajax, however the results shows duplicate item to the corresponding div. I will share to you guys my sample code that already made,
I have here my backend php:
<?php
require_once('../ConnectionString/require_db.php');
session_start();
//submit function
$status = 'Active';
$posttype_affiliation_page = 'affiliation_page';
$posttype_member_org_page = 'member_org_page';
$affiliation_member_org_content = $db->prepare('SELECT title,link,posttype FROM tblcontent
WHERE status = ? AND posttype = ? OR posttype = ? ORDER BY contentID DESC')
or die($db->error);
$affiliation_member_org_content->bind_param('sss',$status,$posttype_affiliation_page,$posttype_member_org_page);
$affiliation_member_org_content->execute();
$affiliation_member_org_content->bind_result($title,$link,$posttype);
$result = array();
while ($affiliation_member_org_content->fetch()) {
$result[] = array('title'=>$title,'link'=>$link,'posttype'=>$posttype);
header('Content-type: application/json');
}
echo json_encode($result);
?>
my front end:
$(document).ready(function(){
//mission vision
$.ajax({
url:'./Function/fetch_affiliation_member_org.php',
type:'get',
success:function(response_fetch_affiliation_member_org) {
console.log(response_fetch_affiliation_member_org);
var fetch_affiliation_member_org = jQuery.parseJSON(JSON.stringify(response_fetch_affiliation_member_org));
$.each(fetch_affiliation_member_org,function(i,data){
if(data.posttype == 'affiliation_page') {
const title = data.title;
const link = data.link;
var data = "";
data = '<p style="font-size:14px;" class="list_affiliation_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_affiliation_links').append(data);
}
else if(data.posttype == 'member_org_page') {
const title = data.title;
const link = data.link;
var data = "";
data = '<p style="font-size:14px;" class="list_member_org_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_member_org_links').append(data);
}
});
},
error:function(error) {
console.log(error);
}
});
});
My Html:
<div class="Affiliation">
<h5>Affiliation</h5>
<p style="font-size:14px;" class="list_affiliation_links">
</p>
</div>
<br>
<div class="Member">
<h5>Member Organizations</h5>
<p style="font-size:14px;" class="list_member_org_links">
</p>
</div>

$(document).ready(function(){
//mission vision
$.ajax({
url:'./Function/fetch_affiliation_member_org.php',
type:'get',
success:function(response_fetch_affiliation_member_org) {
console.log(response_fetch_affiliation_member_org);
var fetch_affiliation_member_org = jQuery.parseJSON(JSON.stringify(response_fetch_affiliation_member_org));
$.each(fetch_affiliation_member_org,function(i,data){
if(data.posttype == 'affiliation_page') {
const title = data.title;
const link = data.link;
var data = "";
$('p.list_affiliation_links').html('');
data = '<p style="font-size:14px;" class="list_affiliation_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_affiliation_links').append(data);
}
else if(data.posttype == 'member_org_page') {
const title = data.title;
const link = data.link;
var data = "";
$('p.list_member_org_links').html('');
data = '<p style="font-size:14px;" class="list_member_org_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_member_org_links').append(data);
}
});
},
error:function(error) {
console.log(error);
}
});
});
You should first clear html content and then set to DOM element. Might be it works for you.

you're appending a second p tag with your HTML that also gets selected in your append later in the code. You should only build the link withing the var data.
Greetings

Related

Woocommerce: How to show Product Attribute name and Category name on title

Using the answer provided in this thread (Woocommerce: How to show Product Attribute name on title when in a category page and "filtering" products via '?pa_attribute=' on address bar) I would like to display the category as well as the attribute name. I have a separate JS function that is currently updating the page_title when a filter is applied but that is only loading after ajax has finished. So in this event it would not load till after the filter is applied.
In the event that a user uses the nav to get to the category, currently only the attribute is displaying in the page_title. Looking to also display the category. I believe this would work out of the box if I organized my products in to subcategories but due to how the filtering is being set up I elected not to go this route. I can explain in further detail why I had to take this approach if anyone is interested.
I have left the commented out code in so that you can see the approach I was attempting to take. If this is confusing can edit it out.
add_filter( 'woocommerce_page_title', 'custom_woocommerce_page_title', 15, 2 );
function custom_woocommerce_page_title( $page_title ) {
if ( is_archive() ) {
$exists_attr = false;
foreach ( $_GET as $index => $value ) {
if ( substr( $index, 0, 3 ) === 'pa_' ) {
//$cat_id = wc_category_taxonomy_id_by_name( $index );
$attr_id = wc_attribute_taxonomy_id_by_name( $index );
if ( $attr_id === 0 && $cat_id ) {
continue;
}
if ( ! $exists_attr /* && ! $exists_cat */) {
$exists_attr = true;
//$exists_cat = true;
$page_title .= ' ';
} else {
$page_title .= ' ';
}
//$terms = get_the_terms( $post->ID, 'product_cat' );
$term = get_term_by( 'slug', esc_html( $value ), $index );
$page_title = /*$terms->name . ': ' . */ $term->name;
}
}
}
// Need to add category name after attribute term name.
return $page_title;
}
Also, I have included the JS I am using to apply page_title in the event a filter selection occurs. Ideally it would be great if I could handle it all via a JS file as I am much more familiar with JS and just starting to dive in to php. I am using the WOOF - WooCommerce Products Filter and modifying some of the code to accomplish what I need.
(function() {
var machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
var processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
var optionMachine = machineEl.querySelector("option[selected='selected']");
var optionProcess = processEl.querySelector("option[selected='selected']");
var machineValue = optionMachine.innerHTML;
var processValue = optionProcess.innerHTML;
var result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
if (machineValue != 'Product Machine' && processValue != 'Product Processing') {
result.innerHTML = machineValue + " " + processValue;
}
else if (machineValue != 'Product Machine') {
result.innerHTML = machineValue;
}
else if (processValue != 'Product Processing') {
result.innerHTML = processValue;
}
})()
So was able to get this to work by taking my JS and adding it in as a script within my functions.php. So essentially I was able to eliminate the custom_woocommerce_page_title filter.
Function.php
<?php
add_action('wp_footer', 'onLoadPageTitle');
function onLoadPageTitle() {
?>
<script>
machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
optionMachine = machineEl.querySelector("option[selected='selected']");
optionProcess = processEl.querySelector("option[selected='selected']");
if (optionMachine != null) {
machineValue = optionMachine.innerHTML;
}
else {
machineValue = "";
}
if (optionProcess != null) {
processValue = optionProcess.innerHTML;
}
else {
processValue = "";
}
result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
result.innerHTML = machineValue + " " + processValue;
</script>
<?php
}
?>
Then the woof woocommerce filter js that updates the title when a new select occurs after the AJAX.
(function() {
machineEl = document.getElementsByClassName('woof_select woof_select_pa_machine')[0];
processEl = document.getElementsByClassName('woof_select woof_select_pa_processing')[0];
optionMachine = machineEl.querySelector("option[selected='selected']");
optionProcess = processEl.querySelector("option[selected='selected']");
if (optionMachine != null) {
machineValue = optionMachine.innerHTML;
}
else {
machineValue = "";
}
if (optionProcess != null) {
processValue = optionProcess.innerHTML;
}
else {
processValue = "";
}
result = document.getElementsByClassName('woocommerce-products-header__title page-title')[0];
result.innerHTML = machineValue + " " + processValue;
})()
will probably pare it down by just calling the script function from within the woof js after ajax.

How to refer on dynamically created variables

I want to know if it is possible to refer to an dynamically created variables and if yes how?
I create on this site many forms which have p elements on the bottom is one button and if I click that button I want to transmit the variable(IdJB) which was created specific in this form.
I marked the variable with a command in the code.
$(document).ready(function() {
var Id = sessionStorage.getItem('Id');
var status = 0;
var nummer = 0;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
status: status
},
success: function(data) {
var anzahl = data;
status = 1;
while (anzahl > nummer) {
nummer++;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
nummer: nummer,
status: status
},
success: function(data) {
var Daten = JSON.parse(data);
var Ausgabebereich = document.getElementById('main');
var IdJB = Daten.id;
window.IdJB = IdJB; //This Variable !!!!!!!!!!!!!
var f = document.createElement("form");
var pInhalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.inhalt);
pInhalt.appendChild(Inhalt);
f.appendChild(pInhalt);
var pDatum = document.createElement('p');
var Inhalt = document.createTextNode(Daten.datum);
pDatum.appendChild(Inhalt);
f.appendChild(pDatum);
var pUhrzeit = document.createElement('p');
var Inhalt = document.createTextNode(Daten.uhrzeit);
pUhrzeit.appendChild(Inhalt);
f.appendChild(pUhrzeit);
var pGehalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.gehalt);
pGehalt.appendChild(Inhalt);
f.appendChild(pGehalt);
var pDauer = document.createElement('p');
var Inhalt = document.createTextNode(Daten.dauer);
pDauer.appendChild(Inhalt);
f.appendChild(pDauer);
var pAdresse = document.createElement('p');
var Inhalt = document.createTextNode(Daten.adresse);
pAdresse.appendChild(Inhalt);
f.appendChild(pAdresse);
var pNam_ersteller = document.createElement('p');
var Inhalt = document.createTextNode(Daten.nam_ersteller);
pNam_ersteller.appendChild(Inhalt);
f.appendChild(pNam_ersteller);
var bInhalt = document.createElement('button');
var Inhalt = document.createTextNode("Senden");
bInhalt.appendChild(Inhalt);
bInhalt.setAttribute("type", "button");
bInhalt.setAttribute("onclick", "zuJB()");
f.appendChild(bInhalt);
Ausgabebereich.appendChild(f);
$(document).on('click', 'button', function() {
sessionStorage.setItem('IdJB', IdJB); //Here !!!!!!!!!!!!!
alert(IdJB);
window.location = "http://localhost/jQuery&PHPnew/JobBlock.html";
});
}
})
}
}
})
$("#sub").click(function() {
window.location = "http://localhost/jQuery&PHPnew/Markt.html";
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jobs</title>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<button id="sub">Update</button>
Alle Jobs
Meine Jobs
Einstellungen
<main id="main">
</main>
</body>
</html>
This is how the Programm looks like
Don't use a global variable. Put IdJB in an attribute of the button. You can use the jQuery .data() method for this.
Also, don't add the event handler every time through the loop. When you use event delegation, you should just add the handler once.
$(document).ready(function() {
$(document).on('click', 'button', function() {
var IdJB = $(this).data("IdJB");
sessionStorage.setItem('IdJB', IdJB);
alert(IdJB);
window.location = "http://localhost/jQuery&PHPnew/JobBlock.html";
});
var Id = sessionStorage.getItem('Id');
var status = 0;
var nummer = 0;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
status: status
},
success: function(data) {
var anzahl = data;
status = 1;
while (anzahl > nummer) {
nummer++;
$.ajax({
type: "POST",
url: "http://localhost/jQuery&PHPnew/Markt.N.php",
data: {
nummer: nummer,
status: status
},
success: function(data) {
var Daten = JSON.parse(data);
var Ausgabebereich = document.getElementById('main');
var IdJB = Daten.id;
window.IdJB = IdJB; //This Variable !!!!!!!!!!!!!
var f = document.createElement("form");
var pInhalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.inhalt);
pInhalt.appendChild(Inhalt);
f.appendChild(pInhalt);
var pDatum = document.createElement('p');
var Inhalt = document.createTextNode(Daten.datum);
pDatum.appendChild(Inhalt);
f.appendChild(pDatum);
var pUhrzeit = document.createElement('p');
var Inhalt = document.createTextNode(Daten.uhrzeit);
pUhrzeit.appendChild(Inhalt);
f.appendChild(pUhrzeit);
var pGehalt = document.createElement('p');
var Inhalt = document.createTextNode(Daten.gehalt);
pGehalt.appendChild(Inhalt);
f.appendChild(pGehalt);
var pDauer = document.createElement('p');
var Inhalt = document.createTextNode(Daten.dauer);
pDauer.appendChild(Inhalt);
f.appendChild(pDauer);
var pAdresse = document.createElement('p');
var Inhalt = document.createTextNode(Daten.adresse);
pAdresse.appendChild(Inhalt);
f.appendChild(pAdresse);
var pNam_ersteller = document.createElement('p');
var Inhalt = document.createTextNode(Daten.nam_ersteller);
pNam_ersteller.appendChild(Inhalt);
f.appendChild(pNam_ersteller);
var bInhalt = document.createElement('button');
var Inhalt = document.createTextNode("Senden");
bInhalt.appendChild(Inhalt);
bInhalt.setAttribute("type", "button");
bInhalt.setAttribute("onclick", "zuJB()");
f.appendChild(bInhalt);
$(bInhalt).data('IdJB', IdJB);
Ausgabebereich.appendChild(f);
}
})
}
}
})
$("#sub").click(function() {
window.location = "http://localhost/jQuery&PHPnew/Markt.html";
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jobs</title>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<button id="sub">Update</button>
Alle Jobs
Meine Jobs
Einstellungen
<main id="main">
</main>
</body>
</html>
I may be misunderstanding your question, but if not: In order to reference dynamically created elements, the click handler just needs to be instantiated after the element is created and put in the DOM. An easy way to handle this is by having a function generate your tag like so:
function appendTag(parent, child){
parent.append(child)
child.click(function(){
//Click code here
});
}
So it looks like when you are adding the button click event dynamically you are adding it to all the buttons on the page. This is why when you click one it runs 3 times.
This can be seen by the button text in this line of code:
$(document).on('click', 'button', function() {
.....
});
To address this problem you need to make the click listener specific to the button. You can do that by making a more specific button selector. Although it's not a perfect solution one way to do this is to give each button a unique I'd. Something like button-## where ## here is a different number each time you create a new button. You can then do:
$(document).on('click', '#button-##', function() {
.....
});
Again replacing ## with the corresponding Id value.
Edit: actually you can use the answer #Laif posted by rather than using the $(document).on( call just simply do b.click()

JavaScript $.GET not passing through

I am building a very simple chat application, nothing too fancy just a way for multiple users to chat at once.
The problem I am having is that whilst I can read and display messages from the database, no new messages will get inserted.
I am using JavaScript to pass a $.Get with the message and the username. I have checked the console and there is no errors showing but I have an undefined index: text and undefined index: username when I use POSTMAN to test.
Can anyone help push me in the right direction to solve this?
chat.php
<div class="wrapper">
<p id='chat-user'> </p>
<div id='chat-area'></div>
<form id='send-message-area'>
<textarea name="the-textarea" id="the-textarea" maxlength="150" placeholder="Start Typing..."autofocus></textarea>
</form>
<button id='chatSend' class="btn btn-info" type="submit">Post New Message</button>
<div id="the-count">
<span id="current">0</span>
<span id="maximum">/ 150</span>
</div>
</div>
var name = prompt("Enter your name:", "Guest");
if (!name || name === ' ') {
name = "Guest";
}
window.onload = function () {
document.getElementById("chat-user").innerHTML = "Your are: " + name;
};
$(document).ready(function () {
var chatInterval = 250;
var $chatOutput = $("#chat-area");
var $chatInput = $("#the-textarea");
var $chatSend = $("#chatSend");
function sendMessage() {
var chatInputString = $chatInput.val();
$.GET("testProcess.php", {
username: name,
text: chatInputString
});
retrieveMessages();
}
process.php
<?php
error_reporting(E_ALL);
include ("connection.php");
$username = substr($_GET["username"], 0, 32);
$text = substr($_GET["text"], 0, 150);
$nameEscaped = htmlentities(mysqli_real_escape_string($conn, $username));
$textEscaped = htmlentities(mysqli_real_escape_string($conn, $text));
$timestamp = date("Y-m-d H:i:s");
$insertMessage = "INSERT INTO message (messageID, messageBody, timeSent, nickname, sent) VALUES ('', '$textEscaped', '$timestamp', '$nameEscaped')";
$result = mysqli_query($conn, $insertMessage);
Your postman request is wrong as shown in the picture
you are passing the param GET with the value send but in your php script you have $_GET["username"] and $_GET["text"] the method GET is already set in the left side of the url in the picture so you dont need to send it what you want to send is the param username and text so the url would look like this
http://xxxxxxx/testProcess.php?username=Guest&text=test
as for your javascript code the jquery method for get is $.get and not $.GET and you are missing a way to handle the submit of the form because your submit button is outside of the form so a correct way to this would be
var name = prompt("Enter your name:", "Guest");
if (!name || name === ' ') {
name = "Guest";
}
window.onload = function() {
document.getElementById("chat-user").innerHTML = "Your are: " + name;
};
$(document).ready(function() {
var chatInterval = 250;
var $chatOutput = $("#chat-area");
var $chatInput = $("#the-textarea");
var $chatSend = $("#chatSend");
//intercepting the submit event to call the sendMessage function
$("#send-message-area").on("submit", function(e) {
e.preventDefault();
sendMessage()
})
function sendMessage() {
var chatInputString = $chatInput.val();
$.get("testProcess.php", {
username: name,
text: chatInputString
});
retrieveMessages();
}
})

Alternative to AJAX setTimeout?

I have a script that uses ajax to retrieve PHP data for video files on my server (godaddy shared hosting), and then play the video file on my php page if it is the highest ranked video, like so:
<script id="source" language="javascript" type="text/javascript">
$(function refreshscreen ()
{
$.ajax({
url: 'screen.php',
data: "",
pass to api.php
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
var votes = data[2];
var video = data[3];
var image = data[4];
$('.screen').hide(); $("#video"+id+"").show();
var whichvideo = "thevideo" + id;
var videoplay = document.getElementById(whichvideo);
var killvideo = document.getElementsByClassName('videobg');
var allvideos = document.getElementsByClassName("videobg");
for(var x=0; x < allvideos.length; x++)
{
var allvideosid = document.getElementById(allvideos[x]);
if ($(allvideos[x]).attr("id") == whichvideo) {
allvideos[x].play();
} else {
allvideos[x].pause();
}
}
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(refreshscreen, 5000);
}
});
});
And then the screen.php referenced above:
<?php
$host = "localhost";
$user = "myuserhere";
$pass = "mypasshere";
$databaseName = "mydbnamehere";
$tableName = "mytablenamehere";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName ORDER BY votes DESC");
$array = mysql_fetch_row($result);
echo json_encode($array);
?>
This all works fine, and the video switches as it should when a new higher ranked video is voted in, however, periodically, the video will freeze when playing, completely at random. My guess is that we are overloading the server with the setTimeout function of the ajax script, so I am wondering if there is a way I can clean up this script to avoid the freezing, or an alternative method.
Thanks in advance.
I've cleaned up the code:
var currentID = -1;
function refreshscreen() {
$.getJSON('screen.php', data => {
var topID = data[0];
// Schedule the next request
setTimeout(refreshscreen, 5000);
if (topID === currentID) return; // top rated video hasn't changed
$('.screen').hide();
$("#video" + topID).show();
var pauseID = "thevideo" + currentID;
var playID = "thevideo" + topID;
$(".videobg").each(function() {
if (this.id === pauseID) this.pause();
if (this.id === playID) this.play();
});
currentID = topID;
});
}
$(document).ready(function () {
refreshscreen();
});
The biggest change is keeping track of the currently playing video and exiting right away if it hasn't changed. Other than that I got rid of all the unused variables and used jQuery throughout. This should be much easier to debug at the least and might fix the error to boot.

Placing the errors in its respective div

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);

Categories

Resources