jQuery adding CSS class to dynamically created elements - javascript

I know this question has been asked before but I have some serious weird behaviour here...
I have a DIV containing a list of anchors which are pulled via ajax from a php file (mysqli). I can dynamically add, edit and delete the items (categories) on this list. This works fine. It looks like this:
However, after a category is created I want to automatically select it. Same goes for edited categories.
And, after the page first loads, the category "Alle" should be selected by default.
I have an external categories-management.js file which contains these functions amongst other things:
function selectRootCategory () {
selectedcategoryname = "Alle";
categegorySelected = 0;
$("#training_management_categories_items>ul>li>a").removeClass('categories_selected');
$('#training_management_categories_list_a_all').addClass('categories_selected');
}
function selectEditedCategory() {
categorySelected = 1;
categoryid = 'training_management_categories_list_a_' + selectedcategoryid.toString();
$("#training_management_categories_items>ul>li>a").removeClass('categories_selected');
$('#'+categoryid).addClass('categories_selected');
}
On the main page I call this function:
$(document).ready(function() {
GetCategories();
CheckIfCategoryChecked();
selectRootCategory();
});
So basically, what should happen when the page first loads, the category "Alle" should be selected. This doesn't work though.
I would think I got the function wrong, BUT if I delete an Item, the selectRootCategory()-function is called, too and then it works. This is the function in which it works (housing in categories-management.js, too):
function submitDeleteCategory() {
var url = './ajax/training_management_data.php';
$('#delete_category_dialog_error').hide();
$.ajax({
url: url,
type: "POST",
data: {
action: 'delete_category',
category_id: selectedcategoryid,
},
dataType: 'JSON',
success: function (data) {
if (data == 'success') {
GetCategories();
CheckIfCategoryChecked();
selectRootCategory(); //THIS WORKS
categorySelected = 0;
$('#delete_category_dialog').dialog('close');
}
else {
$('#delete_category_dialog_error').html('<b>Fehler:</b><br>Fehler beim Löschen der Kategorie.')
$('#delete_category_dialog_error').show( "blind" ,300);
}
}
});
}
However, the selectEditedCategory()-function never works (which is called after you edited or created a category so it gets selected) though the given variable (categoryid) is correct, tested with alert. The function that calls selectEditedCategory is also placed in categories-management.js.
So my questions are:
Why does selectRootCategory() work when it is called via success-function in the delete-dialog but not when called via $document.ready()?
Why doesn't selectEditedCategory() work at all?
BTW don't get fooled by the categegorySelected variable, this is meant to determine if the edit- and delete-button are enabled or not. "Alle" is a fake category which contains all items from all categories and cannot be deleted or edited ("Alle" means "all" in German).
I'm using jquery-1.10.2.
Edit: To make things more clear: The ids on the items are correctly set when I call GetCategories();. This function does the following:
function GetCategories()
{
var url = './ajax/training_management_data.php';
$('#training_management_categories_items').html('<ul style="list-style: none; margin-left:0px; margin-top:0px; padding:0px;" id="training_management_categories_items_ul"></ul>');
$('#training_management_categories_items_ul').append(' \
<li class="training_management_categories_list"> \
Alle \
</li> \
');
$.ajax({
url: url,
type: "POST",
data: {
action: 'get_categories',
},
dataType: 'JSON',
success: function (data) {
$.each(data, function(index, data) {
$('#training_management_categories_items_ul').append(' \
<li class="training_management_categories_list"> \
'+data.name+' \
</li> \
');
});
}
});
}
It works fine which is proven by the fact that I can delete and edit the categories (the functions to do so require the id of the element. However I read the ID not via the ID field as this contains a string but by the attribute "data-id" which only contains the ID (as you see in above code). So the problem lies solely at the jQuery part and not at the ajax-part.
Edit2: When I add selectRootCategory() to the success-function of GetCategories(), it works on page load. But I still don't get why it doesn't work with document.ready(). I cannot use it in GetCategories(), though because it would de-select any item and select "Alle" instead.
I can still not get selectedEditedCategory to work.
The var categoryid contains a valid ID though, e.g. training_management_categories_list_a_70.

You have to parse the data coming back from the server and add a class to it.
like
$.ajax({
...
success:function(data){
$.each(data,function(singleData){
$(singleData).addClass('blahblah');
});
}
...
});
Hope this helps

Related

ASP.net: AJAX Result Not Kicking Off

I think this will be a weird one for you as I am at my wits end with this. On a screen I have in a table, I have a link being clicked that is setting off a javascript/ajax request. I have similar code in another screen that works perfectly as it heads down into the success part of the ajax call and runs code in the success portion of the call. For some reason though I can't seem to get this to work and when I debug it in chrome, I lose my breakpoints and it never seems to get into the success portion of the Ajax call.
#section scripts{
<script>
// Get the bond ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.updatelink').click(function () {
var bondid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Maintenance/Bond_Maint?handler=UpdateandReloadData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { bondid: bondid },
success: function (result) {
if (result.pass != undefined) {
document.forms[0].submit();
}
},
});
});
</script>
}
The ASP.net code behind that is calling does an update to the database and then passes back a variable containing Success as its message.
//-------------------------------------------------------------------------------
// Try to get and insert the data from a selected row and copy it
//-------------------------------------------------------------------------------
public ActionResult OnPostUpdateandReloadData(string bondid)
{
return new JsonResult(new { pass = "Success" });
}
I'm not sure how else to describe my issue other than when I debug my other code via the browser, it appears to take a different path than this code does and I cannot fathom why. For reference my other code looks like this:
#section scripts{
<script>
// Get the offender ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var offenderid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.path != undefined) {
window.location.replace(result.path);
}
},
});
});
</script>
}
Any help would be appreciated.
Okay guys so first off, thank you everyone for responding to my question. Frank Writte and Alfred pointed me into the right direction by looking for the status in the network tab for my calls. I found out that I was getting cancellations for my requests. After looking into that I found this article What does status=canceled for a resource mean in Chrome Developer Tools? that has an answer from FUCO that gave me what I needed to do. Apparently I needed to add event.preventDefault(); in front of my ajax call and all of a sudden my code worked. I'm not sure I completely understand why this works but I can't complain about the results. Again thank you everyone for trying to help. This one has been boggling my mind all morning.

