I am trying to send some data from my AngularJS Project to a PHP Server where I am using PHP Slim but I have tried everything I know and nothing seems to work.
SERVER PHP SLIM
$app->get('/create',function() use ($app) {
$data = $app->request()->params();
response_json(200,"DB: User Created",$data);
});
It works if I type directly from the browser
http://localhost:8888/core/users/create?login=test&password=123&name=Test&email=test#test.com&phone=12313
But if I try to send from the app using $http or $resource
var obj = { name:"Hello",email:"hello#email.com"};
$http.get('/core/users/create?',obj).success(function(data){console.log(data); });
I get an empty Array[0].
And if I try to use $resource I got an obj but not how I expected.
.factory('qServer',function($resource){
return $resource('/core/users/create?:data',{data: '#data'});
});
var obj = { name:"Hello",email:"hello#email.com"};
var send = JSON.stringify(obj);
//console.log(lol);
qServer.get({data:send},function(data) { console.log(data) });
With this code I get an Object like that:
data: Object
{"name":"Hello","email":"hello#email_com"}: ""
Anyone could tell me what I am doing wrong?
The second argument of $http.get method is not GET params but a request config.
You want to use something like this (notice the params key in config argument and lack of ? at the end of URL):
var obj = { name:"Hello",email:"hello#email.com"};
$http.get('/core/users/create', {params: obj})
.success(function(data){console.log(data); });
See also: Q: $http get parameters does not work and config argument docs.
Related
I have the following in a js script:
let skippers = {};
for(let i = 0; i < skipperIds.length;i++){
skippers[skipperIds[i].value] = skipperIds[i].checked;
}
regData.skippers = skippers;
responseData = sendData2('https://sailwbob.com/lagin/public/register.php',regData);
where sendData2 is an async call using axios. skippers looks like
{1:true,20:false}
In my php file I have:
$skippers = ($_POST['skippers']);
$skipperIds = array_keys($skippers);
$skipperValues = array_values($skippers);
but this is not working. I think php converts an array in $_POST to a string but I'm not sure.
two qustions:
how do I convert $skippers back to an array?
I've been trying to use print_r to see the data on the server but as this is an async call it's not working as the print_r results are being sent back to the js script and not printing out on the screen. Is there a way to see the results of print_r?
Update:
I tried $x=json_decode($_POST); but got an error saying it was expecting a string.
here's the call to axios:
function sendData2(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
//console.log(key,value)
bodyFormData.append(key,value)
}
return axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function(response){
return response.data
})
.catch(function(response){
return response
})
}
update2:
$skippers shows $skippers = [object Object]. Is there a way to send this to the server correctly?
As discussed in this article, axios serializes Javascript objects to JSON and becase PHP doesn't support JSON as a data format for populating $_POST, you can retrieve them in PHP like this:
$_POST = json_decode(file_get_contents("php://input"),true);
$skippers = $_POST['skippers'];
While axios does automatically stringify data it apparently doesn't do that for nested arrays. I needed to add:
regData.skippers = JSON.stringify(skippers); in my js
and then in the php file
$skippers = get_object_vars(json_decode($_POST['skippers']));
Am passing data to yii2 using ajax request but i keep on getting a 500 error
This is the ajax request code:
<?php
$script = <<< JS
$('form#forward_pr').on('beforeSubmit', function(e){
var keys = $('#grid').yiiGridView('getSelectedRows');
$.post({
url: "forwardpr", // your controller action
dataType: 'json',
data: {keylist: keys},
success: function(data) {
alert('I did it! Processed checked rows.')
},
error: function(err){
console.log("server error");
}
});
return false;
} ) ;
JS;
$this->registerJS($script);
?>
When i do console.log(keys) this returns
[0, 1]
This is my controller code:
if (Yii::$app->request->post()) {
echo $post = json_encode($_POST['keys']);
if (isset($_POST['keylist'])) {
$keys = \yii\helpers\Json::decode($_POST['keylist']);
print_r($keys);
}else{
echo "1";
}
The above always executes the error part of post request, What could be wrong;
You are sending your JSON as encoded (post) data body, not key value pairs. So your approach is not working this way.
There are two options to fix this:
refactor your controller into a RESTful service
in your controller use the JSON body rather than POST parameters
While the first option is preferred in the long run, the second option is pretty simple as a quick fix.
First, make sure you configure your app to parse JSON body conten.
IN config.php add this to the components array:
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
]
Then in your controller use this to get the JSON parameters:
$model->load(Yii::$app->getRequest()->getBodyParams());
I'm a newbie.. But I also want use checkboxcoloumns in gridview (Kartik version).
1st thing.
Instead of writing
var keys = $('#grid').yiiGridView('getSelectedRows');
I have to write
var keys = $('#w4').yiiGridView('getSelectedRows');
2nd thing.
In the controller you can process the keylist, but don't try to decode it, simple use it int this way:
$keys = $_POST['keylist'];
and it seems it works for me!
Sorry for my english..
Im working on some AJAX login function, making a request via PHP.
I am wondering how do I return data via the PHP so that I can handle it like the code mentioned below. I only worked on the javascript side and not the PHP server side so I am confused now.
I want to get a value/values stored in the response like data.name , data.sessionID , data.listOfnames
Is the data a JSON Object by itself?
Thanks!
The code below was used before and has been verified to work.
function retrieveVersion(){
var URL = RSlink + "/updates";
$.ajax({
headers : {
"Content-Type" : "application/json; charset=UTF-8",
"sessionid" : result
},
type : "GET",
url : vURL,
statusCode : {
0 : function() {
hideLoadingMsg();
showError(networkError, false);
},
200 : function(data) {
currentVersion = String(data.version);
updatesArray=data.updates;
});
}
}
});
Suppose you have a php file for handling ajax calls. It should be available by this url - vURL.
In this file you need to create an array.
Something like this:
$data = array('data' => array('version' => yourversion, 'updates' => yourupdates));
Then you need to convert this object into json string. You can do this using json_encode() function
echo json_encode($data);
One thing to keep in mind: You need to echo your data and only. If somewhere in your file you will have some other echo-es, the result string returning to your ajax-funtion might be broken.
I´m trying to pass object with two keys/values and I want to read it on the other side when I make Apache connect to it.
My nodejs server looks like so:
var sWeather = {"url1": "something", "url2": "another"};
var oWeather = JSON.stringify(sWeather);
console.log(sWeather);
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(sWeather+'\n');
}).listen(1340, '#');
console.log('Server running at http://###/');
Now I´m really new to nodejs and I have tried alot of thing so I´m not sure if I need to stringify the sWeather before I send it away.
My PHP file is like so:
<?php
$responseFromNode = file_get_contents("IP address");
var_dump($responseFromRuby);
For now I get string '[object Object] on my webpage because of var_dump.
I've tried doing something like
$url1 = $responseFromNode->url1
or
$url1 = $responseFromNode['url1']
I would just like to access both of the urls as a string so I can store it.
Any tips would be highly appreciated.
oWeather is the JSON string. Change
res.end(sWeather+'\n');
To
res.end(oWeather+'\n');
Then the PHP side has to decode the JSON
$responseFromNode = json_decode( file_get_contents("IP address") );
Notes:
You should also change your content type: res.writeHead(200, {'Content-Type': 'application/json'});, as mentioned by Brian Glaz
Your variable names are inverted:
oWeather should be the object
sWeather should be the JSON string
I'm trying to use an api and I'm just learning how to actually implement an api using php, hopefully I'll learn to incorporate jquery. I know how to create a simple search feature through mysql and its data with php, but is there a way to create search within the api? with API, there's json/xml responses, and they're all strings, so I was wondering if the user was able to search those strings?
Thanks
First you have to send the json data to php via AJAX. Something like this:
var request;
function runAjax(JSONstring)
{
// function returns "AJAX" object, depending on web browser
// this is not native JS function!
request = getHTTPObject();
request.onreadystatechange = sendData;
request.open("GET", "parser.php?json="+JSONstring, true);
request.send(null);
}
// function is executed when var request state changes
function sendData()
{
// if request object received response
if(request.readyState == 4)
{
// parser.php response
var JSONtext = request.responseText;
// convert received string to JavaScript object
var JSONobject = JSON.parse(JSONtext);
// notice how variables are used
var msg = "Number of errors: "+JSONobject.errorsNum+
"\n- "+JSONobject.error[0]+
"\n- "+JSONobject.error[1];
alert(msg);
}
}
You then can call the variable that javascript creates by calling the $_GET['json'] variable.
strstr($_GET['json'] , $whatEverYourSearchingFor);