Pebble.js ajax request with post data. No data in request - javascript

I just started fiddeling with pebble.js for a prototype. I have to make a connection to a server and send user data from the pebble (login information) to the server for a handshake and send back data from the server to the pebble. I am using pebble.js because its easy for prototyping.
Now I am using the ajax library (http://developer.getpebble.com/docs/pebblejs/#ajax) to setup the connection. I have the following code:
ajax(
{
url: URL,
method: 'post',
type: 'json',
data: {
auth : 'test'
}
},
function(data) {
// Success!
console.log(JSON.stringify(data));
},
function(error) {
// Failure!
console.log('no response');
}
);
In PHP on the server I get the complete header information by apache_request_headers(); and send it to the pebble with echo json_encode(apache_request_headers());
This results in an output of console.log(JSON.stringify(data))
{"Host":"192.168.0.113","Content-Type":"application/json","Accept":"*/*","Connection":"keep-alive","Cookie":"v2ci_session=55MmpPmzb2cvBWiq3VNgneHexYzBtIFr46Ycb94s2KNKwmnz%2FStJq3euLpUSuBmbsKmKou2915ZR5Cp%2FA7xXnK7FO5EHcnem3Xi6gLpAJPXCF51sQxVQn%2BP1fAmlDqEzSnZEVkbhAO3LkZzALdnjzUc2SPyRCdVx70xAnkohQVH%2BuaU7qZtlCtYwJ7MYQqwa1%2BXuPfw9Vb7vgduYqoWMB%2FVIab5uDPe1KnIxZ08reU1PHVTWXcXXyGCEwmYfCYDkXZSIH%2FcnM%2B4oKAu3kEalGX9jxEVvC6VKz4mAdg7O5Q4Ns%2BEKyTR5VqrpisfZcY2VWOX8ipjCuYMTTosY9Lm%2F0qSpU4P%2B2ObuXCbsJIYviK2EsQqj6%2BWNo0L3DEK6L2N7","User-Agent":"PebbleApp/20141016231206 CFNetwork/711.1.12 Darwin/14.0.0","Accept-Language":"nl-nl","Accept-Encoding":"gzip, deflate","Content-Length":"6"}
As you can see no data is send within the request.
Anyone have an idea why no data is send with the request?
Solved
I was able to solve it through the github of pebblejs. For people with the same problem:
When the 'type' is set to 'json' the ajax library does not only expect the response to be json, but also the data that is posted is posted as json. If you want to gather this data in an array in PHP use the following code:
json_decode(file_get_contents('php://input'), true);

Related

Error 405: Method not allowed

I have my json data which i need to be posted to a url or just update the json data in one of my site urls. But i get the 405 error.
This is my code.
$.post("details", {name: "John", location: "us"});
405 errors can be traced to configuration of the Web server and security governing access to the content of the Web site. It seems that the server to which you are sending the Post request(your Site's server) has been configured to block Post request. You can configure your server to allow the Post request. For more details, go to http://www.checkupdown.com/status/E405.html
I had the same problem. My failure was in the sort of the request:
I had a "POST" request in my mockserver.js:
{method: "POST", path: "app/Registration/sendRegisData.*", response: function (xhr) { xhr.respondFile(200, {}, "../testdata/getUser.json"); } }
and tried to use this path with a "PUT"-call in my controller:
$.ajax({
url: "z_dominosapp/Registration/sendRegisData",
type: "POST",
data: data
}).done(function(){.......});
First, I didn't noticed it and was wondering why only the "fail" part of the ajax call was called. Maybe this careless mistake of me helps you in any way.

Sending a json object using ajax to a servlet and receiving a response json object

I'm trying to send a json object using ajax to a servlet. The object is to be changed and sent back to the client. This is the code I used to send the json object from client to server.
function sendJson(jsonObj)
{
var parsed = JSON.parse(jsonObj);
$.ajax({
type: 'get',
url: 'GameLogic',
dataType: 'JSON',
data: {
loadProds: 1,
parsed: JSON.stringify(parsed)
},
success: function(data) {
},
error: function(data) {
alert('fail');
}
});
}
I only have a basic knowledge of javascript. As I understand this piece of code just sends a json object to a servlet. When receiving the response from the servlet, how do I get it? I searched for this and found functions similar to above function to receive response. I don't understand what this success: function(data) part does.
Can someone explain me the way to send a json object and receive the response to and from a servlet.
When I send a json object to the servlet, is there any way I can know whether it is received by the servlet, other than sending the object back as the response.
Ver simply, the answer is already in your code.
The ajax method of jquery has to callback methos for success and error.
Both are already impl. in your example but doing nothing!!
Here your code with comments pointing to the callback impl.
{
var parsed = JSON.parse(jsonObj);
$.ajax({
type: 'get',
url: 'GameLogic',
dataType: 'JSON',
data: {
loadProds: 1,
parsed: JSON.stringify(parsed)
},
success: function(data) {
// PROCESS your RESPONSE here!!! It is in "data"!!!!
},
error: function(data) {
// This is called when the request failed, what happend is in the "data"!!!
alert('fail');
}
});
}
Impl. something in the success callback and debug it with your browser dev tools to see what's inside of "data".
As you changed your question more about how to handle the communication in general and how to know if your request was received. Here my normal approach.
First I define an envenlope for every request and response which is always the same. It can look like this:
{
status: OK | ERROR,
message: "possible error message etc."
data: JSON Object representing the payload.
}
After doing this I can impl. a generic logic to send and receive message between server and client and every side nows how to handle the envelope. To make sure a message is received, could be processed etc.
Then you have this:
Make an ajax call to your server.
2a. If there is topoligical problem your error callback on client side is called. Request failed, server not reachable!
2b. The message was received by the server. The server can now process the payload regarding the URL used to call the server. The server method succeed it will write an OK in the envelop and his possible result in "data" as payload. If the method fails, it sets "status" to "ERROR" and provides an proper message, data is empty.
The client receives data on the success callback and it can inteprete the "status" field if it's a usefull response or if it's an error.
Hope that helps
The success:function() part goes like this
A function to be called if the request succeeds. The function gets passed three arguments:
The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified
a string describing the status
the jqXHR (jQuery-XHR) object
What this means is - if your ajax request was successful, the server will return you some response, ie, the data. This "data" can be used in the function.
$.ajax({
...
success: function(data) {
// process the "data" variable
console.log("SERVER RESPONSE");
console.log(data);
}
});

JQuery $.ajax request returns me "Error 404" even if the resource exists

I'm developing an app with TideSDK and I need to send some data to a PHP script that will create a file to store it on the pc. I'm pretty new to AJAX and to send data I do:
var jsonString = JSON.stringify(GW2.items);
$.ajax({
url: "/assets/scripts/save.php",
type: "post",
dataType: "json",
data: { jsonString: jsonString }
}).done(function(data){
console.log(data);
});
Where GW2.items is a JSON object, "save.php" is my script and jsonString is the variable I want to send.
But, when I try to execute the program it returns me:
POST http://127.0.0.1:52432/assets/scripts/save.php 404 Not Found
And the answer is: Cannot POST /assets/scripts/save.php
This is the PHP script:
<?php
$jsonString = $_GET['jsonString'];
return {};
?>
I checked the path and it's correct so why it can't find my file?
Did you try your path with POST or just GET? It could be exist for GET requests (pasting the url on a browser) but probably not for POST or other HTTP verbs.
You can use REST clients like Postman to be sure, which is also a Chrome extension.

Send a request to a route in Symfony2 using Javascript (AJAX)

I have a working prototype Symfony2 RESTful webservice which I am still working on and I am trying to figure out how a client can send JSON or consume JSON data from the webservice. All I need is an example(s) on how to send a request or post data to it and I can figure out the rest. From my browser, if I visit http://localhost/app_dev.php/users.json, I get the correct result from my database as JSON, e.g.
[{"id":1,"username":"paulo","username_canonical":"paulo","email":"a#ymail.com","email_canonical":"a#ymail.com","enabled":true,"salt":"66r01","password":"UCxSG2v5uddROA0Tbs3pHp7AZ3VMV","last_login":"2013-12-03T13:55:15-0500","locked":false,"expired":false,"roles":[],"credentials_expired":false,"first_name":"Monique","last_name":"Apple"}, ... etc.
All other routes are working correctly and I can get the same result by using httpie or cURL. Now, the problem I am trying to solve is to get the same JSON data using AJAX (and mobile iOS, Android, etc later). Here is my attempt at using AJAX JS:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$.ajax({
dataType: "json",
type: "GET",
url: "http://192.168.1.40/symfony/web/app_dev.php/users.json",
success: function (responseText)
{
alert("Request was successful, data received: " + responseText);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
</script>
The AJAX alerts the following results which indicates an error:
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
What am I doing wrongly and how can I solve the problem. Kindly give an example.
This is a cross-domain request issue. You need to make the request to the same domain you are on. This is a browser-level security feature.
For example, you can only request URLs on http://192.168.1.40 if you are currently ON http://192.168.1.40. This means that a request from http://192.168.1.39 (for example) won't work

Get Ajax POST data on php via Javascript call

First I am conface that I am Newbie to php,
I am using jquery(knockout js) at client side & PHP at server side. my code.
Client side: I am using knockout js(Javascript). to call my PHP service.
My Code:
self.VMSaveEditUserMode = function () {
try {
var params = { "ClientData": [controllerVM_.ClientID(), controllerVM_.VMList[0].ClientName(), controllerVM_.VMList[0].ShortName(), controllerVM_.VMList[0].Address(), controllerVM_.VMList[0].CreatedBy(), controllerVM_.VMList[0].CityName(), controllerVM_.VMList[0].PostalCode(), controllerVM_.VMList[0].ContactEmail(), controllerVM_.VMList[0].ContactPhone(), controllerVM_.VMList[0].IsCorporate()] };
$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});
}
catch (error) {
alert("Catch:" + error);
}
}
Server Side My Code, I am using this PHP code to connect with DB.
PHP Code:
public function SaveClient($userToken)
{
$value = json_decode($Clientdata);
echo $value->ClientData[0];
}
*My Question *:
I am not clear on how to POST data in PHP ? I tried with $_POST[''] method as well as many more.
I am using eclipse as a php framework. so, not able to debug it when i post the data.Normally mode i am able to debug my code.but not from remotely.for that i made changes on php.ini file also.
How to get Response of Post Data on php code ?
How to debug via remote post ?
My Request sample:
suppose i use:
For, data: params, only at that time my request format is.
ClientData%5B%5D=4&ClientData%5B%5D=kamlesh&ClientData%5B%5D=KAM&ClientData%5B%5D=Junagadh&ClientData%5B%5D=me&ClientData%5B%5D=SANTA+ROSA&ClientData%5B%5D=76220&ClientData%5B%5D=kamlesh.vadiyatar%40gmail.com&ClientData%5B%5D=9998305904&ClientData%5B%5D=false
For, data: JSON.stringify(ko.toJS(params)),
{"ClientData":["4","kamlesh","KAM","Junagadh","me","SANTA ROSA","76220","kamlesh.vadiyatar#gmail.com","9998305904",false]}
If I understand correctly you need to create a PHP service which is able to receive REST-like requests from client.
In order to do thad you need to access raw POST data. In PHP its being done like this:
$ClientData = file_get_contents('php://input');
You can read more about php://input in the wrappers documentation.
Of course from the client's side the data need to be sent using the POST method and as raw data, i.e. as a string. You can obtain a string from object using JSON.stringify() which you already do.
If you pass an object, it will be converted to string internally by jQuery using query-string format. More on that in the jQuery documentation for $.ajax (the most importatnt options being data and processData).
Just pass the ajax data param as an object, don't convert it into JSON. Then in PHP use $_POST directly.
Use firebug or chrome dev tools to analyze the ajax request and see which data is sent
Use this simple jquery function to accomplish your task
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"tbl="+table,
dataType:"json", //if you want to get back response in json
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
in PHP use:
if(isset($_POST['ClientData'])){
$client_data = $_POST['ClientData']
}
now $client_data variable should contain the array.
For debugging purpose you can use php's built-in print_r() function. It's pretty handy.
here's is an example:
//make sure it's post request
if(isset($_POST)){
//now print the array nicely
echo "<pre>";
print_r($_POST);
echo "</pre>";
}

Categories

Resources