Invalid JSON with markup of my html page - javascript

I have created jquery script that was successfully run on my local machine.but when i uploaded the same script on remote server then jquery script generate error. error is "Invalid Json" and XMLHttpRequest.responseText property show my html page markup in. i have spent 3 days on internet to find the solution but i didn't. my code is here:
<script type="text/javascript">
var pageUrl = '<%=ResolveUrl("~/test2.aspx")%>'
$(document).ready(function () {
$('#<%=Button1.ClientID %>').click(function () {
$.ajax({
type: "POST",
url: pageUrl+ "/ServerSideMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("1");
$('#myDiv').text(msg.d);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Failure: " + textStatus + XMLHttpRequest.responseText );
}
})
return false;
});
});
</script>
and my web method is
_
Public Shared Function ServerSideMethod() As String
Return ("Muhammad Aurangzeb")
End Function

The problem comes from the json generated by your "/ServerSideMethod". Check is validity with http://jsonlint.com/ to find the problem.
Often an history of quotes ' versus the good use of "

If your page method is returning the page's HTML, but your local setup is working correctly, your remote server isn't configured correctly.
If it's ASP.NET 3.5, make sure the remote server's web.config matches your local one.
If it's ASP.NET 2.0, you need to also install the ASP.NET AJAX Extensions.
More information: http://encosia.com/2010/03/08/asmx-scriptservice-mistakes-installation-and-configuration/

Related

Why does Chrome add a query string parameter after included Javascript file? [duplicate]

This question already has an answer here:
jQuery keeps putting a cache buster in my CDN scripts?
(1 answer)
Closed 3 years ago.
I have a javascript file in my HTML page that is included like so:
<script type="text/javascript" src="javascript\pages\page.js"></script>
yet in the chrome network debugger, when i look at what is loaded, it has:
http://localhost:12639/javascript/pages/page.js?_=1556081859333
This is problematic as im not wishing this particular file to bypass caching.
If it makes a difference, the html file is being loaded through an AJAX call.
The value for the field looks to me like a timestamp. Or even just a random number. Any guesses on how it gets there?
Edit: Below is the AJAX call code which will retrieve the HTML result:
$.ajax({
url: 'process.php',
type: 'POST',
datatype: "json",
async:true,
data: {
//some data
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
},
success: function (data) {
$("#somediv").html(data);
}
});
Unfortunately, the issue is jQuery. From their docs
:
cache (default: true, false for dataType 'script' and 'jsonp')
Type: Boolean
If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

How to call a server side method from JS

