How to get the array in ajax success function - wordpress

I have passed array as return array($posts,$count) from my ajax file.
now in success function i wnat both this array
How to get this array in my success function
I have written as below but i dont get any this in my console :(
in my ajax_post.php
return array($posts, $count);
jQuery.ajax({
url: 'http://localhost/abc/wp-content/themes/directory/Templates/ajax_post.php',
data: {
'action':'example_ajax_request',
'city' : city
},
success:function(data,count) {
// This outputs the result of the ajax request
console.log(data,count);
//loadPopup(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});

If your success function is not logging anything at all in your console, then it probably isn't getting called at all.
What do you see in your console? Do you get an error message after your ajax call? What if you try to just copy / past your jQuery.ajax call directly in the console, what happens then?
It's a bit hard to answer here without details of your function on the PHP side and without error messages, but I suggest you try to first return a simple data type from PHP (just a mock value) to make sure your function is indeed getting called and returns properly when called. If that works then you know your problem is with the data type your are returning. If it doesn't, then the problem is with your AJAX call.
You might very well be having problems with AJAX requests because you are doing them on localhost and that might be causing Cross-Domain request problems.
This question / answer actually explains the concept and the solution to that very well. I think you should at least get a reply to your request if you do that : Make cross-domain ajax JSONP request with jQuery

Related

Meteor.call is very slow when responding back

I am facing performance problem with Meteor.call(). I have a method on server side which gets execute within a millisecond but when I seek a response in the client side, it is taking long to get the response data inside the callback function. Is anyone experience the problem before?
I was using Meteor 1.12.1 and updated to Meteor 2.1.1 hoping to solve the problem by updating but I didn't find any difference.
Update: I am facing issue on all environment (osx, linux, windows).
For eg: This is my server code
Meteor.methods({
newEntry() {
//This method is executed within millisecond
}
})
This is my client code
function submitEntry(data) {
Meteor.call(
'newEntry',
data,
(error, res) => {
//Here I am getting the response after long wait.
},
);
}
Can somebody help me on this?
I found the solution. As per the Meteor docs.
Once the Method has finished running on the server, it sends a result message to the client with the Method ID generated in step 2, and the return value itself. The client stores this for later use, but doesn’t call the Method callback yet. If you pass the onResultReceived option to Meteor.apply, that callback is fired.
Ref: https://guide.meteor.com/methods.html#advanced-boilerplate
So if you want your call back to be triggered once the server method return the value then you can use Metor.apply method with the option onResultReceived.
Meteor.apply(
"methodName",
[...params],
{
onResultReceived: function() {
// Whatever you want to do after callback.
}
}

MeteorJs "loginWIthPassword" seems not to work in method

It seems that the "Meteor.loginWithPassword" function does not work when called in a method.
I want to create my login form with autoforms and so I created a callback method which get called after a user submitted the login form. The form gets called the right way but the loginWithPassword function does not seems to work.
This is my method (on Client & Server side)
Meteor.methods({
autoform_test_login : function (doc) {
console.log('Called login method');
if (Meteor.isClient) {
Meteor.loginWithPassword('test', 'test', function(e) {
if (e) {
console.log(e);
}
});
}
}
});
My autoforms calls this method when submitting with:
{{#autoForm schema="Schema_Login" id="form_login" type="method" meteormethod="autoform_test_login"}}
....
When submitting this form I get this error:
Error: No result from call to login {stack: (...), message: "No result from call to login"}
When I now open my Browser console and type in:
Meteor.call('autoform_test_login');
I will get the same error.
But: When I type the following in my console it works (The error now is: Username not found):
Meteor.loginWithPassword('test', 'test', function(e) {
if (e) {
console.log(e);
}
});
My method do absolutely nothing else then this snipped so I am asking myself whats going wrong here.
Ps.:
I know that I added the "test" as Username and "test" as password - its just to test. Even when the input is the right the error is always the same.
Okay, so I got a response and now I know why this is not working as expected.
loginWithPassord may only be executed on the client.
When you use Meteor.methods on the client, it will still run the functions you define within it on the server. That is why it won't work to have the loginWithPassword call within a Meteor.methods function.
Simply use this function anywhere else on the client. For example - directly within some template event.
Took me like forever to find out why it wasn't working.
Make sure that autoform is actually passing the correct values. If you've made a mistake in you're schema setup it will automatically clean the values (set to undefined) without throwing an error.
I'm also not entirely sure if using it with method set will work in this case, as you want to do the login call on the client not the server (I think).
Make sure your current Meteor instance has an active connection with the mongo database pointed to by variable MONGO_URL. Meteor.loginWithPassword fails to give error feedback when this connection gets closed or broken.

Get data from the ajax response

For school, i have to develop a Twitter client with ASP.NET.
In the app, i have a list of tweets with a delete link. This link is created with the helper Ajax.ActionLink() and i specified a callback function for OnSuccess event.
This link is okay : the action is performed, the callback is triggered BUT i can't access data sent in the Ajax response.
The callback receive only one argument. Here is the dump of this object :
>> Sys.Mvc.AjaxContext
$0: 0
$1: null
$2: Sys.Net.XMLHttpExecutor
$3: Sys.Net.WebRequest
$4: null
Where is my responseText ? I know that the response has a content (according to Chrome developer tools) and i really want to access it.
Bonus : can Ajax client automatically parse the response as JSON (the action returns JSON properly with the JSON method) ?
Thanks ! ;)
The deadline of this school project is over.
I used get_data on the response.
I'm quite disappointed by the lack of documentation for this trivial need. Even now i know the way, i can't find that on MSDN… Such a pity. :(
Back to my precious Ruby on Rails, i feel better.
Good day and thanks for your help anyway ! :)
Try calling get_object() on your AjaxContext to get a javascript object or get_data() to get the text. An easier method though is to have your OnSuccess function take an argument which will be the object returned.
public ActionResult ReturnJson()
{
return Json(new { TestMessage = "Hello, world!" }, JsonRequestBehavior.AllowGet);
}
And the view...
<script type="text/javascript">
function AjaxSuccess(obj) {
alert(obj.TestMessage);
}
</script>
#Ajax.ActionLink("Say Hi", "ReturnJson", new AjaxOptions() { OnSuccess = "AjaxSuccess" })
If you want to access the responseText within your code you do not want to use AJAX(Asynchronous JavaScript And XML), you want to use SJAX (Synchronous JavaScript And XML).
When using AJAX your code will not wait for the responseText it will just continue to execute so if you try referencing it later in your code it may not work as it might not have processed yet.
When using SJAX your code will wait for the responseText before continuing to execute.
I don't use ASP.NET so I can't help with the code.
Here is how it is done in JavaScript: JavaScript - AJAX / SJAX - Submit Form Data to a Script

Loss of data in a JQuery call to a WebService

I've made a JQuery function that makes a call to a web service, the web service returns an int but somewhere between the web service returning its value and the JQuery picking it up the data is getting lost. below is my Jquery Function:
//Make a call to a web service to get the latest number of comments for this item
WebDesign.wfGetNumberOfCommentsForWebDesignItem(vintCurrentItemID,fGetNumberOfCommentsResult);
function fGetNumberOfCommentsResult(GetNumberOfCommentsResult){
//If the number of comments returned is not zero update the the number of comments
if (GetNumberOfCommentsResult != -1 && GetNumberOfCommentsResult != null)
{
vspanCommentsNumber.html(GetNumberOfCommentsResult);
}
else
{
vspanCommentsNumber.html("Unknown");
}
}
The variable GetNumberOfCommentsResult is null, not every time but I'd say about 10% of the time. I've recorded the data that the web service returns to the JavaScript and it's not null, it's valid data, so I'm at a loss as to how the JavaScript variable is set as null. Any ideas?
Can you confirm that you are running this in a callback, when the call to the webservice is guaranteed done, and not some timed method using setTimeout ? in the second case, a race condition could explain the variable results that you are getting.
Using FireBug (add-on for Firefox), on the Console tab you can see what data is being returned from the web service call, as well as what data is being passed.
First verify the data being moved back and forth. This is the easiest way to find a truly reproducible case.
Also, it would be helpful to see how you are calling the web service on the JavaScript side.
use fiddler or something similar to monitor http requests and actually grab the response when it is null, there has to be something different about it.

Ajax function throwing WebServiceFailedException

I am using same asp.net page to edit and add data, only with some fields disabled and enabled accordingly. Now when I call webmethod from the add page, it's working fine, but when I call it from edit page, it is not. Though I am using the same javascript function to call the server side method. Please see the code:
.aspx:
function KeyCheck()
{
var KeyID = event.keyCode;
if(KeyID==46)
{
PageMethods.Delete_files(CurrentObj.id);
}
Now when I try to call this same method through edit, its generating following error :
Microsoft JScript runtime error:
Sys.Net.WebServiceFailedException: The
server method 'Delete_files' failed
with the following error:
If you look here they discuss a similar problem. Although the last answer wasn't selected I would still recommend doing what he says. After your first parameter you can pass two function callbacks; one for a successful Ajax call and one for a failure.
Your function should look more like this:
var onDeleteSuccess = function(result) {
//Successfully deleted files, maybe display confirmation to user.
};
var OnDeleteError = function(result) {
//Deleting files unsuccessful, display error to user.
};
PageMethods.Delete_files(CurrentObj.id, onDeleteSuccess, OnDeleteError);
Try adding the "missing" (although they should be optional) parameters to your PageMethod call and see if that solves it.
Edit:
I found a closed bug at connect.microsoft.com about this problem. Have you tried using the page only in IE7? If so, test it in other browsers and see if it works. If it does your only option may be to upgrade IE7 to a newer version or re-open the issue.
Edit after comments:
Try placing this code before your PageMethods.Delete_files function call:
PageMethods.set_path("PageYouAreTransferringto.aspx");
I think the handler you're calling is confused about which server-side page method to call since it appears (to the browser and JavaScript) that you're on a different page.

Resources