jQuery - Ajax showing empty RESPONSE / Success: not triggered when used with WordPress posts and pages - wordpress

Any help would be appreciated.
I have created a small script which works fine when used with simple php pages. Now I just tried to add this script to my WordPress posts and pages. So I used "exec-php" plugin to call the php script.
Everything works fine. But when user fills the data and submits the form, the data actually gets submitted (I can see the posted variables in firebug), but the response is not displayed under the form when used with wordpress, where as it works fine when used with plain php pages.
My jQuery code is like this:
var dataString = 'name=' + name + '&country=' + country + '&lang=' + language;
$("#paypal-submit").click(function () {
$.ajax({
type: "POST",
url: "get.php",
data: dataString,
dataType: 'html',
success: function (gotresponse) {
$('#response-id').html("<div id='id-message'><p>Got Response</p></div>");
$('#id-message').html(gotresponse).fadeIn(1500, function () {
$('#id-message');
});
$('#name').attr('onchange', 'resetForm()');
$('#country').attr('onchange', 'resetForm()');
}
});
});
When I actually view the whole process in firebug, I can see that the data is actually posted to the server.
200 OK 2.03s
But when I see the response tab in firebug console, it is empty. I think the success message is not getting triggered when used with WordPress.
I cant figure out what could be the problem? Can someone help me solve this?
NOTE: The same script works fine when used as it is, but when used with WordPress the jQuery - Ajax success does not get triggered.
1st Edit:
I just included the error: in ajax function
error:function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
Now when I submit the form I get the alert saing "You are offline!! Please Check Your Network." This error is getting triggered. So please help me now.

On you success:function() , it should success:function(data) then change .html(gotresponse) to .html(data)

Related

Halt progress of Ninja Forms if Webhooks respond with error

I'm setting up Ninja Forms in Wordpress. And I want to use the Webhooks extension to post a code to an external URL. If the code is correct Ninja Forms should submit the data on move on. If the code is wrong then the user should get an error message and try again.
How can I do this, I see no way if interrupting the submit?
In Ninja Form when you use webhook, I guess you may catch the error respond from the API with this code
$data['errors']['form'][] = $this->submit_response->result[0]->error;
So when the API respond error, in this case user has no chance to re-submit the form again unless reload the page.
When the form contain the error, Ninja form prevent the form to submit, so you need to find a way to clear/remove this error.
Few workarounds can fix this problem.
An easy way is that, you cache the respond error differently with the following code:
$data['errors']['last']['message'] = $this->submit_response->result[0]->error;
With this code, your form will not display the error message respond from API but it is possible for user to re-submit the form again and you can use the javascript code below to display the error to some HTML element
var customFormController = Marionette.Object.extend({
initialize: function() {
// Listen to submit respond
this.listenTo(nfRadio.channel( 'forms' ), 'submit:response', this.checkSubmitRespond);
},
checkSubmitRespond: function(response, textStatus, jqXHR, formID) {
if ('undefined' != typeof response.errors.last) {
var msg = response.errors.last.message;
// display error on some pre-defined element
jQuery('.error-container').html(msg);
}
}
});
jQuery(document).ready(function($) {
new customFormController();
});
Hope this help.

jQuery Ajax Stop is not invoked (No error; 200 OK)

