Invalid Response - JSON & Laravel 5. 6 - laravel

In my code below is a json response that i am trying to access its element. When i get the description from the response, i get an error. Below is the structure of the response
How do i get the description from the response ? I am only able to get success by $response->success
Response
{"description":["My Description Is Here"],"success":true}
When i validate the json, it is actually a valid json. What could i be doing wrong ?
Code
$response = {"description":["My Description Is Here"],"success":true}
if ($response->state == true) {
$message = $response->detail;
} else {
//do something here
}

You are trying to work with JSON in PHP. But at first you have to decode it into object:
$response = json_decode('{"description":["My Description Is Here"],"success":true}');

Related

Laravel url::assets return "\" after every part in url

I make an API that return url of some media and file
I returned the url like this
$file->url = URL::asset('storage/files/'.$request->course_segment_id.'/'.$file->id.'/'.$file->name);
the URl return like that in Postman
"url": " http:\/\/localhost:8000\/storage\/media\/2\/1\/03.png "
without much more information, it looks like the response is encoded in JSON.
If you are using Javascript in your front-end, you can parse the response and then access the data properly formatted.
let response='{"url": " http:\/\/localhost:8000\/storage\/media\/2\/1\/03.png "}';
let responseObject=JSON.parse(response);
// responseObject returns a-
// -javascript object: {url: " http://localhost:8000/storage/media/2/1/03.png "}
console.log(responseObject.url);
//> http://localhost:8000/storage/media/2/1/03.png

Grails Consuming JSON response.

