$http angularjs php response - php

Quite new to angularjs, but already done some research.
I'm making the following $http post request:
$scope.onClick2 = function () {
var myRequest = {};
myRequest = {};
myRequest.ServiceType = "SearchExams";
myRequest.SessionId = 'SessionlessRequest';
myRequest.Compression = 'no';
myRequest.Parameters = {};
myRequest.Parameters.Status = ['30', '40'];
myRequest = JSON.stringify(myRequest);
var request = $http({
method: 'POST',
url: 'http://localhost/request.php',
data: 'data=' + myRequest,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
};
My request.php handles the request and sends back an json response.
Howerver I see in the response tab of chrome and in fiddler that the original request is also in the response. See below:
Array
(
[data] => {"ServiceType":"SearchExams","SessionId":"SessionlessRequest","Compression":"no","Parameters":{"Status":["30","40"]}}
)
{"Error":false,"ErrorMessage":null,"Data":[{"ExamID":1,"A.......
I would expect only the last line ({"Error":false,"ErrorMessage":null,"Data":[{"ExamID":1,"A...... to be returned....looking at what my request.php send back it should.
Am I missing something?
Thanks,

Sorry for waisting anybodies time on this.
There was an error in my php code indeed.

Related

axios/ fetch failed but postman work with php api

I got stuck when calling php api with form-data type in my React app. When I test with Postman, it works correctly but failed in react.
Please let me know if I'm doing wrong here.
In Postman, call api like this:
URl_API: xxxx/yyyy.php.
Config in Body tab in key/value: form-data
k: "some string"
id: "some string"
With axios, I had an error:
My code:
const formData = new FormData()
formData.append('k', 'some string')
formData.append('id', 'some string')
const response = await axios.post('xxxx/yyyy.php', formData, {
headers: {
'Access-Control-Allow-Origin': '*',
},
})
xxxx/yyyy.php net::ERR_HTTP2_PROTOCOL_ERROR
I had already tried with fetch but no luck - call api success with status 200 but the response.text() is empty.
With fetch api:
const result = await fetch('xxxx/yyyy.php', {
method: 'POST',
mode: 'no-cors',
body: formData,
cache: 'no-cache',
})
.then(async (res) => {
return res.text()
})
.then((text) => console.log('It is empty here', text))
It look like a CORS also, but you will be able to sort it out
a simple solution in development is to use a local api server, and finally when the app is deployed to the server which is on the same domain as the api, you should get the response, as demonstrated below by making the calls using dev tools.
in short: if a api calls work with postman but not through the browser, its mostly due to cors restrictions, then it could be the response type
Verifying cors issue by making calls throught dev tools
let onSubmit = async () => {
try {
const url = "https://www.your-domain***.com/getUrlApp.php";
const formData = new FormData();
formData.append("k", "kk");
formData.append("id", "dd");
const data = new URLSearchParams(formData);
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "no-cors", // no-cors, *cors, same-origin
body: data // body data type must match "Content-Type" header
});
//const res = response.json();
const buffer = await response.arrayBuffer();
const decoder = new TextDecoder("iso-8859-1");
const text = decoder.decode(buffer);
console.log("text", text);
return response;
} catch (error) {
console.log("error", error);
}
};
To verify the response
go https://www.your-domain***.com
open dev tools => console
past the function above and run it by typing onSubmit() in the console
you will see the response
Hope it helps you in some way

Update view angular array push

I am trying to handle the push update in Angular in the view but it has been impossible for me. I know the following:
I have an array, this array is called marca1 and it receives all the objects that the get request that I make to the server and it shows in the view with ng-repeat.
When I send the post request to save a new data, it gets a response from the server that I save it in an object called pepa.
I use the push function for my fix to refresh the view, but that does not work.
Why can it be failing? How can I fix it?
This is my code:
miAppAngular.controller('marca',function($scope,$http,$location,$routeParams,configuracionGlobal){
$scope.config = configuracionGlobal;
$scope.marca1=[];
$http.get( configuracionGlobal.api_url + "/marca/listaMarca.php")
.then( function(respuesta){
$scope.marca1=respuesta.data;
});
$scope.nuevaMarca = function ( ){
$scope.newMarca={
'nombre':$scope.nombreMarca
}
$scope.pepa={};
//
$http({
url: configuracionGlobal.api_url + "/marca/nuevaMarca.php",
method: "POST",
data: $scope.newMarca,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(
function(respuesta){
$scope.pepa= respuesta;
$scope.marca1.push($scope.pepa);
$('#modalMarca').modal('hide');
}
)
}
Try to run getMarca after posting:
$scope.getMarca = function() {
$http.get( configuracionGlobal.api_url + "/marca/listaMarca.php")
.then(function(respuesta)
{
$scope.marca1=respuesta.data;
});
}
In your .then() of your post, at the end call: $scope.getMarca()
This shall update the array $scope.marca1.
The response returned after a POST is usually used for checking; whether it was a success or failure (or to return custom values from backend).

PHP cURL request body is undefined in node.js

I've tried all the examples on these SO posts:
How do I send a POST request with PHP?
PHP cURL Post request not working
Always my request.body is undefined yet in the request itself I see "_hasBody":true
The current code for my php post file:
function httpPost($url,$data){
$curl = curl_init($url);
curl_setopt($curl,CURLOPT_POST,true);
curl_setopt($curl,CURLOPT_POSTFIELDS,http_build_query($data));
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
$response=curl_exec($curl);
curl_close($curl);
return $response;
}
$fields = array(
'name' => 'ben'
, 'foo' => 'bar'
);
echo httpPost("http://localhost:8002", $fields);
Then my node.js listening server code is:
var test=require('http').createServer(function(q,a){//question,answer
console.log(q.body);
console.log(JSON.stringify(q).indexOf('ben'));
a.end(JSON.stringify(q));
});
test.listen(8002,function(e,r){console.log("listening");});
As you can see, in the node.js server I search the request for my name but the console says
undefined//no body
-1//could not find your name in the request
then I hand over the request back to the response and print it to the page so I can see the whole data.
logically it would seem that I am doing the cURL part right as its copied code, so I would say I might be doing something wrong to access the vars
My question is how do I see the request body or where the vars?
To handle a POST request, you have to do the following:
var qs = require('querystring');
var http = require('http');
var test = http.createServer(function(req, res) {
//Handle POST Request
if (req.method == 'POST') {
var body = '';
req.on('data', function(data) {
body += data;
});
req.on('end', function() {
var POST = qs.parse(body);
console.log(body); // 'name=ben&foo=bar'
console.log(POST); // { name: 'ben', foo: 'bar' }
if(POST.name == 'ben')
console.log("I'm ben"); //Do whatever you want.
res.setHeader("Content-Type", "application/json;charset=utf-8");
res.statusCode = 200;
res.end(JSON.stringify(POST)); //your response
});
}
});
test.listen(8002, function(e, r) {
console.log("listening");
});
cURL response:
{"name":"ben","foo":"bar"}

Ajax call failing; xhr.responseXML is undefined

I'm trying to make a simple ajax call:
When the user selects and option, some info about that option will be
echoed into a div (this is dynamic)
Here's my code for the ajax call
ajax.js
$(document).ready(function()
{
//Add Event
//Currently Broadcasting #Zone
$('#beacon0').on('change', function ()
{
var Selected = $(this).find("option:selected");
var SelectedText = Selected.text();
var SelectedEncoded = encodeURIComponent(SelectedText);
$.ajax
({
url: 'ajax-addevent.php',
data: 'n_beacon='+ SelectedEncoded,
dataType: 'JSON',
success: function(returnClass)
{
var resultajax = jQuery.parseJSON(returnClass)
console.log(resultajax);
},
error: function(xhr, status, error)
{
var errors = JSON.parse(xhr.responseText);
console.log("failed");
console.log (errors);
}
});
});
});
SO the ajax call should give the name of the zone in the URL, so I can $_GET the parameter in my php script. This is the php I run just to test the ajax call.
ajax-addevent.php
<?php
include("classes/event.class.php");
$event = new Event();
$GetZoneName = $_GET['n_beacon'];
$ZoneName = urldecode($GetZoneName);
$arrayDetails = $event->getBeaconEvent($ZoneName);
while($row = mysqli_fetch_array($arrayDetails))
{
$EventTitle = $row["n_title"];
$EventLink = $row["n_link"];
$EventDate = $row["n_date"];
}
$arr = array( "EventTitle" => $EventTitle,
"EventLink" => $EventLink,
"EventDate" => $EventDate );
header("content-type:application/json");
$json_arr = json_encode($arr);
return $json_arr;
?>
My problem is that the ajax call fails and gives me this as result:
What's wrong why my ajax call? Can you help?
EDIT Update Code:
You're trying to get an XML response when the returned datatype is JSON - xhr.responseXML will always be undefined unless the response is valid XML.
Try using xhr.responseText instead. You can use JSON.parse(xhr.responseText) to get a javascript object out of it.
Another good technique is to use the dev tools of your current browser to inspect the network response directly (F12 in Firefox or Chrome, then open the Network tab).

How do I evaluate this specific JSON with Prototype(JS)?

Data from a Server became a JSON array as responseText an ajax request :
Price : [{"id":"1","max_price":"100000"},{"id":"2","max_price":"150000"},{"id":"3","max_price":"200000.55"}]
Name : [{"id":"1","name":"P1"},{"id":"2","name":"P2"},{"id":"3","name":"P3"}]
I see into Prototype this method : var json = transport.responseText.evalJSON(true);
How can I just get the Price array, so JSON equals:
[{"id":"1","max_price":"100000"},{"id":"2","max_price":"150000"},{"id":"3","max_price":"200000.55"}]`
The php needs to include the json header:
header('Content-type: application/json');
The ajax request needs to include evalScripts (make sure you trust the source):
new Ajax.Request("json.php",
{ method: 'get',
parameters: {'xyz': 'json', 'var2': 'some_val'},
evalScripts: true,
onSuccess: function(response){your_function(response);}});
Then your function can get the json like the following:
your_function = function (response) {
var result = response.responseJSON;
...
}
Edit: There's also these instructions directly from the source:
http://www.prototypejs.org/learn/json
Edit2: Here's how to update the server:
$return_data = array();
$return_data['price'] = getPrice($db);
$return_data['name'] = getName($db);
echo json_encode($return_data)."\n";
after you do this, in js you can do something like the following (from the above your_function example):
alert ("first id is: " + result['price'][0]['id']);

Categories