I have a working ASP.Net 2.0 code in my development server that uses jQuery Ajax. The result of the ajax call is used to load dropdown values.
But when this code is deployed to a new DMZ server, the result is not getting populated in dropdown – though I am getting 200 OK as response. One obvious thing is that the Type is different in the response. It is expected as application/json but coming as text/plain.
I have success call back and error callback codes. Along with this I have handlers for ajax start and stop. But none of these events are getting fired. What is the reason error/stop handlers are not getting fired? How can we make it work?
Note: The behavior is same in both IE and Chrome.
Update
Also observed that there is an error logged in console, as shown below. Is it related to the "Type"? How can we address this?
Note: Also note that the Content-Length is 0 in the response headers shown below.
Success Callback
jQuery
function loadASN()
{
var receiveScanParameter = getContainerParameters();
// console.log(receiveScanParameter);
$.ajax({
type: "POST",
url: "rcvScanTXAdd.aspx/GetASNForPlant",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ receiveScanParameter: receiveScanParameter }),
success: successPopulateASN,
error: errorFunction
});
}
Global jQuery Code
//Global Ajax Error handling Function
function errorFunction(xhr, status, error)
{
if(xhr == 'undefined' || xhr == undefined)
{
alert('xhr undefined');
}
alert(status);
alert(error);
}
$(document).ready(function ()
{
//Ajax Start
$('body').ajaxStart(function()
{
//Change cursor to waiting
$(this).css({'cursor':'wait'})
});
//Ajax End
$('body').ajaxStop(function() {
//Reset the cursor
$(this).css({'cursor':'default'})
});
});
Screenshots
I figured it out.
Step 1: Observed that there is an error logged in browser’s console (saying result is null). [This screenshot is updated in the question]
Step 2: Observed that the content length of the response is zero. Also observed that there is a gzip compression happened on the response (by reading the response headers).
Step 3: Analyzed the server's web.config. It was uisng a C# httpModule for compression. In that httpModule added bypassing logic for json. [I don’t want json to be compressed with this custom module. Later I will consider adding compression to JSON when I use IIS for compression instead of custom module]. Following is the C# code segment for by-passing JSON compression
request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith("application/json")
WHen in doubt, read the API docs:
As of jQuery 1.8, the .ajaxStop() method should only be attached to document.
http://api.jquery.com/ajaxStop/
Same note can be found in $.ajaxStart docs

JQuery AJAX Call reports success in every browser but Chrome

I'm working on a bit of legacy code that is being used to authenticate users to a web application via username/password check. The code is contained within a standard ASPX page (yes, I know) and, when the page is requested it either returns status 404 to indicate an authentication failure or populates a literal on the ASPX page if all is well.
Its a standard JQuery ajax call:
$("#btnSWSignInPin").click(function () {
$.ajax({
url: "/Security/Validate.aspx",
type: "GET",
data: "Rnd=" + Math.random() + "&Identifier=" + $(".inpIdentifier").val() + "&Pin=" + $("#inpSWPin").val(),
success: function () {
$("#divSessionLogin").jqmHide();
WarnInFuture();
DoChecks = true;
},
error: function () {
ShowLogin("The password you entered was incorrect. Please try again.");
}
});
$("#inpSWPin").val("");
return false;
});
The .NET code which this calls runs fine and I can successfully step through it with no issues in VS. I have tested extensively in Safari, Firefox and IE9, all but the latter on OSX and Windows, and it executes as expected. However in Chrome (latest build) the success function is never executed, the javascript seems to think that something other than status 200 is being returned from the browser although Fiddler shows its definitely a 200 in the Response header.
Can anyone suggest what I can check to try to understand and correct this behaviour?
I think it can be a url parsing problem, please try by giving your parameters this way :
data = {
"key_1": "value_1",
"key_2": false,
"key_4": 123
};
Set
async: false
Google Chrome seems to have an issue with firing success when async is set to true.

Getting "401 Unauthorized" error consistently with jquery call to webmethod