I've read many questions, forums, blogs, tried many things and I just can't seems to make it work.
I've tried using PageMethods.MyMethod() and that didn't work. Made sure my ScriptManager had EnablePageMethods ="true" and still nothing. I have a breakpoint on the server side and it never hits. Tried using ajax and still nothing
I'm 1st trying to understand how to make it work to then implemented on my program.
This is what I've tried so far:
Server-side:
[System.Web.Services.WebMethod]
public static void SomeMethod(string subject, string body, string recipients, string CurrentUserId)
{
MessageBox.Show("In c#");
}
JS:
function SomeFuntion()
{
debugger; alert("Before web service");
//PageMethods.CreateDraft(var1, var2, var3, var4);
$.ajax
(
{
type: "POST",
url: "NewMessage.aspx/SomeMethod",
data: "{subject:'" + var1+ "', body:'" + var2+ "', recipients:'" + var3
+ "', CurrentUserId:'" + var4+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function()
{
alert("In ajax");
}
}
);
}
As you can see, I tried PageMethods and it didn't work. I know the function runs cause I see the alert message. By the way, the function is being called when the onclick event is fired of on a button. I don't get any errors and neither does it hit the break point on the MessageBox. This is new to me so any explanation would be very helpful too.
Check for errors from the server:
function SomeFuntion()
{
$.ajax({
type: "POST",
url: "NewMessage.aspx/CreateDraft",
data: "{subject:'" + var1+ "', body:'" + var2+ "', recipients:'" + var3+ "', CurrentUserId:'" + var4+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend:function ()
{
alert("about to send request");
},
success: function()
{
alert("In ajax");
},
error: function(xhr, status, error)
{
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
);
}
more additions
Since you are telling me that you are getting a "The HTTP verb POST used to access path '...' is not allowed" you might need configuration to enable .NET web service for http POST requests.
I have dropped .NET few years ago and therefore I have no direct experience but from what I could find in other sites you might need configuration at the server level such:
<system.web>
<webServices>
<protocols>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
Or directives above your method such
[ScriptMethod(UseHttpPost = true)]
public string SomeMethod()
{
....
}
I managed to figure it out with the help of a friend, I would post my answer but I believe it's quite long and complicated. I understood most of the things he did but I still didn't believe how it worked. It was pretty much almost the same thing I did but he made the JS in a separate file and set that file like a base JS. Called the web service there and from my JS he called that function that calls the web service. And it worked lol

.Next To remove limitation on data send using JSONP

Can we remove the limitation on data send using JSONP. Below is my code. What i am trying to do is to pass 3000 characters(actuallly a image which is converted to base64 data) at a time to service(serviceCall.ashx). As my data is large up to 30,000-40,000 characters i am dividing it in packets(3000 each ) and then sending it. Is there any way i can send this complete data in one go. Reason for switching to JSONP is to avoid the pop up on IE which says 'This page is accessing info that is not.....'. I know as JSONP uses GET method there would obviously a data limitation but is there any way to work around this problem.
$.ajax({
type: "GET",
url: 'http://sys108/restnew1/serviceCall.ashx',
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
async: false,
data: {
datachunk: imgdatachunk,
packetlen: imgdatachunk.length,
imagekey: imageid
},
success: function (data) {},
error: function (jqXHR, textStatus, errorThrown) {
if (window.console)
console.log("Error... " + textStatus + " " + errorThrown);
}
});
No, it's not possible to send a GET request of that length in a more-or-less reliable way: actually, it depends both on how the web server is set up and what client (= browser) is used by someone who works with your application.
So I'd suggest looking for alternative (to JSONP) solutions - like CORS, for example.

Unable to get a simple jQuery.Ajax call to work

I'm pretty new to the web-dev world, and I'm having a bear of a time getting a simple jQuery.ajax call to work. Here is the call:
var url = "http://client.the_url.com/get_account_data.php";
$.ajax({
url: url,
dataType: 'json',
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:function (xhr, ajaxOptions, error){
alert("Error");
}
});
I can copy and paste the url into a browser and it renders what I would expect:
{
"id":"Level 3.xpusdscah",
"type":"Level 3",
"name":"xpusdscah",
"total":0,
"in":0,
"out":0
}
Instead, I get the Error alert every time. :/.
The php script I'm hitting starts with the header:
header('Content-type: application/json');
I was trying to pass params to the php script, but now I'm not even doing that. I would think this should be a 'no brainer', but if it is, then I have no brain. I'm trying to figure out how to use wireshark right now, but should I really need to use wireshark to debug a call that is as simple as it gets to a php file?
Can anyone help me? What I'm really hoping for is a "Well duh, you didn't do (insert obvious solution here)!
Thanks in advance,
Fledgling web developer
First, your callback function isn't helpful. It just shows the text "Error" every time. You want to actually display what the error is, like this:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:error(jqXHR, textStatus, errorThrown){
alert("Error:" + textStatus+ "," + errorThrown);
}
});
Your parameters for the error callback were named strangely. The documentation says the second param is a text error code, and the errorThrown is the HTTP status code provided by the web server. See the documentation here: http://api.jquery.com/jQuery.ajax/
Next, you'll want to grab a packet sniffer. This will allow you to inspect the packets going to and from the web server and see the error message that it is throwing. A good free option is Fiddler.
The data you're sending is not json.
var data = "login="+localLogin+"&pw="+localPassword+"&forAccount="+forAccount+"&forAccountType="+forAccountType+"&topAccount="+topAccount+"&fromDate="+fromDate+"&toDate="+toDate;
Should be something like this:
var data = '{"Key1":"' + Value1 + '","Key2":"' + Value2 .... + '""}';
And perhaps you should add the type as POST and content type like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: ....
try these:
inspect the Network tab on your console.
copy and paste the response and parse it in the console command line to verify the JSON is well formed.
show more verbose error description.

Report user errors in jQGrid

I have a jqgrid table querying a MySQL DBMS through an apache2 web server via XML.
Sometimes whenever the DB server shuts down or the server side program encounters
some kind of crashes the jqgrid just freezes down waiting for the XML data to arrive.
In this kind of situation, I would be preferable to make the jqgrid user aware of this matter and thus display a gentle message describing the type of the annomaly.
I was wondering is there any jqgrid option specific for this kind of situation
I'm using:
jquery-1.3.2
jquery-ui-1.7.2
jquery.jqGrid-3.5.3
Thanks,
If for the jqgrid you are using the function datatype with jQuery.agax then place your logic in the error handler. The only problem with this is that you manually have to populate the grid and you don't get the "Loading" hint, though you can create one.
This sample was taken from the usual pattern that I use when calling ASP.NET WCF services, my results object contains int properties for the pager and a rows collection, this is defined in myGrid.setGridParams.
datatype: function(postdata) {
$.ajax({
type: "POST",
url: 'SomeService.svc/SomeGetMethod',
data: JSON.stringify(postdata),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(res) {
myGrid.clearGridData();
for (var i = 0; i < res.d.rows.length; i++) {
myGrid.addRowData(i + 1, res.d.rows[i]);
}
myGrid.setGridParam({
page: postdata.page,
lastpage: res.d.total,
records: res.d.records,
total: res.d.total
});
myGrid.each(function() {
if (this.grid) this.updatepager();
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// Code to handle error.
}
});
},
I answered a similar question regarding the reporting of (server side) errors with a jqgrid.
How can I get JQGrid to recognize server sent Errors?
You can use the loadError event in jqGrid definition (see documentation). E.g.:
//Catch errors
loadError = function(xhr, textStatus, errorThrown) {
var error_msg = xhr.responseText
var msg = "Some errors occurred during processing:"
msg += '\n\n' + error_msg
alert(msg)
}

Categories