jquery ajax request to asp.net code behind not working - javascript

the ajax request is part of a larger function. I am trying to refrain from clogging up the page with code so here is the request itself:
$.ajax({
url: "PubMedNewSnp.aspx/GetEdits",
data: "{ 'Drug':'" + drug + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (alreadyInDB) {
var TableName = "combo";
var curRow = curComboRow;
if (alreadyInDB) {
TableName = "edit";
curRow = curEditRow;
curEditRow++;
}
else {
curComboRow++;
}
do stuff...
}
});
Here is the aspx.cs file:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static bool GetEdits (string Drug) {
//masterDBDataContext masterDB = new masterDBDataContext();
bool alreadyInDB = false;
if (Drug == "bannana")
{
alreadyInDB = true;
}
//var inTbl = (from a in masterDB.tbl_custom_SNPs_Alls
// join
// where a.PubMedInfoId == Convert.ToInt32(curRow[0]) &&
// a.DrugId == Convert.ToInt32(curRow[0])
// select r).ToList();
return alreadyInDB;
}
for some reason there is no response coming back. In the network tab all I see are the Request Headers and the Request payload. There is also a warning: Provisional headers are shown. Not sure what that means. Sorry if the question is phrased vaguely or not information is given. I will be glad to provide more, just not sure what else is needed.
Thanks in advance.

This is your output for alreadyInDB which is in json format.
Object {d:true} or Object {d:false}
$.ajax({
url: "PubMedNewSnp.aspx/GetEdits",
data: "{ 'Drug':'" + drug + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (alreadyInDB) { // alreadyInDB is in json format. you need to access object property.
var TableName = "combo";
var curRow = curComboRow;
if (alreadyInDB.d) {
TableName = "edit";
curRow = curEditRow;
curEditRow++;
}
else {
curComboRow++;
}
}
});
Hope that helps.

Related

AJAX does what I need it to do, but errors still occur

