Issue populating ajax response into a div - javascript

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

Related

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.

VBA Excel run javascript form event

I’ve already tried to get the element by id, however, the html does not include it. As shown below, this is the script for the drop down that I am trying to change automatically. It will change the name with
appIE.Document.getElementById("supervisor").Value = "Sup_name"
However, it doesn’t fire the event that generates a list of people.
The top of the form also includes <form id='filterform' action="javascript:void(0);">
The JavaScript containing the function I need to call is below.
<script type="text/javascript">
$(function() {
$('#supervisor').change(function() {
document.getElementById('results').innerHTML = '<img src="/img/busy.gif" />';
var str = $('#filterform').serializeArray();
$.ajax({
url: 'ajax.php?p=agentrosters&mode=1&field=supervisor',
type: 'POST',
data: str,
success: function(j) {
//alert(j);
document.getElementById('results').innerHTML = j;
document.getElementById('lastsearch').value = 'supervisor';
resetscript('supervisor');
},
failure: function() {
document.getElementById('results').innerHTML = 'There has been an error, please try again';
resetscript('null');
}
})
})
})
</script>
Any Ideas on how I can get this to work?
If the element is part of a form you may to submit the form, alternatively you can use the onchange event on the element itself. So you may want to change appIE.Document.getElementById("supervisor").Value = "Sup_name" to
With appIE.document.getElementById("supervisor")
.Value = "Sup_name"
.onchange
End with
And if it is part of a form change the ".onchange" to
".parentElement.Submit"
This worked for me.

jQuery adding CSS class to dynamically created elements

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

pass ID when button is clicked to Action link

I want to assign a certain value for an ID when button/url is clicked.
So that I can display a dynamic list based on this id by passing the id to action link.
Sample of my code (button)
<a class="" href="/LaborerSearchByName/Index">
<img src="/Content/images/b7.png" id="b7"
onclick="bb7();"
onmouseover="bigImg(this)"
onmouseout="normalImg(this)">
</a>
The call for action link
#Html.Action("Menu", "MenuItem", new { id = "MenuId"})
"MenuId" must by a dynamic value based on which button is clicked.
Here goes my solution, use Html.ActionLink() -
#Html.ActionLink("Menu Text", "Menu" ,"MenuItem", new { id = "MenuId" }, new { #id = "MenuId" })
Then say you have image control like this -
<img src="/Content/images/b7.png" id="b7"/>
Then you have simple JQuery script to replace query string in this way -
<script>
$(document).ready(function () {
$("#b7").click(function () {
$("#MenuId").attr("href","/MenuItem/Menu/" + this.id);
});
});
</script>
In the above script, when you click on the image element, its id (b7) will be used to formulate the anchor tag url. so now when image was clicked, a new url will be assigned to anchor tag on the client side using JQuery. So the final url should be something like this -
/MenuItem/Menu/b7
UPDATE: As per your comment, I am presenting a simple demonstration on how to use JQUERY AJAX to make a GET request with a parameter and get results back on to the UI.
Lets say you have a controller which returns Json -
public JsonResult GetJson(string MenuId)
{
List<string> urls = new List<string>();
urls.Add("https://google.com");
urls.Add("https://bing.com");
return Json(urls, JsonRequestBehavior.AllowGet);
}
Then you can call this controller action in a button click using JQuery Ajax in the following way. In your implementation you should get that dynamic value instead of input text control. For demo purpose I used Input text to get a value and pass it to controller action.
<input type="text" id="Menu" />
Click me
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#ClickMe").click(function () {
var o = new Object();
o.MenuId = $("#Menu").val();
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) {ou parse data
// This is how we parse returned json string
$.each(data, function (i, item) {
alert(data[i]);
});
},
failure: function (errMsg) { alert(errMsg); }
});
});
});
</script>
When you run the code, you should see following view -
When you enter the value and click on anchor tag -
And as a result, you will get all the results parsed -
You can pass this using your function onclick="bb7(this);"
then in JavaScript part use setAttribute in you function: bb2(this){this.setAttribute("id","someID");}

Put json result from php script into divs jQuery

I have two divs, each one should have a record name from a json result.
<div class="first"></div>
<div class="second"></div>
My json file is as follows :
[{"Name":"name1","Instruction":"instr"},
{"Name":"name2","Instruction":"instr again"}]
I want to put in the first div's value, the ‘Name‘ value of the first record, same for the second div but with the second record.
I'm using jQuery :
<script>
$(document).ready(function() {
$.post("data/result.php",
function(data) {
//alert("Data: " + data);
$('div.first').append(data.Name); //data.Name returns undefined
}
);
});
</script>
Any help would be appreciated.
as far as you are using post for you ajax call, the data returns as a json string, do this:
$(document).ready(function() {
$.post("data/result.php",
function(data) {
data = JSON.parse(data);
$('div.first').append(data[0].Name);
$('div.second').append(data[1].Name);
}
);
});
As previously mentioned you need to parse the result as json. You could use the built in parser in jquery. Like this:
<script>
$(document).ready(function() {
$.ajax({
url: 'data/result.php',
type: 'POST',
dataType: 'json',
success : function (data) {
$('div.first').append(data[0].Name);
}
});
});
</script>
First of all, you can give a datatype with a request:
$.post('data/result.php',function(data) { },'JSON');
If you are not posting any information, why not just use $.get ? (it's the same syntax btw)
$.post('data/result.php',function(data) {
var $first = $('div.first'),
$second = $('div.second');
$first.text(data[0].Name);
$second.text(data[1].Name);
},'JSON');
Also, if you use .append(..) it will be appended to whatever is already in the div. If that is your intention, use .append(...). However, if you want to replace the content of it, even if it is empty, use .text(...) or .html(...)

Categories

Resources