I have been struggling to get my jquery call to a webmethod to work. I am being bounced by the server with a "401 Unauthorized" response. I must have an incorrect setting in the web.config or somewhere else that would be preventing a successful call.
Your insight is appreciated!
Call to js function the invokes the jquery call
button.OnClickAction = "PageMethod('TestWithParams', ['a', 'value', 'b', 2], 'AjaxSucceeded', 'AjaxFailed'); return false;";
JavaScript function that makes the jquery call
function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
var urlPath = pagePath + "/" + fn;
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
timeout: 10000,
dataType: "json",
success: function(result) { alert('Overjoyed'); },
error: function(result) { alert('No joy'); }
});
}
Web method in page
public partial class WebLayout : System.Web.UI.Page
{
[WebMethod()]
public static int TestNoParams()
{
return 1;
}
[WebMethod()]
public static string TestWithParams(string a, int b)
{
return a + b.ToString();
}
...
Response as seen in Firebug console
json: {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
and
"NetworkError: 401 Unauthorized - http://localhost/Care-Provider-Home/Profile/Personal-Profile.aspx/TestWithParams" TestWithParams
I have looked at and read the usual sites on the subject (Encosia, et al), but to avail. Either I am missing a critical piece, or there are some subtleties in the security parameters of my environment that preventing a call.
Here are some other potentially useful tidbits that may impact your diagnosis:
Webmethods in codebehind
Using Sitecore CMS (Does not seem to intefere, never know)
IIS7
.NET 3.5
jQuery 1.3.2
I look forward to your insights and direction--thank you!
Yes, it did get working! Since Sitecore CMS does perform URL rewriting to generate friendly URLs (it assembles the pages in layers, dynamically, similar to Master Page concept), it occurred to me that it may be causing some problem the initially caused the 401 error. I verified this by creating a separate project with a single ASPX--and with some work I was able call the web methods and get values using the jquery. I then created nearly identical ASPX in my web root, but told Sitecore to ignore it when a request is made to it (IgnoreUrlPrefixes in the web.config), after some work I was able also get it to work successfully! Thanks for your help.
The json response from the Firebug Console provides the most telling clue IMO. The System.InvalidOperationException (which strangely rides on a 401 response) suggests something more is at work.
First, googling on "InvalidOperationException webmethod jquery" returns articles which suggest serialization problems can throw this exception. To rule this out, temporarily change "data: paramList" to "data: '{}'". In addition, attach a debugger and see if the exception happens before the method executes or after it completes and attempts to serialize the result.
If the steps above come up empty, you may want to try resetting to a clean web.config or read more of the results that come back from the "InvalidOperationException webmethod" search
What form of authentication are you using, if any? The first thing that comes to mind is to make sure that your webApp in IIS is set to allow anonymous users (if you indeed desire to make the call as an anonymous user). Also that your Authentication mode in web.config is not set to Windows by mistake. If you cannot allow anonymous users and are using forms authentication, then the user will have to be logged in before this call is made from your page.
If the above are properly set, then try making a regular call to the service from server side to make sure the problem is consistent regardless of the point of invocation of the service.
Post more settings if the problem is not resolved. Hope this helps.

Jquery Ajax call to webservice is failing

Can anyone help? I have an issue with calling a asp.net webservice from jquery.. actually i think it maybe jquery ... as i have a break point and it doesn't arrive in the webservice..
Here is my jquery, the webservice method accepts 2 parameters...
So i setup a simple test to pass in 7 and 7 .. i tried replacing with the word "test" also and it doesn't work..
Basically lands in the error function which displays "sorry error happens" but the err is undefined.
jQuery.ajax({
type: 'POST'
, url: 'CallService.asmx/TempCanMakeCall'
, contentType: 'application/json; charset=utf-8'
, dataType: "json"
, data: "{'reservationNum':'7','completedReservationNum':'7'}"
, success: function(data, status) {
alert(data);
}
, error: function(xmlHttpRequest, status, err) {
alert('Sorry! Error happens.' + err);
}
}
);
Here is the asp.net webservice
[WebMethod()]
public bool TempCanMakeCall(string reservationNum, string completedReservationNum )
{
return true;
}
xmlHttpRequest.responseText has always been my goto when dealing with jQuery AJAX errors.
Try making your ASP.NET function static:
[WebMethod()]
public static bool TempCanMakeCall(string reservationNum, string completedReservationNum )
{
return true;
}
Also note that the returned JSON value is encapsulated in an object named 'd' (ASP.NET specific.) To display your return value upon success, you would need to do this:
success: function(data, status) {
alert(data.d);
}
The jquery ajax call looks fine. I think you need to make sure that the path to "CallService.asmx" is correct. The way it is now, I will only work if the file making the jQuery call is in the same virtual directory as the ASMX.
In your error callback function, you could check 'xmlHttpRequest.status' to get the http code returned from the server. This may give you another clue. If ichiban above is correct, it should be a 404.
You can check the xmlHttpRequest.responseText property. The response text is very probably an html document returned by the server that contains the reason for the error.
If you are using Visual Studio, you can also enable script debugging in Internet Explorer and put the following keyword in your error function: debugger. The browser sees this as a breakpoint and will invoke a debugger (which should be Visual Studio). Now you can check the entire contents of the xmlHttpRequest instance.
For clarity, your error function will then look like this:
function(xmlHttpRequest, status, err)
{
debugger;
...rest of your function...
}

Resources