jsonp and zendframe work 1 doesnt return any thing(im working with phonegap and use Zend as a service) - zend-framework

this is my zend controller
and this is how i called my service
please teach me how. it's important ! thank you so much

Seems like a bit of extra work with what you have there. I've done it this way in both ZF1 and ZF2:
PHP
// notice 'searchteams' is lowercased. There's been problems in the past
// when camelcasing action names, by default I believe ZF is looking for
// a lowercase action name unless you've configured it otherwise
public function searchteamsAction()
{
// make sure this is an ajax request (this is a method I usually write, if
// Zend has one you could use that here)
if ($this->isXmlHttpRequest())
{
// instantiate model, get the results, good
// disabling view and layout, good
// headers, never really had an issue that needed the headers to be set here
// would simply have..
echo json_encode($res);
}
}
JS: in the success method in the AJAX call, I'd do this:
success : function (data){
// parse the json
var parsed_data = $.parseJSON(data);
console.log(parsed_data);
// do stuff with parsed_data
}
Hope that helps.

Check your datas with a return var_dump($res); before $this->_response->setHeader(...
if you have datas, try to add $this->_response->setHeader('Content-Type', 'application/json', true);
If not work, try to replace
$this->_response->setHeader(...);
$this->_response->setHeader(...);
$this->_response->setHeader(...);
$this->_response->setHeader(...);
and echo Zend_Json::encode($res);
by only
return $this->_helper->json($res);
You can also see the error on the side of jQuery with something like:
error: function(xhr, status, error) {
alert("error status: " + status);
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
I hope it will help you :)

Related

How to know the response of a callback rest call protractor

I am running an automation script. We have a scenario where Java makes a callback REST call to UI. Below is the code where am doing httpGet to that URL. I want to know when the response comes. If it comes how to know that. I searched a lot I din't find a clear answer anywhere. Please give some hints!
http.get(siteUrl, function(response) {
var bodyString = '';
response.setEncoding('utf8');
response.on("data", function(chunk) {
bodyString += chunk;
});
response.on('end', function() {
defer.fulfill({
statusCode: response.statusCode,
bodyString: bodyString
});
});
}).on('error', function(e) {
defer.reject("Got http.get error: " + e.message);
});
//If we are sure that response has come, then extract it
httpGet("http://testurl").then(function(result) {
//alert('inside test automation');
console.log(result);
});
You can use the response detail whether success or fail with "response code", there are lots of way using interface as callback, using methods by checking response code, lots of network library available - volley, okhttp rest client etc...
help : response code detail
if(response.statusCode == 200) {
// do success work read response etc...
// you can call methods what you want if success happen
} else {
// you can check other status code too..
// call methods if api get fail.
}
Hope this would help
good luck.

Returning multiple server operations in Meteor in one call. How to?

I've very new to this but essentially I want to create a cleanup function that runs on the server that I can call at any time to reset various things like collections and sessions in one call.
I'm really very new but this is what I have so far. Can someone please help fill me in where I'm going wrong?
I am trying essentially to return two things (and many more in the future) at once. I've done some research on this but it's as far as I can fathom with my skill level at the moment.
It would be much appreciated. Thank you.
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
return Meteor.methods({
//Use this to emplty the form data
cleanUpForms: function() {
var cleanUpPhoneNumbers = orgPhoneNumbers.remove({});
var cleanUpEmailAddresses = orgEmailAddresses.remove({});
return {
cleanUpPhoneNumbers : cleanUpPhoneNumbers;
cleanUpEmailAddresses : cleanUpEmailAddresses;
}
}
});
});
}
By the way, the current error is for line :
cleanUpPhoneNumbers : cleanUpPhoneNumbers;
It states:
Unexpected token
I'm not sure if I'm doing this correctly. I essentially want it to run multiple cleanups in one go, all called from the client to the server with the above method. I hope that makes sense.
The unexpected token is likely for the ; at the end of the line. When building a JSON object, use a comma between the elements...
return {
cleanUpPhoneNumbers : cleanUpPhoneNumbers,
cleanUpEmailAddresses : cleanUpEmailAddresses
}
I think this will return the number of items that where removed. Is that what you are expecting?
Also, just in case you didn't know, you can run 'meteor reset' from the command line to erase ALL collections.
This is the fully adjusted code for any future reference which may help others. Thanks so much to FloatingCoder for the help.
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
return Meteor.methods({
removeAllNewOrgs: function() {
var PhoneNumbers = newOrgPhoneNumbers.remove({});
var Organsations = newOrgansations.remove({});
//If we want to return the data, to get around only being able to return one thing at a time we're return via an array. CLEVS!
return {
PhoneNumbers : PhoneNumbers,
Organsations : Organsations
}
}
});
});
}

