I put this add action in my spoutnik controller like the REST doc of cakephp :
public function add() {
$this->layout = null;
$this->autoRender = false;
if ($this->Spoutnik->save($this->request->data)) {
$message = array(
'text' => __('Saved'),
'type' => 'success'
);
} else {
$message = array(
'text' => __('Error'),
'type' => 'error'
);
}
$this->set(array(
'message' => $message,
'_serialize' => array('message')
));
}
I put this JS part in my angularjs app (actually in a other domain than the cakephp site):
<form ng-controller="MessageController" ng-submit="createMessage()">
<legend>Create Message</legend>
<label>Title</label>
<input type="text" id="name" name="name" ng-model="message.name" placeholder="Title">
<label>Message</label>
<input type="text" id="email" name="email" ng-model="message.email" placeholder="ur message here">
<button class="btn btn-primary">Add</button>
</form>
and
function MessageController($scope, $http) {
$scope.message = {};
$scope.createMessage = function() {
$http({
method : 'POST',
url : 'http://www.mycakephpdomain.com/spoutnik/add',
data : $scope.message
})
}
}
Nothing work... i have no errors in chrome console, i'm totally lost :/ I just want to build an android app in angularjs with no java or PHP, and post to my cakephp website. For the moment, i try to post form an other domain (i can't touch apache configuration).
What is wrong in my code ?
Just for the record and debugging purposes:
I did not find the reason to this same problem, but looking the AJAX request done by AngularJS I found that message data from the form was no being sent as regular form data. Instead it was being sent as REQUEST PAYLOAD.
Indeed, the response from the server contained this error just before the JSON response from my view:
Warning (4096): Argument 1 passed to Hash::get() must be of the type
array, null given, called in
/var/www/test/lib/Cake/Network/CakeRequest.php on line 866 and defined
[CORE/Cake/Utility/Hash.php, line 44]
Of course, i checked that there was nothing strange by my side executed, I even tried disabling all security component and allowing AUTH *.
If you set the core.debug in php to 0, the error wont be shown and
everything will be ok, but thats not what you want for your awesome
app.*
I changed query data from $scope.message to just $('form').serialize(), but still no way.
So finally, the only solution I found was to remove the $http.post and replace it by a very know $.ajax() which just did its job as always...
So thats my suggestion, remove the $http.post and user common jQuery.ajax();
There is much confusion among newcomers to AngularJS as to why the $http service shorthand functions ($http.post(), etc.) don’t appear to be swappable with the jQuery equivalents (jQuery.post(), etc.) The difference is in how jQuery and AngularJS serialize and transmit the data. Fundamentally, the problem lies with your server language of choice being unable to understand AngularJS’s transmission natively ... By default, jQuery transmits data using Content-Type: x-www-form-urlencoded and the familiar foo=bar&baz=moe serialization. AngularJS, however, transmits data using Content-Type: application/json and { "foo": "bar", "baz": "moe" } JSON serialization, which unfortunately some Web server languages—notably PHP—do not unserialize natively.
So concretely, your $_POST variable is empty !
To go through this problem there're 2 solutions:
Change the data format in Angular config
Change the way to get the datas with PHP(Deprecated but works)
I haven't invented anything here, just linking...
Hope it'll help.
Related
I'm new to Pact.io and trying to get contract tests set up on our platform. The app is set up in such a way that each customer account has its own database schema which is directly tied to a URL subdomain. When making an API request, that URL subdomain must be provided in addition to the authorization header. I can create a static token to pass in with the consumer tests, but when Pact sends the request, it doesn't know which account to use. I don't see a way to pass in a URL subdomain as part of the consumer test and not sure how to force it to use a specific account on the provider side? Any ideas?
Here is the pact log. We are making a request for users and instead of the JSON body being returned, we get an HTML error page, even though the status code returns 200.
I, [2017-10-25T12:39:24.344559 #91639] INFO -- : Running example 'Verifying a pact between bridge_perform and bridge_learn Given one user a get request for learn users with GET /api/learner/users returns a response which has a matching body'
I, [2017-10-25T12:41:40.962186 #91639] INFO -- : Sending GET request to path: "/api/learner/users" with headers: {"HTTP_AUTHORIZATION"=>"Basic xxxxxxxxxxxxxxxxxxxxx"}, see debug logs for body
D, [2017-10-25T12:41:40.962234 #91639] DEBUG -- : body :
I, [2017-10-25T12:41:40.977995 #91639] INFO -- : Received response with status: 200, headers: {"Content-Type"=>"text/html", "ETag"=>"W/\"1bd857d3e20d3ed50aa6f48b5be15f42\"", "Cache-Control"=>"max-age=0, private, must-revalidate", "X-Request-Id"=>"8dd9a9bf-da21-44b1-8b6b-9de486a7e9ea", "X-Runtime"=>"0.007579", "Content-Length"=>"630"}, see debug logs for body
D, [2017-10-25T12:41:40.978049 #91639] DEBUG -- : body: <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Account Not Found</title>
<link rel="stylesheet" href="/stylesheets/application.css" />
</head>
<body class="indigo-bg">
<div role="main" class="large-content-area centered margin-t-xl text-center white">
<h1 class="h1">Oh, snap!</h1>
<p class="large">It looks like you've tried to access App without telling us which
account you belong to.</p>
<p class="large">To log in, try using your account's URL. Usually that looks
something like https://myaccount.app.com.</p>
</div>
</body>
</html>
Here is an example of one of the consumer tests. As you can see, we create a mock provider that has no URL/Path, so no place to provide a subdomain on the URL which specifies the account needed.
public class AdminImportedUserId {
#Rule
public PactProviderRuleMk2 mockProvider = new PactProviderRuleMk2("provider_app", PactSpecVersion.V2, this);
#Pact(provider = "provider_app", consumer = "consumer_app")
public RequestResponsePact createFragment(PactDslWithProvider builder) throws IOException {
return builder
.given("an admin with two imported users")
.uponReceiving("a get request for admin imported user id")
.path("/api/admin/users/imports/1")
.method("GET")
.headers(new ProviderClient().getHeaders())
.willRespondWith()
.status(200)
.body("{\"meta\":{},\"linked\":{\"contexts\":[{\"id\":1,\"class\":\"Domain\"}]},\"imports\":[{\"id\":\"160\","
+ "\"context_id\":\"1\",\"user_name\":\"user10 Royer\",\"context_description\":\"Dev Environment\","
+ "\"context_type\":\"Domain\",\"completed\":17,\"total\":17,\"state\":\"complete\",\"new_user_count\":0,"
+ "\"restored_user_count\":0,\"updated_user_count\":17,\"deleted_user_count\":0,\"ignored_user_count\":0,"
+ "\"deported_user_count\":17,\"invalid_rows\":[],\"created_at\":\"2017-09-23T13:13:21.132-06:00\","
+ "\"user_id\":4078}]}")
.toPact();
}
When you say "URL subdomain" are referring to a separate Host header e.g. someaccount.foo.com or a prefix on the URL e.g. `http://foo.com/someaccount'?
Either way, these would go into your consumer test as either the URL/Path or a specific header.
Everyone, I am asking this because I really can't understand how I can send data from my webservice(vb.net) to my ionic app(android/ios/windows).
I used Firebase Cloud Messaging and it worked perfectly fine, but there's a case I need to handle and I wanted to use FCM but can't because it needs the internet connection.
Basically, I want to send a signal from one app to my localserver and then the localserver sends a post to another app via LAN, so I can't have an internet connection.
How can I achieve this?
Do I really need to use an external service to manage the connections to my devices?
this is what i did in receiving and reading the json from my own wcf.
import http:
import { Http } from '#angular/http';
add this to your constructor:
public http: Http
getting the data from uri:
this.http.get('http://your_url').map(res => res.text()).subscribe(data => {
console.log("XML MO: "+data.toString());
this.DataBind(data);
reading the response:
DataBind(data: any) {
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(data.toString(),"text/xml");
this.customerTitle = xmlDoc.getElementsByTagName("myData")
}
and in your html file:
<ion-item>
<ion-label floating>My Data</ion-label>
<ion-input enabled="false" type="text" [(ngModel)]="myData"></ion-input>
</ion-item>
you should also know that ion-input is a textfield. And it should work already
Is there a way to create a serious HTML/CSS/JS project with multiple HTML, CSS, JS files on JSfiddle.net ?
If yes, how to do it ?
I want to create a basic mobile apps based on HTML/CSS/JS, about a dozen of HTML/CSS/JS files. I would like to develop it all on JSfiddle, my favorite Online JavaScript IDE. But JSfiddle.net while a clean way to test projects stays limited to:
1 html file (personal)
1 CSS file (personal)
1 JS file (personal)
several external resources (CSS, JS libs, data) which request you another webhosting.
The official doc suggesting Github hosting for 1HTML/1JS/1CSS/someDataFiles is not satisfying. I wish all on JSFiddle, and more files in my project.
You can do it inside a jsFiddle but there are few limitations, and you are probably not going to be satisfied with it.
You can test only 1 HTML multiple pages template. But in case of jQuery Mobile framework this will be enough, as you can place numerous jQM pages inside a 1 html file.
For example, this is my jsFiddle template when helping to this group: http://jsfiddle.net/Gajotres/yWTG2/
You cant use normal form submitting. Instead you should use ajax to sumbit form data.
In my other answer you can find solutions for ajax form submitting and how to send parameters during the page transition: jQuery Mobile: Sending data from one page to the another
In case you want to communicate with an remote host:
var ajax = {
sendRequest:function(save_data){
$.ajax({url: 'http://localhost/JSONP_Tutorial/json.php',
data: save_data,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
if(result == "true") {
$.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
} else {
alert('Login unsuccessful, please try again!'); // In case result is false throw an error
}
// This callback function will trigger on successful action
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
}
}
jsFiddle has a stupid policy where they want to prevent usage of full HTML files. They are trying to enforce this with stupid error warnings in HTML content part. You will need to have something like firebug plugin for Firefox or Chrome to remove this stupidity. Or you can even do it with Grease Monkey plugin.
In case you want to use full HTML template like in this example: http://jsfiddle.net/Gajotres/yWTG2/ you will need to use your javascript code in onDomready state.
Some functionalities are not going to work. Like window.orientationchange event.
Ive been scratching my head with this for a few days now.
I have written a mobile specific website using plain old html and jquery.
It used ajax with json responses to get data from a service written using service stack.
all works perfectly fine from desktop and lots of different mobile i have tried (android, iphone, bb etc)
However there seems to be a specific issue with my handset (Samsung Galaxy S2 on vodafone)
When the handset is on wifi the ajax works perfectly and the json object is received from the service and processed correctly.
However when on mobile data the response does not come back as json but as the service stack web page (it looks like its not being told to return json correctly)
Im wondering if the headers could be being stripped out by vodafone or someting?
this is the ajax call being used
$.ajax({
url: sgee.ApiUrl + "/api/GetRegionId/" + sgee.App.postcode,
type: 'GET',
dataTye: 'json',
contentType: "application/json;charset=utf-8",
cache: false,
success: function (data) {
if (data.success) {
sgee.App.EnquiryId = data.enquiryId;
sgee.App.RegionId = data.regionId;
sgee.App.RegionName = data.regionName;
$("#regionTxt").html("We have identified that you live in the " + sgee.App.RegionName + " supply region.");
sgee.EndLoading(250);
sgee.HideStep(2);
} else {
sgee.SetValidationError("#pcodeControl", "Please enter a valid UK postcode");
}
},
error: function () {
sgee.SetValidationError("#pcodeControl", "Please enter a valid UK postcode");
sgee.SendError("Error on /api/GetRegionId/", "sgee.Step1");
},
complete: function () {
}
});
This is the data expected
{"postCode":"s63","regionId":14,"regionName":"YORKSHIRE","enquiryId":578106,"success":true,"returnedId":0}
and when running on mobile this is what i am receiving (ill not include the whole as it is long but it is just the html response as if i hadnt set the response type or browsed to the page)
<!doctype html>
<html lang="en-us">
<head>
<title>GetRegionId Snapshot of 03/08/2012 13:59:50</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
This really is driving me mad as it is impossible to debug (at least i cant find a way) i am using the android chrome remote developer tools to step through code but i cant capture the http request and response as it is on the mobile network.
Just guessing... But you're expecting json content right? If so, why is your response "text/html" instead of "application/json"?
You have a typo in there... "dataTye: 'json',". Could this be it?
I think is due to type of form submission. use post instead of get...
I wanted to know the answer to a simple question but i have'nt found a good one
(i've google it for hours :) )
I'm playing with the sl4a with python and i can send events from js to the python script, but the js is not catching the eventPost i put in the code below from python to js.
Anyone knows how is this been done or if there is another way without the registerCallback?
HTML CODE :
<html>
<head>
<script>
var droid = new Android();
function doit(){
droid.makeToast("Text send :=>"+document.getElementById("msg").value);
droid.eventPost("doit",document.getElementById("msg").value);
}
function alert_me(data){
droid.makeToast("All done!");
document.getElementById("msg").value = '';
}
droid.registerCallback("done",alert_me);
</script>
</head>
<body>
<input type="text" name="boton" id="msg" value="" />
<input type="button" name="boton" value="Go!" onclick="javascript:doit()" />
</body>
</html>
PYTHON CODE:
import android,time
if __name__ == '__main__' :
droid = android.Android()
droid.webViewShow("file:///sdcard/sl4a/scripts/sample.html")
while True:
event = droid.eventWait().result
if event["name"] == 'doit':
droid.makeToast("Event catched! %s" % event['data'])
droid.eventPost("done","Done message")
time.sleep(2)
droid.exit()
This is simple to get working, but isn't obvious or well documented.
First you want to get a hook to the Android object inside the webview. Then you can use it to register one or more callbacks. For a simple example, we'll just do one that pops an alert with a message from Python.
var droid = new Android();
droid.registerCallback("echo", function(msg) {
alert(msg.data)
});
In this case, echo is the name of the event type you want this callback to handle. So this will handle 'echo events'. The event names are arbitrary strings, just call them whatever makes sense.
In the Python script that launched the webview, you can now post events to the registered handler whenever you like.
droid.eventPost("echo", "hello world")
The second argument here is the message you want to pass to the JavaScript callback.
Note that although you pass the message back as a string, it arrives in the JavaScript function as an object. That object, we're calling it msg above, has an attribute called data which contains the string you passed from the Python side.
Unfortunately I have never personally been able to get this working, using both registerCallback() and eventWaitFor(). However, if you are still keen on getting this working, I strongly recommend you head on over and download sl4a_r5x – an unofficial but newer and updated release of SL4A. In it is support for using FullScreenUi's based off the same xml code that native Android apps use. With this you can do what you're after and examples can be found on the page.Hopefully this has been helpful and you're still interested in SL4A!