I'm trying to create a restful service and I'm trying to consume my JSON response and convert it back to an Object.
Controller method
def mergeVendors(String region) {
def report = new VendorReport();
//do something with report
response.status = 201
response ([vendorReport: report]) as JSON
}
Test Method
void "Test Merge Vendors"() {
when:
controller.request.method = 'POST'
controller.request.json = '[{id:1, zip:"14224"}]'
controller.mergeVendors("Florida")
def response = controller.response
then:
response.zip == "14224"
}
The code above is what I'm trying to use and I get the following exception. How do I cast the response back to a VendorReport obj?
groovy.lang.MissingMethodException: No signature of method: org.healthresearch.VendorController.response() is applicable for argument types: (java.util.LinkedHashMap) values: [[vendorReport:org.vendor.VendorReport#1b0dbdf1]]
Possible solutions: respond(java.lang.Object), getResponse(), respond(java.lang.Object, java.util.Map), respond(java.util.Map, java.lang.Object), respondsTo(java.lang.String), respondsTo(java.lang.String, [Ljava.lang.Object;)
response ([vendorReport: report]) as JSON
change to
render ([vendorReport: report]) as JSON

Alamofire not recognizing POST method and also the parameters

I am using Alamofire in iOS 9 and am noticing that Alamofire is not sending the parameters to my PHP script in a POST method.
This is the PHP script:
if($_SERVER['REQUEST_METHOD'] != 'POST') {
echo '{"status": "error", "message" : "Only POST supported. You sent: '.$_SERVER['REQUEST_METHOD'].'"}';
return;
}
if (!isset($_POST['GENDER']) || !isset( $_POST['CHAR_COUNT_LOWER'] ) || !isset( $_POST['CHAR_COUNT_UPPER'] )) {
echo '{"status": "error", "message" : "Minimum parameters not set."}';
return;
}
Then, when firing my Alamofire POST request, I get the message:
swift:55 fetchData(_:completionHandler:): Only
POST supported. You sent: GET
And, finally, this is my Alamofire request:
Alamofire.request(.POST, url, parameters: ["CHAR_COUNT_LOWER":String(lowerValue), "CHAR_COUNT_UPPER":String(upperValue), "GENDER": String(gender!)] )
.validate()
.responseJSON { response in
QL1(response.description)
switch response.result {
case .Success:
var result = [BabyNames]()
let json = JSON(data: response.data!)
if json["status"] == "error" {
QL4(json["message"])
completionHandler(babyNames: [], error: StoreError.CannotFetch("Could not retrieve baby names"))
return
}
.......
I also tried changing the encoding to everything else but JSON, as my service does not take JSON as input.
It's a simple service that reads $_POST["param"]
Anything I am doing wrong?
Thanks.
EDIT:
Still going crazy about it. Installed Charles to check what was the request coming out of my PC and here it goes:
EDIT 2:
Change the Alamofire request encoding to JSON:
Alamofire.request(.POST, url, parameters: parameters!, encoding: ParameterEncoding.JSON )
Now I can see a GET and a POST request. The Post request:
URL http://example.com/backend/names/query_names.php
Status Complete Response Code 301 Moved Permanently
Finally found what the problem was.
My request URL was set to http://server.com/api
When I changed it to http://www.server.com/api
That got it working. I don't know honestly why that would happen and if that's something to do with the .httpaccess but that's it.

Codeception Laravel sendAjaxGetRequest return empty string

Do you know why this return an empty string
public function tryToTest3(AcceptanceTester $I)
{
$I->wantTo('To see a 200 status code and a json response');
$I->haveHttpHeader('Content-Type', 'application/json');
$I->sendAjaxGetRequest('/users',array());
$I->seeResponseCodeIs('200');
$I->seeResponseIsJson();// until here green bar
dd($I->grabResponse()); // empty string
}
Acceptance Tests (5) ----------------------------------------------------------------------------------------------------------------------------
Modules: PhpBrowser, AcceptanceHelper, Db, REST
-------------------------------------------------------------------------------------------------------------------------------------------------
Trying to try to test (LoginCest::tryToTest)
Scenario:
PASSED
Trying to try to test2 (LoginCest::tryToTest2)
Scenario:
PASSED
Trying to To see a 200 status code and a json response (LoginCest::tryToTest3)
Scenario:
* I have http header "Content-Type","application/json"
* I send ajax get request "/users",
[Response] 200
[Page] http://localhost/laravel/phpunit/public/users
[Cookies] []
[Headers] {"Date":["Thu, 31 Jul 2014 08:49:58 GMT"],"Server":["Apache/2.2.22 (Ubuntu)"],"X-Powered-By":["PHP/5.4.6-1ubuntu1.4"],"Vary":["Accept-Encoding"],"Content-Length":["120"],"Content-Type":["text/html"]}
* I see response code is "200"
* I see response is json
* I grab response
string(0) ""
NB
in my app/bootstrap/start.php I've got
if ((gethostname() === 'homestead') && (isset($_SERVER['REMOTE_ADDR'])) && ($_SERVER['REMOTE_ADDR'] === '127.0.0.1'))
{
dd('homestead');
$env = $app->detectEnvironment(['codeception' => ['homestead']]);
}
else
{
$env = $app->detectEnvironment(['local' => ['homestead']]);
}
homestead is never printed
while this print the actual response and print homestead
public function tryToTest3(AcceptanceTester $I)
{
$I->wantTo('To see a 200 status code and a json response');
$I->haveHttpHeader('Content-Type', 'application/json');
$I->sendGET('/users',array());
$I->seeResponseCodeIs('200');
$I->seeResponseIsJson();
dd($I->grabResponse()); // the good response
}
Scenario:
PASSED
Trying to To see a 200 status code and a json response (LoginCest::tryToTest3)
Scenario:
* I have http header "Content-Type","application/json"
* I send get "/users",
[Request] GET http://localhost/laravel/phpunit/public//users
[Response] [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
[Headers] {"Date":["Thu, 31 Jul 2014 09:12:43 GMT"],"Server":["Apache/2.2.22 (Ubuntu)"],"X-Powered-By":["PHP/5.4.6-1ubuntu1.4"],"Cache-Control":["no-cache"],"Set-Cookie":["laravel_session=eyJpdiI6IjdxSVE3RzFEYUw4Q0VmbWNWTzlVVkE9PSIsInZhbHVlIjoiSXY5c2xZbVlmdTdSU1hjNTJuVU1cLzlkZXRwQmRGOEc2R3dscTBtY3JHRVwvR3V5TWM2K1BkVkpmdERDY3h0NkloU09CaUFNN0cwSk56TDBZbmhIOVVLZz09IiwibWFjIjoiNzE2YTlhZGEyMTIyZTdlODQ0ZjA0ZGEzZjE5NDg0MTBlMWNkY2IzMzRkN2NhNjEzOTg5ZTQ5NmRkNDU2OTE4MyJ9; expires=Thu, 31-Jul-2014 11:12:43 GMT; path=/; httponly"],"Transfer-Encoding":["chunked"],"Content-Type":["application/json"]}
[Status] 200
* I see response code is "200"
* I see response is json
* I grab response
string(52) "[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]"
try this instead of $I->grabResponse()
$response = $I->grabDataFromJsonResponse();
I have the same problem, but i think that in my case i have mistunderstood the testing tools.
In my case i was trying to test a JSON response provided by a controller that accepted AJAX POST requests.
I was trying to test that a successfull-style flash message is displayed to the user in a div, but as i wasn't able to test Javascript, i was looking for the JSON in the response. And then i reached your case when null is given as a JSON.
I tried with all the possible headers and combinations and then i reached this response in PHPtest.club and i think that it maybe can help you as it helped me.
It's about the difference between sendPOST and sendAjaxPostRequest, and then i realised that i was using in a wrong way the sendAjaxPostRequest.
http://phptest.club/t/what-is-the-difference-between-sendpost-and-sendajaxpostrequest/212
Basically:
sendAjaxXRequest is used to test an HTML response, so you should use, see, seeElement and those methods.
sendX is designed to work with JSON response and not with HTML, so you should use seeResponeIsJSON or all the other methods.
I hope to be helpful to you or someone else.
Greetings!
I'd like to say thanks to davert for such a meaningful response.

WebWorks AJAX Cross domain request

I'm working on a playbook app with webworks sdk.
I'm trying to make an http request (method: post) by sending AND recieving data.
I can get the response from server, but the server can't get the $POST data, when I try to display $_POST['apiKey'], nothing apears, I checked my code 100 times, checked my config.xml for uri, can't find the error.
TL;DR: can't send but can receive data.
My PHP Server code:
echo "passed key is: ".$_POST["apiKey"]; // Nothing apears
echo "<br>";
if(md5($_SESSION['private_key'])===$_POST["apiKey"]){
}
else{
echo "Invalid API Key"; // Always getting this response on client app
exit();
}
?>
My JS Client code:
function httpRequest(){
var key="a984a4474cff54d8468a296edf3af65b";
document.getElementById("status").innerHTML="Reaching server...";
//////////////////////////////////////
var xdr = getXDomainRequest();
xdr.onload = function() {
document.getElementById("status").innerHTML=xdr.responseText;
}
xdr.open("POST", "http://mydomain/index.php");
xdr.send("apiKey="+key);
}
Solved:
When using POST method you should define the request header:
xdr.open("POST", "http://mydomain.com/index.php");
xdr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); // with this line
xdr.send("apiKey="+key);
Solved: When using POST method you should define the request header:
xdr.open("POST", "http://mydomain.com/index.php");
xdr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); // with this line
xdr.send("apiKey="+key);

Resources