Simple use of dispatch

I'm about to set up a stupid play/scala app whose only job will be to make some http call once it receives calls itself
GET /abracadabra controllers.Application.abracadabra(stuff: String)
and then
def abracadabra(stuff: String) = Action {
Logger.info("called for stuff: "+stuff);
// call this other URL with 'stuff' as get parameter
// log http return status code and return Ok/200 anyways
}
Now for the second (commented) part I thought about using Dispatch.
I've read the docs but I can't just figure out how to use Promises and all that.
If anybody could point me to some sample code or something, it will be much appreciated
Since Play! has a built in Async library, you should probably go ahead and use that unless there's a feature in Dispatch that you specifically need.
Here's a short example:
def abracadabra(stuff: String) = Action {
Logger.info("called for stuff: "+stuff);
Async {
WS.url("http://stackoverflow.com/").get().map { response =>
Ok("I got it: " + response)
}
}
}
The documentation is here: https://github.com/playframework/Play20/wiki/ScalaWS

What's the best way to handle a REST API's 'create' response in Backbone.js

I'm using backbone.js to interact with a REST API that, when posting to it to create a new resource, responds with a status of 201, a 'Location' header pointing to the resource's URI, but an empty body.
When I create a new model at the moment, its successful, but the local representation of the model only contains the properties I explicitly set, not any of the properties that would be set on the server (created_date, etc.)
From what I understand, Backbone would update its representation of the model with data in the body, if there were any. But, since there isn't, it doesn't.
So, clearly, I need to use the location in the Location header to update the model, but what's the best way to do this.
My current mindset is that I would have to parse the url from the header, split out the id, set the id for the model, then tell the model to fetch().
This seems really messy. Is there a cleaner way to do it?
I have some influence over the API. Is the best solution to try to get the API author to return the new model as the body of the response (keeping the 201 and the location header as well)?
Thanks!
Sounds like you will have to do a little customization.
Perhaps override the parse method and url method of your model class inherited from
Backbone.Model.
The inherited functions are:
url : function() {
var base = getUrl(this.collection);
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + this.id;
},
parse : function(resp) {
return resp;
},
and you could try something like:
parse: function(resp, xhr) {
this._url = xhr.getResponseHeader('location')
return resp
}
url: function() {
return this._url
}
Yes, backbone.js really wants the result of a save (be it PUT or POST) to be a parseable body which can be used to update the model. If, as you say, you have influence over the API, you should see if you can arrange for the content body to contain the resource attributes.
As you point out, its makes little sense to make a second over-the-wire call to fully materialize the model.
It may be that a status code of 200 is more appropriate. Purists may believe that a 201 status code implies only a location is returned and not the entity. Clearly, that doesn't make sense in this case.
With Backbone 0.9.9, I couldn't get the accepted answer to work. The signature of the parse function seems to have changed in an older version, and the xhr object is no longer available in the function signature.
This is an example of what I did, to make it work with Backbone v0.9.9 and jQuery 1.8.3 (using a Deferred Object/Promise), relying on the jqXHR object returned by Backbone.Model.save() :
window.CompanyView = Backbone.View.extend({
// ... omitted other functions...
// Invoked on a form submit
createCompany: function(event) {
event.preventDefault();
// Store a reference to the model for use in the promise
var model = this.model;
// Backbone.Model.save returns a jqXHR object
var xhr = model.save();
xhr.done(function(resp, status, xhr) {
if (!model.get("id") && status == "success" && xhr.status == 201) {
var location = xhr.getResponseHeader("location");
if (location) {
// The REST API sends back a Location header of format http://foo/rest/companys/id
// Split and obtain the last fragment
var fragments = location.split("/");
var id = fragments[fragments.length - 1];
// Set the id attribute of the Backbone model. This also updates the id property
model.set("id", id);
app.navigate('companys/' + model.id, {trigger: true});
}
}
});
}
});
I did not use the success callback that could be specified in the options hash provided to the Backbone.Model.save function, since that callback is invoked before the XHR response is received. That is, it is pointless to store a reference to the jqXHR object and use it in the success callback, since the jqXHR would not contain any response headers (yet) when the callback is invoked.
Another other to solve this would be to write a custom Backbone.sync implementation, but I didn't prefer this approach.