Insert data into MySQL Databse with PHP/AJAX, execute success option AFTER it's inserted (Callback)

I've been trying to make a simple site, and I can't quite wrap my head around some of the things said here, some of which are also unrelated to my situation.
The site has a form with 3 input boxes, a button, and a list. The info is submitted through a separate PHP file to a MySQL database, once the submit button is clicked. I'm supposed to make the list (it's inside a div) update once the info is successfully sent and updated in the database. So far I've made it work with async:false but I'm not supposed to, because of society.
Without this (bad) option, the list doesn't load after submitting the info, because (I assume) the method is executed past it, since it doesn't wait for it to finish.
What do I exactly have to do in "success:" to make it work? (Or, I've read something about .done() within the $.ajax clause, but I'm not sure how to make it work.)
What's the callback supposed to be like? I've never done it before and I can get really disoriented with the results here because each case is slightly different.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
url: "save.php",
method: "POST",
data: { name: name.value, email: email.value, telephone: telephone.value },
success: $("List").load(" List")
});
}
Thank you in advanced and if I need include further info don't hesitate to ask.
From this comment
as far as i know the success function will be called on success you should use complete, A function to be called when the request finishes (after success and error callbacks are executed). isnt that what you want ? – Muhammad Omer Aslam
I managed to solve the issue simply moving the $.load clause from the success: option to a complete: option. (I think they're called options)
I haven't managed error handling yet, even inside my head but at least it works as it should if everything is entered properly.
Thanks!
(Won't let me mark as answered until 2 days)
I would first create an AJAX call inside a function which runs when the page loads to populate the list.
window.onload = populatelist();
function populatelist() {
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'populate'},
success: function(data) { $("#list").html("data"); }
});
}
Note: #list refers to <div id="list> and your list should be inside this.
I would then have another AJAX call inside a different function which updates the database when the form is submitted. Upon success, it will run the populatelist function.
function save() {
var name = document.getElementById('name');
var email = document.getElementById('email');
var telephone = document.getElementById('telephone');
$.ajax({
type: "POST",
url: "list.php",
data: {function: 'update', name: name.value, email: email.value, telephone: telephone.value },
success: function() { populatelist(); }
});
}
list.php should look like this:
<?php
if($_POST['function'] == "populate") {
// your code to get the content from the database and put it in a list
}
if($_POST['function'] == "update") {
// your code to update the database
}
?>
I will show you piece of solution that I use in my project. I cannot say it is optimal or best practices, but it works for me and can work for you:
PHP:
function doLoadMails(){
//initialize empty variable
$mails;
$conn = new mysqli($_POST['ip'], $_POST['login'], $_POST['pass'], $_POST['db']);
// Check connection
if ($conn->connect_error) {
die("");
}
//some select, insert, whatever
$sql = "SELECT ... ... ... ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row, j is counter for rows
$j =0;
while($row_a = $result->fetch_assoc()) {
//for each row, fill array
$mails[$j][0] = $row_a["name"] ;
$mails[$j][1] = $row_a["mail"] ;
$mails[$j][2] = $row_a["language"] ;
$j++;
}
}
//if $mails has results (we added something into it)
if(isset($mails)){
echo json_encode($mails);/return json*/ }
else{
//some error message you can handle in JS
echo"[null]";}
}
and then in JS
function doLoadMails() {
$.ajax({
data: { /*pass parameters*/ },
type: "post",
url: "dataFunnel.php",
success: function(data) { /*data is a dummy variable for everything your PHP echoes/returns*/
console.log(data); //you can check what you get
if (data != "[null]") { /*some error handling ..., in my case if it matches what I have declared as error state in PHP - !(isset($mails))*/ }
}
});
Keep in mind, that you can echo/return directly the result of your SQL request and put it into JS in some more raw format, and handle further processing here.
In your solution, you will probably need to echo the return code of the INSERT request.

laravel: view not shown after ajax post

I want to show a view after ajax post. but view shown only in browser console.not in main browser.what i am doing wrong?? please help. i am stucking here for one week.i am using laravel 5.3
javascript:
$('#btn-save').click(function () {
var doctor_id=$('#doctors_id').val();
var doctor_name=$('#autocomplete-custom-append').val();
var patient=$('#p_name').val();
var mobile=$('#p_mobile_no').val();
$.ajax({
url: '{{URL::to('confirmation')}}',
type: "POST",
data: {
'doctor_id':doctor_id,
'doctor_name': doctor_name,
'patient_name': patient,
'mobile_no':mobile
},
dataType: 'json',
success: function (data) {
//window.location.href=data.url;
}
});
return false;
});
controller:
public function serialConfirmation(Request $request)
{
$doctor_id=$request->input('doctor_id');
$doctor_name=$request->input('doctor_name');
$patient_name=$request->input('patient_name');
$mobile_no=$request->input('mobile_no');
return view('serial.confirmation',compact('doctor_id','doctor_name','patient_name', 'mobile_no' );
}
You will need to assing the html to your page you will do this in your javascript like so:
$("#wrapper").html(data);
If so that you want to put the html to a element with the id of wrapper.
Note this will exchange the current html in the element with the html returned from php if you want to preserve current html and just append the new html you will have to use either prepend or append jquery function depending on if you want to prepend or append.
if you want to redirect, there is no need to use ajax, just change the method you call serialConfirmation to call your url /confirmation then keep the function as you have it.
(You can have a form with action="{{ url('/confirmation') }} )
And you can access the data in your view like this {{$doctor_id}}
Just change your success like below:
success: function (data) {
// Insert your html code into the page using ".html(html)" method
// or other similar method.
}
Something like this way.

Passing data from Javascript MVC controller

I'm really new to jQuery and Charts. This is my script, it works fine. It gives me the id of the checkboxes selected by the user. I have a Chart action in my controller which also works fine, but it creates a chart using all my values. I want it to create a chart based on the selected values that are in my script. I don't know how to pass the selected values to my controller.
var checkboxes = $("input[type='checkbox']");
$(function ()
{
function getValueUsingClass() {
/* declare an checkbox array */
var chkArray = [];
/* look for all checkboes that have a class 'chk' attached to it and check if it was checked */
$(".chk:checked").each(function () {
chkArray.push($(this).val());
});
/* we join the array separated by the comma */
var selected = chkArray.join(",") + ",";
/* check if there is selected checkboxes, by default the length is 1 as it contains one single comma */
if (selected.length > 1)
{
alert("You have selected " + selected);
}
else
{
alert("Please check at least one of the checkbox");
}
}
$("#Charter").click(function () {
getValueUsingClass();
});
});
Return the data you want in your js function after populating the variable using return selected; then send it back by posting a form or using ajax.
Bind your data to an element on your View page, for example:
<input name="foo" id="yourId" value="bar" />
then modify it's value:
$('#foo').val(getValueUsingClass());
and pass the model back by posting your form to your controller.
If you wish to send data to your controller async then you can look into Ajax.
You can use ajax to call your controller method within getValueUsingClass().
It would probably look something like this:
$.ajax({
url: "/YourControllerName/Chart",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { arr: chkArray },
success: function () {
// do things upon success
},
error: function () {
alert("Error!");
}
});
That is, providing your Controller action has a parameter named arr, because json maps chkArray to it once it is passed to the Controller.

Issue populating ajax response into a div

What am I missing? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. But I can't figure out why it won't populate my div area.
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal.
Second, you are using jQuery but then switch back to classic JavaScript. You could update your code to the following:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName") selector is for selecting by class and $("#SomeName") is to select by id.
Edit and Note
If this terminal div could start to get a lot of data inside of it, you may look at using the .append() function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. The update would be something similar to the following (its a little shorter and should be more efficient as well)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
If you want to change the contend of div not using jquery, you should use innerHTML instead of value.
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data

Categories

Resources