Statement below I had used before to focus on 1st element in a form, and it works very well.
$('form:first *:input[type!=hidden]:first').focus();
But now the problem is when I use it in a form that was empty(without any input element), and I create the elements inside that form by using jQuery .html() after some work, it will not focus on any element.
This is my form:
<form id="edit_marks" method="post">
<div id="display">
</div>
</form>
This is my jQuery AJAX:
function getData()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
$('#display').html(data);
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();
$('form:first *:input[type!=hidden]:first').focus();
You are triggering the event before you are adding the form, so you need to trigger event after form get added. Add it inside ajax success. Since ajax is asynchronous it may complete at any time, so before completing it will return from the function.
function getData()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
$('#display').html(data);
$('form:first *:input[type!=hidden]:first').focus();
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();
Move the focus code inside the AJAX success, because AJAX means it is asynchronous call. So in order to make focus work after AJAX is to add it in the success.
function getData() {
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax({
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {
Semester:Semester,
StudentID:StudentID
},
dataType: 'text',
success: function(data) {
$('#display').html(data);
$('form:first *:input[type!=hidden]:first').focus();
},
error: function(ts) {
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();
Related
I have a global javascript file 'Global.js' with a Global Handler 'GlobalHandler.ashx',
what i am trying to do is to render some data in the back-end (inside the handler ), than return text data using context.Response.Write(MyString)
The question is how to append the data to my html element .
I looked into the response (200) and the data is there , but i don't know the reason of not appending my text into the html element
I have tried to append them like the classic way success:function(data){
$(elementID).html(data);}
But that doesnt work
Here In Global.js
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here In MyPage.aspx
$(document).ready(function () {
GetProfession("Profession");
});
HERE In the Handler
string functionName = context.Request["functionName"];
GroupDAO GroupDAO = new GroupDAO();
if (functionName.Equals("GetProfession"))
{
var ListOfGroups = GroupDAO.GetGroups();
string Builder = "";
foreach (var group in ListOfGroups)
{
Builder+="<option value='" + group.GroupID + "'>" + group.GroupName + "</option>";
}
context.Response.Write(Builder);
}
I am expecting to have those options appended to the html element 'Profession'
but this unfortunately it does not happening
I found the answer , i did not recognize the logical reason of such behaviour ,
but the data was not in the success method even if the statuc code was 200 .
in fact it was in the error: properties of ajax request .
what i have done is :
instead of appending the data in success to the html element .
i did it in the response text
.
Here is the code before not working :
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here is the one that works
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "text/html; charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data, fata, meta) {
},
error: function (err) {
$("#Profession").html(err.responseText);
//alert(err.responseText);
}
});
}
$(document).ready(function () {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id); //<-------
$.ajax({
url: "m/a/a.class.php",
method: "POST",
data: {pId: p_id},
dataType: "text",
success: function (data) {
console.log(data); //<------
}
});
});
I want to pass the my data to PHP, but when I am trying to use it for a query it is empty, so I added the console.log before and after the AJAX script.
Before it gives me the right value ("id") of the selected product, for example "9", but the console.log in the AJAX script just returns an empty value "".
What is the problem with this? Do I miss-understand the code of AJAX?
UPDATE:
case 'linie':
if (isset($_POST['pId'])){
$t = $_POST['pId'];
}
$sql = 'SELECT l.id, l.bezeichnung as bezeichnung '
. 'FROM l "
. 'LEFT JOIN p ON p.id=l.p_id '
. 'WHERE l.p_id ="'.$t.'" AND l.deleted=0 AND p.deleted=0 '
. 'ORDER BY l.bezeichnung ';
break;
This is the relevant part of my PHP code where I try to get the previous input.
UPDATE 2:
$(document).ready(function () {
$("#p").change(function () {
var p_id = $(this).val();
console.log(p_id);
$.ajax({
method: "POST",
url: "m/a/a.class.php",
data: { pID: $('#p').val() },
async: true,
dataType: 'text', (...)
When I changed it to this it worked for me :)
I guess you are playing data data.
This data
data: {produktId: p_id},
is not same as this data
success: function (data) {
Better way of writing it will be
$("#produkt").change(function () {
var p_id = $(this).val();
console.log(p_id); //<-------
$.ajax({
url: "modules/ausschuss/ausschuss.class.php",
method: "POST",
data: {produktId: p_id},
dataType: "text",
success: function (response) {
console.log(response); //<------
}
});
});
Notice the success block parameter
So this data data: {produktId: p_id}, is detail which you pass to an ajax call.
And the ajax call may or may not return response which is returned in success block as response.
Example
i have this ajax call
$.ajax({
type: 'POST',
url: "<?php echo $_SERVER_ADDR . PUBLIC_PATH . 'presupuestos/buscant/'; ?>",
data: { 'arregloid':sel_articulos, 'idpre':$('#presupuestos_id').val()},
dataType: "json",
success: function(responses) {
$.each(responses, function(ii, response) {
$("[name='#pre_detalle["+response["idart"]+"[canart]]']").val(response['canart']);
$("#pre_detalle_precio["+response["idart"]+"]").val(response["precio"]);
console.log(response["idart"]);
console.log(response["canart"]);
console.log(response["precio"]);
});
},
complete: function () {
$('#spinner').hide();
actTotales();
},
error: function() {
}
});//ajax 2
i need to assign to 2 text inputs with ids:
id="pre_detalle_precio[x]" and id="pre_detalle_[x][canart]
being x the article id being returned by the ajax this three responses:
response["idart"];
response["canart"];
response["precio"];
i can see the responses being returned correctly with console.log but can't alter the values of the input boxes.
i think you are missing underscore
$("[name='#pre_detalle_["+response["idart"]+"[canart]]']").val(response['canart']);
$("#pre_detalle_precio_["+response["idart"]+"]").val(response["precio"]);
as in id="pre_detalle_precio[x]" and id="pre_detalle_[x][canart]
try now
I am not able to pass value using ajax in php file.
Corrected Code
<script>
$("body").on('change', '#area', function () {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'box.php',
type: 'POST',
data: {option: selectedValue},
success: function () {
console.log("Data sent!");
}
});
});
</script>
here the php code
<?php $val=$_POST['option'];echo $val; ?>
There are a few problems here:
It should be url, not rl. Also, you have type: POST' with it ending in a ', but no starting '.
It should be type: 'POST'.
It should then look like this:
$("body").on('change', '#area', function() {
var selectedValue = this.value;
$.ajax({
url: 'box.php',
type: 'POST',
data: {
option : selectedValue
},
success: function() {
console.log("Data sent!");
}
});
});
If you want to view your data on the same page after (as on box.php, you are echo'ing the value.), you can do this:
success: function(data) {
console.log(data);
}
This will then write in the console what option is, which is the value of #area.
Try the following code
$("body").on('change',function(){
$.ajax({
URL:<you absolute url>,
TYPE:POST,
Data:"variable="+$("#area").val(),
Success:function(msg){
<do something>
}
});
});
Hope this will help you in solving your problem.
Your just miss ajax method parameter spelling of 'url' and single quote before value of type i.e. 'POST'. It should be like
$.ajax({
url: 'box.php',
type: 'POST',
data: {option : selectedValue},
success: function() { console.log("Data sent!");}
});
I am using knockout with MVC in my project. when I pass viewModel on dropdown change It's getting continues ajax request to the server. How can I avoid the continues request??? any one can please help me on this???
My View
#ko.Html.DropDownList(m => m.RoomList, new { #class = "full-width", #id = "rmch" }, "Text", "Value").Value(m=>m.NoOfRooms)
Javascript
$(document).ready(function () {
$('#rmch').on("change", function (e) {
//viewModel.NoOfRooms = $(this).val();
$.ajax({
url: '#Url.Action("DropChange", "Home")',
type: 'POST',
data: ko.mapping.toJSON(viewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
//ko.applyBindings(viewModel, document.getElementById("p_scentsFH"));
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
})
});
})
if I remove value part from the dropdownlist in the view It's working .but I need the value for the processing.
The simplest thing I can think of is to set the dropdownlist to readonly before updating it, then when you have finished adding the new items, remove the readonly attribute.
$(document).ready(function () {
$('#rmch').on("change", function (e) {
//viewModel.NoOfRooms = $(this).val();
$.ajax({
url: '#Url.Action("DropChange", "Home")',
type: 'POST',
data: ko.mapping.toJSON(viewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
//this will disable the onchange event
$('#rmch').attr("readonly","readonly");
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
//ko.applyBindings(viewModel, document.getElementById("p_scentsFH"));
ko.mapping.fromJS(data, viewModel);
}
//this will enable the onchange event for the next time you select something.
$('#rmch').removeAttr("readonly");
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
})
});
})