ajaxcontroltoolkit setting hidden value after asyncfileupload has completed

I have an asyncfileupload control that I'm using from the ajaxcontroltoolkit. On the file complete in the code behind I process the file and write the information in the file to a database. I get the id of the record from the database, and this needs to be written to an asp hidden field. I've tried just setting the value:
fldImageID.Value = pimg.IdImageGroup.ToString();
I've tried Registering a script like I've seen in an example on a website:
ScriptManager.RegisterClientScriptBlock(
ImageFileUploader,
ImageFileUploader.GetType(),
"script1",
"alert('hi'); top.document.getElementById('"
+ fldImageID.ClientID
+ "').value='"
+ pimg.IdImageGroup.ToString()
+ "'; top.document.getElementById('"
+ lblError.ClientID
+ "').innerHTML = 'image uploaded'",
true);
I've just tried embedding javascript in a response.Write call from the method I've set to process the uploaded file. Nothing I've done has worked so far. After I've done everything the hidden field still does not contain the required value.
This is pretty easy with jQuery. Have an html hidden input control placed in your page, not the asp:hidden input control. Add a class lets say "hiddenPhoto" to your html hidden control.
so lets say our control html is like this
<input type="hidden" class="hiddenPhoto" runat="server" id="hdPhotoName" />
Now access it using class selector in your OnClientUploadComplete js method and set its value. Have it declared runat="server" in order to access its value on the server side.
Regards
I found an acceptable solution back when I was working on this. And since then I've received emails from people who have had the same problem and have been asking if I found a solution. So I'm presenting it here, stripping out any extraineous code:
From the user control that has the FileUpload control I first set the session variable on the back side in the FileUploadComplete handler:
*in the ascx file (upload_chart.ascx) I have the AsyncFileUpload, what is important is the OnUploadComplete and the OnClientUploadComplete:*
<ajaxToolkit:AsyncFileUpload
OnUploadedComplete="FileUploadComplete1"
OnClientUploadComplete="UploadComplete1"
ID="ImageFileUploader"
runat="server" />
*in the code behind of the ascx file (upload_chart.ascx.cs) I handle the FileUploadComplete:*
public void FileUploadComplete1(object sender, EventArgs e)
{
try
{
if (ImageFileUploader.FileBytes.Length > 0)
{
// File data is in ImageFileUploaded.FileBytes
// Save it however you need to
// I saved it to a database, in a DBImage Object class I created
// DBImage is specific to my application
ODS.Entity.DBImage pimg =
ODS.Data.DataRepository.SaveImageBytes(ImageFileUploaded.FileBytes);
// Set the ImageID1 in the session
Session["ImageID1"] = pimg.IdImageGroup.ToString();
}
else
{
// error handling for an empty file, however you want to handle it
}
}
catch (Exception Ex)
{
// error handling for an unhandled exception, whatever you want to do here
}
}
Javascript and script methods are used to set the value on the page, here is my codebehind for the script method:
// on the aspx page code behind (chartofthedayadmin.aspx.cs) I have the webmethod:
[System.Web.Services.WebMethod]
public static string GetImageID1()
{
System.Web.SessionState.HttpSessionState Session = System.Web.HttpContext.Current.Session;
String retval = Session["ImageID1"].ToString();
Session["ImageID1"] = null;
return retval;
}
Here is the javascript:
// on the aspx front end (chartofthedayadmin.aspx) I have the javascript
// to call the Web method and the javascript failed message:
function UploadComplete1() {
var str = PageMethods.GetImageID1(uploadSuccess1, uploadFailed);
}
function uploadFailed() {
alert('error occurred or some meaningfull error stuff');
}
*// javascript on the user control (upload_chart.ascx) to set the value of the hidden field*
function uploadSuccess1(result) {
document.getElementById('<%= fldImageID.ClientID %>').value = result;
}
note: Make sure your scriptmanager has EnablePageMethods="true".
The better and more simple solution is in code behind:
string script = String.Format("top.document.getElementById('hdnFilename').value='{0}';", safeFilename);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "hdnFilenameFromCodeBehind", script, true);
In my case, safeFilename is the unique filename, after handling duplicate filename, i.e. sample_5.png in the 5th upload of sample.png.
See http://forums.asp.net/t/1503989.aspx