AJAX first attempt json data element not changing - ajax

Hi I have my first AJAX JSON working and it returns C5:3; at the moment for development and displays this in a div, a img tag should be replaced from a off.png to a on.png but this isn't happening. Would appreciate if anyone could through some light on this?? here is my code
$("button.checkStatus").click(function(){
//This Ajax checks the current on/off status of the passed X10 code
$('img.checkStatus').each(function(i, obj) {
$x10Device = $(this).data("x10");
var postData = "url=http://local/tenHsServer/tenHsServer.aspx?t=ab&
f=DeviceStatus&d=" + $x10Device ;
$.ajax({
type: "POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'urlencodeJson.php',
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
if (data.success == true){
$('#section1').html(data.message);
$("X10").data('src','lightbulbon.png');
}
else{
$('#section2').html(data.message);
$("X10").data('src','lightbulbon.png');
}
}
});
The HTML
<img src="lightbulboff.png" class="checkStatus" data-x10="C5">
<img src="lightbulboff.png" class="checkStatus" data-x10="C6">
<img src="lightbulboff.png" class="checkStatus" data-x10="C7">
<button class="checkStatus">Device Status Check</button>
<div id="section1"></div>
<div id="section2"></div>
This is driving me crazy!!! every way tried over the last 2 days hit a brick wall would be great if I could crack it!!!
Many thanks!!!

I think you could change a couple of things to make it works, first of all change the success part inside your ajax request:
$("X10").data('src','lightbulbon.png');
this wont lead you anywhere, since you're addressing nothing, insted save you current object in a variable and change it (or use the $(this) context where this is your current image object) :
$(this).attr('src','lightbulbon.png');
another little thing is how you set up the call, while it's not wrong, doing :
$x10Device = $(this).data("x10");
var postData = "url=http://local/tenHsServer/tenHsServer.aspx?t=ab&
f=DeviceStatus&d=" + $x10Device ;
could be a little redundant and can lead to easy error while you setup a post request, just rewrite it like an array :
data: {url : 'http://local/tenHsServer/tenHsServer.aspx?t=ab',
f : 'DeviceStatus',
d: $(this).data("x10") }
the whole function should be like :
$("button.checkStatus").click(function(){
$('img.checkStatus').each(function(i, obj) {
var element = $(this);
$.ajax({
type: "POST",
url: 'urlencodeJson.php',
dataType: "json",
data: { url : 'http://local/tenHsServer/tenHsServer.aspx?t=ab',
f : 'DeviceStatus',
d: $(this).data("x10") },
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
},
success: function(data) {
if (data.success == true){
$('#section1').html(data.message);
element.attr('src','lightbulbon.png');
}
else{
$('#section2').html(data.message);
element.attr('src','lightbulbon.png');
}
}
});
});
});

Related

What is a proper way to POST multiple sets of data through AJAX to .Net Core EF Core

I have seen numerous examples, mostly wrong or outdated concepts written a decade ago. I cant seem to find a way to submit multiple variables to the ef core database using Ajax. I can get it to work with one, but cant seem to get it to work with multiple. Not sure if I am doing something wrong? I just get a syntax error on the var dataObjects
Ajax Call
<script type="text/javascript">
$("#cosubmitbutton").click(function () {
if ($('#CompanyId').val() == "-1" || $('#CompanyId').val() == "0") {
toastr.warning("Please select company / Client!");
return false;
}
var dataObjects = {
CompanyId = $("#CompanyId").val();
TechnicalContact = $("#TechnicalContactId").val();
TCEmailAddress = $("#TCEmailAddressId").val();
NumOfWorkstations = $("#NumOfWorkstationsId").val();
NumOfUsers = $("#NumOfUsersId").val();
NumOfServers = $("#NumOfServersId").val();
NumOfFirewalls = $("#NumOfFirewallsId").val();
NumOfSwitches = $("#NumOfSwitchesId").val();
NumOfAps = $("#NumOfApsId").val();
Domain = $("#DomainId").val();
};
//ObjThreadItem = JSON.stringify({ 'ObjThread': ThreadItem});
console.log("Json Stringify CommonPostData: ", JSON.stringify(dataObjects))
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'JSON',
url: '/Onboarding/Client/CreateClientOverview',
type: "post",
data: JSON.stringify(dataObjects),
success: function (result) {
debugger
toastr.success("Information successfully updated on server!");
location.reload();
},
failure: function (response) {
debugger
console.log(response);
}
});
});
</script>
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult CreateClientOverview(ClientOverview Modal)
{
_context.ClientOverview.Add(Modal);
_context.SaveChanges();
return Json(Modal);
}