I am writing a web page which reads data from an html table to be used on a MySQL query using PHP. This is a continuation of this question. I got AJAX send the data I need to use on to the PHP file with the code to update the information it sent. However, two errors have occured.
I get a message saying Error:Error: jQuery21405680291895882033_1487801210725 was not called
The data I send has a ":1" at the end of it, giving me an error.
How can I fix these two mistakes? Thank you so much!
JS code:
function getTableData(){
var array = [];
var headers = [];
$('#tablaListado th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#tablaListado tr').has('td').each(function() {
var arrayItem = {};
$('td', $(this)).each(function(index, item) {
if($(this).find("textarea").length){
var costo = $(this).find('textarea').val();
arrayItem[headers[index]] = costo;
}else{
arrayItem[headers[index]] = $(item).html();
}
});
array.push(arrayItem);
});
actualizarCostos(array);
}
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
console.log(array[i]);
console.log(JSON.stringify(array[i]));
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: false,
jsonpCallback: jsonCallback,
cache: true,
data:{ "table_data": JSON.stringify(array[i])},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status"+status+" \nError:"+err);
},
traditional: true
});
}
}else{
alert("Input must be array");
}
}
function jsonCallback(data, status){
console.log(data + " " + status);
}
PHP portion:
//Added on top of the page
header('Access-Control-Allow-Origin: *');
...
function updateCosts($json){
conectar();
$array = json_decode($json, true);
echo "<script>console.log('$array');</script>";
$costo = $array["Costo"];
$sku = $array["SKU"];
$instruccion = "UPDATE articulos SET art_cost='$costo' WHERE art_SKU = '$sku'";
return ejecutarInstruccion($instruccion);
}
if(isset($_GET['table_data'])){
foreach($_GET['table_data'] as $index => $item)
{
// do something here
echo "<script>console.log('$item');</script>";
updateCosts($item);
}
// Response back - if needed
echo json_encode(array('status'=>true, 'msg'=>'Some Message'));
}
Edit:
I forgot to mention that I have tried changing 'jsonp' as 'json' on this code but I get an error saying the PHP file doesn't allow foreign data, even though I tried using header('Access-Control-Allow-Origin: *') on said file.
Your page is returning JSON, not JSONP. They aren't interchangeable. Remove the jsonp and jsonpCallback properties from the $.ajax() call, and change dataType to json:
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: true,
data: {
table_data: JSON.stringify(array[i])
},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status" + status + " \nError:" + err);
},
traditional: true
});
I'd suggest you have the following AJAX:
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
console.log(array[i]);
console.log(JSON.stringify(array[i]));
}
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:{ "table_data": JSON.stringify(array)},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status"+status+" \nError:"+err);
}
});
}else{
alert("Input must be array");
}
}
Then do the For-Loop on the PHP side of the server. Maybe each variable in array has a hidden parameter to know its own index, or JSON is doing something strange like displaying the number of elements in the array (in this case 1 because you're iterating over each one)

Ajax Response add under each element

I have a question that I can't seem to answer about Jquery Ajax Response.
I use a for each to select some data from <p> tags in each info_div. This data I then use to do a ajax call to a service that replies with a XML. I want to place some elements from this XML under each div from where I took the two variables. Each div should have it's own reply.
$(document).ready(function () {
$('#action-button').click(function () {
$(".info_div").each(function () {
var var1 = $(this).find('p:nth-child(4)').text();
var1 = var1.slice(-10);
var var2 = $(this).find('p:nth-child(8)').text();
var2 = var2.slice(-1);
$.ajax({
type: "GET",
url: "http://www.mypage.com/mypage&value1=" + "va1" + "&value2=" + "var2",
cache: false,
dataType: "xml",
success: function (xml) {
$(xml).find('member').each(function () {
var name = $(this).find("title").text()
/* how do I get this variable under each $('.info_div') from where I selected the var1 and var2
Every attempt I made places all replies under all the divs in class .info_div */
});
}
});
});
});
});
I would not recommend you to send ajax requests in a loop. Better collect all your data, then send it to the server and handle the response.
Meanwhile, if you insist to do it in a loop, you should make a reference to the iterated element from $(".indo_div) collection, and use it in ajax callback.
$(".info_div").each(function() {
var _that = $(this);
var var1 = $(this).find('p:nth-child(4)').text();
var1 = var1.slice(-10);
var var2 = $(this).find('p:nth-child(8)').text();
var2 = var2.slice(-1);
$.ajax({
type: "GET",
url: "http://www.mypage.com/mypage&value1=" + "va1" + "&value2=" + "var2",
cache: false,
dataType: "xml",
success: function(xml) {
$(xml).find('member').each(function(){
var name = $(this).find("title").text()
that.append(name);
});
}
});
});

ajax post error: internal error 500 on post method

I am running the script below whe a timer has run out of time, the post was working fine when i started passing the data through that is need for the final information is saved. that when got an internal error.
JavaScript ajax call
var selectedval;
if (document.getElementById('RadioButtonList1_0').checked == true) {
selectedval = document.getElementById('RadioButtonList1_0').value
}
else if (document.getElementById('RadioButtonList1_1').checked == true) {
selectedval = document.getElementById('RadioButtonList1_1').value
}
else if (document.getElementById('RadioButtonList1_1').checked == true) {
selectedval = document.getElementById('RadioButtonList1_1').value
}
else if (document.getElementById('RadioButtonList1_2').checked == true) {
selectedval = document.getElementById('RadioButtonList1_2').value
}
else if (document.getElementById('RadioButtonList1_3').checked == true) {
selectedval = document.getElementById('RadioButtonList1_3').value
}
else {
selectedval = '';
}
var qustNo = document.getElementById('ltlQuestNos').innerHTML;
`enter code here` $.ajax({
type: "GET",
data: '{questNo:'+ qustNo.trim().toString()+',selectedoption:'+ selectedval.toString()+'}',
contentType: "application/json; charset=utf-8",
url: "prTest.aspx/timeFinished",
dataType: "json",
success: function (result) {
// this displays the information so that the page can be re-directed to the results page.
window.location = result.d;
}
Vb.net code.
<WebMethod()>
Public Shared Function timeFinished(questNo As String, selectedoption As String) As String
Dim objExam As New examClass()
If selectedoption = "-1" Then
'lblWarning.Visible = True
'lblWarning.Text = "Please answer Question!"
Else
' lblMessage.Text = "Navigation = " & Request.Form("textNav")
objExam.answerQuestion(HttpContext.Current.Session("examid"), questNo, selectedoption, "00:00:00")
' lblWarning.Visible = False
'close connection
objExam.Dispose()
End If
objExam.finishTest(Convert.ToInt32(HttpContext.Current.Session("examid").ToString()))
objExam.Dispose()
' HttpContext.Current.Response.Redirect("ChapterTestSummary.aspx", true);
Dim url As String = "testsummary.aspx"
Return url
End Function
I think the problem is with data part in ajax. Because, if you are building the data as string by yourself, key and value should enclosed in double quotes. Otherwise make it as an object and use JSON.stringify() method to make it as string.
$.ajax({
type: "GET",
data: JSON.stringify({
questNo: qustNo.trim(),
selectedoption: selectedval
}),
contentType: "application/json; charset=utf-8",
url: "prTest.aspx/timeFinished",
dataType: "json",
success: function(result) {
// this displays the information so that the page can be re-directed to the results page.
window.location = result.d;
}
});

Can I use a concatenated string for the url in my .ajax() request

I'm doing cross-domain requests and once the first request is made I need to retrieve the ID (and do some other stuff) and then use the ID for the next request.
So far the hang-up is that the next request doesn't like the concatenation. Here's my code, and yes I know document.write should be changed to console.log() however console.log doesn't work and I was probably going to ask that question after get help with my current problem. the problem starts at the second .ajax() request.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script >
$(document).ready(function($) {
// First link out of three
var url = 'https://www.sciencebase.gov/catalo
/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
for (var i = 36; i < 37; i++) {
document.write(json.items[i].id);
var urlId = json.items[i].id;
}
var deferUrl = 'https://www.sciencebase.gov/catalog/itemLink/" + urlId
+"?format=json&max=10';
$.ajax({
type: 'GET',
url: deferUrl,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
// Get the next id to use for the next url
document.write(deferUrl);
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog
/item/4f4e4b19e4b07f02db6a7f04?format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
document.write(json.title);
},
error: function(e) {
console.log(e.message);
}
});
},
error: function(e) {
console.log(e.message);
}
});
},
error: function(e) {
console.log(e.message);
}
});
});
</script>
</head>
<body>
</body>
</html>
Thanks for the help
'https://www.sciencebase.gov/catalog/itemLink/" + urlId
+"?format=json&max=10';
should be
'https://www.sciencebase.gov/catalog/itemLink/' + urlId
+'?format=json&max=10';
You mix simples and doubles quotes. use 'srting' + var + 'string' or "string" + var + "string" but don't mix them
To address your concatenation issue only.. you have a mix of single and double quotes there. They should all be consistent.
ex:
var deferUrl = 'https://www.sciencebase.gov/catalog/itemLink/' + urlId + '?format=json&max=10';
I made a slight change from
for (var i = 36; i < 37; i++) {
var urlId = json.items[i].id;
}
var deferUrl = 'https://www.sciencebase.gov/catalog/itemLink/' +
urlId + '?format=jsonp&max=10';
$.ajax({
type: 'GET',
url: deferUrl,
jsonpCallback: 'getSBJSON',
contentType: 'application/json',
dataType: 'jsonp',
to
for (var i = 36; i < 37; i++) {
var urlId = json.items[i].id;
}
var deferUrl = urlId;
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink/' +
deferUrl + '?format=jsonp&max=10',
jsonpCallback: 'getSBJSON',
contentType: 'application/json',
dataType: 'jsonp',
and that seemed to do the trick. It didn't like having the concatenation done completely before assigning it to the url.

How to ensure that a function is executed completely, before navigating to another page?

I'm removing certain records using a webservice. The jquery ajax request is written in the onclick of a hyperlink. When im executing the script, line by line using firebug, it's getting removed otherwise it's not. Does any one meet any situation like this before? Please help
Code sample:
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
jQuery ajax functions return deferred objects, thus we return $.ajax. Then you should use deferred.done to execute the callback when the AJAX is fully finished. When the AJAX is done, navigate away using JS instead:
var func = function() {
...
return $.ajax({...}); //return our ajax deferred
}
$(".target").click(function() {
var target = this; //preserve "this" since this in the callback may be different
func().done(function(){ //our done callback executed when ajax is done
window.location.href = target.href; //assuming .target is a link
});
return false; //prevent the natural click action
});
You can use the async: false on the ajax call that is wait there to complete the call.
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: false,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
Alternative you can make the submit after the request.
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
return false;
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: true,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
$("#YourFormID").submit();
}
//Event that'll be fired on Success
});
}
Simply move the Event to the "success" handler in your ajax request:
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed");
//Event that'll be fired on Success
}
});
Alternatively use jQuery ajax callback methods.

Categories

Resources