How can I load my partial view using ajax call?

I’m trying to load a partial view with an ajax call. I’m trying to follow a solution I found here: Render partial view onclick in asp.net mvc 3 project
My script looks like this:
$("#174").on("click", function () {
$.ajax({
type: "GET",
url: "/TeacherStudent/StudentInformation",
data: "174",
datatype: "html",
sucess: function (data) {
$("#theTimes").html(result);
}
});
});
My controller looks like this:
public ActionResult StudentInformation(string data)
{
int id = Convert.ToInt32(data);
var viewModel = new ScheduleData();
var attend = from s in db.Assignments where s.teacherId == 7 && s.StudentId == 174 select s;
var enroll = from s in db.Enrollments where s.InstructorId == 7 && s.StudentID == 174 select s;
var stdParent = from s in db.Parents select s;
viewModel.Assignments = attend;
viewModel.Enrollments = enroll;
viewModel.Parents = stdParent;
return PartialView("~/Views/Shared/DisplayTemplates/StudentInformation.cshtml");
}
}
Somewhere in my view I have div tag:
<div id="theTimes"></div>
I confirmed that the program calls the partial view but the view does not get displayed in the div tag. What could I be missing in the ajax call? Thanks for helping out!
The problem looks like it's on this line.
sucess: function (data) {
$("#theTimes").html(result);
}
result is undefined and 'sucess' isn't a valid callback.
Try this:
success: function (data) {
$("#theTimes").html(data);
}
Also, change datatype to dataType (grammar) and change data: "174" to data: {"data": "174"}.
I.e.
$("#174").on("click", function () {
$.ajax({
type: "GET",
url: "/TeacherStudent/StudentInformation",
data: {"data": "174"},
dataType: "html",
success: function (data) {
$("#theTimes").html(data);
}
});
});

Pass Ajax POST variable to JQuery UI dialog

Below is an Ajax POST variable I use to return some information to an ASP MVC3 View. However, I cannot get the .dialg() pop-up function to work. Right now you click on the icon that calls GetProgramDetails(pgmname), and nothing happens. First time using Ajax, so any suggestions would be appreciated. Thx!
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
function GetProgramDetails(pgmname) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
});
request.done(function (data) {
$('#data').dialog();
});
</script>
EDIT
I've updated the request.done function to include a simple alert to see if the code was being called. After stepping through with Chrome's debugger, I saw that the code inside was completely skipped over.
request.done(function (data) {
alert("HERE!");
$('#programExplanation').html(data);
});
SECOND EDIT
Here is the controller code the ajax is returning a value from:
[HttpPost]
public string PopDetails(string programName)
{
BatchPrograms batchprograms = db.BatchPrograms.Find(programName);
if (batchprograms == null) return string.Empty;
StringBuilder s = new StringBuilder();
s.Append(batchprograms.ProgramName + " - " + batchprograms.ShortDescription);
s.Append("<br />Job Names: " + batchprograms.PrdJobName + ", " + batchprograms.QuaJobName );
s.Append("<br /> " + batchprograms.Description);
return s.ToString();
}
You need to use the success method to handle the callback, like so:
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(function(data){ $('#data').dialog()} );
This will launch the dialog for you, but if you want to get the response data to work with it, you can have GetProgramDetails take a second parameter which is a callback for after the data is loaded like so:
function GetProgramDetails(pgmname, callback) {
var request = $.ajax({
type: 'POST',
url: '/BatchPrograms/PopDetails',
data: { programName: pgmname },
dataType: 'html'
}).success(callback);
}
This way after the response is received you can handle what to do with the data in your implementation of the callback, in this case it seems like you will be setting data in the dialog and launching the dialog.

synchronize two ajax jquery function

I have two function of jQuery. Both the functions are calling jQuery ajax.
both have property async: false.
In both the function I am redirecting on basis of some ajax response condition.
In the success of first function I am calling the another function and then redirecting to another page. But my first function is not redirecting because my second function is not waiting of the response of the first function.
Hope problem is clear from my question.
my first function is as below
function fnGetCustomer() {
function a(a) {
$("#loading").hide();
//on some condition
//other wise no redirection
self.location = a;
}
var b = $("input#ucLeftPanel_txtMobile").val();
"" != b && ($("#loading").show(), $.ajax({
type: "POST",
url: "Services/GetCustomer.ashx",
data: { "CustMobile": b },
success: a,
async: false,
error: function () {
$("#loading").hide();
}
}));
}
and my second function I am calling the first function
function fnSecond() {
$.ajax({
type: "POST",
url: "some url",
async: false,
data: { "CustMobile": b },
success: function(){
fnGetCustomer();
//if it has all ready redirected then do not redirect
// or redirect to some other place
},
error: function () {
$("#loading").hide();
}
}));
}
I am using my first function all ready. So I don't want to change my first function.
A set up like this should work;
$.ajax({
data: foo,
url: bar
}).done(function(response) {
if (response == "redirect") {
// redirect to some page
} else {
$.ajax({
data: foo,
url: bar
}).done(function(response2) {
if (response2 == "redirect") {
// redirect to some other page
} else {
// do something else
}
});
}
});​
I've not tested doing something like this, but that's roughly how I'd start off
If you don't need the result of the first AJAX call to be able to send the second you could add a counter to keep track of the calls. Since you can send both calls at the same time it'll be a lot more responsive.
var requestsLeft = 2;
$.ajax({
url: "Firsturl.ashx",
success: successFunction
});
$.ajax({
url: "Secondurl.ashx",
success: successFunction
});
function successFunction()
{
requestsLeft--;
if (requestsLeft == 0)
doRedirectOrWhatever();
}
If you absolutely need to do them in order you could do something like this. My example expects a json response but that's no requirement for this approach to work.
var ajaxurls = ["Firsturl.ashx", "Secondurl.ashx"]
function doAjax()
{
$.ajax({
url: ajaxurls.shift(), // Get next url
dataType: 'json',
success: function(result)
{
if (result.redirectUrl) // or whatever requirement you set
/* redirect code goes here */
else if (ajaxurls.length>0) // If there are urls left, run next request
doAjax();
}
});
}
doAjax();

Ajax with Codeigniter not working

I want to make an ajax request and it wont work. This is my code:
function loadSingleProductPaso1(div_loading,div_id,index, json,ajaxurl){
$.ajax({
type: "POST",
url: ajaxurl, //the url is http://www.mysite.com/controller/function
data: "ajax=true&precio="+JSON.parse(json[index]).miprecio,
success: function(msg){
...
}
}
});
}
The thing is, when I add a '?' to the data element (data: "?ajax=true&..."), it works, but sends a $_POST['?ajax'] variable.
I really don't understand what am I doing wrong.
you can use post function,
like this,
$.post(ajaxurl, {
name : "Test",
city : "Istanbul"
}, function(data){
if(data == 1){
alert("success!");
}
});
function ajax(){
if($this->input->post('name') == "Test"){
echo 1;
}
}

Resources