Hello I have this angularjs http.post() request to slim php framework.
'use strict';
soup.factory('loginService',function($http){
return {
login:function(user){
console.log(user);
var $promise = $http.post('api/vendor/slim/slim',user );
return $promise;
};
});
when I debug the $_POST it always return an empty array,
but when I use use json_decode(file_get_contents('php://input')), slim php will return an error.
this is php function that handle the request.
function login(){
$sql = "SELECT * FROM users ORDER by id";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
//print_r($users);
$users = json_encode($users);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
var_dump($_POST);
$test = json_decode(file_get_contents('php://input'));
//do something with the post data
}
how can I solve this?
$http api say:
params – {Object.} – Map of strings or objects which
will be turned to ?key1=value1&key2=value2 after the url.
If the value is not a string, it will be JSONified.
Try sending data as a string, something like this:
var $promise = $http({
url: 'api/vendor/slim/slim', method: 'POST',
data: 'user=' + usr + '&password=' + pwd,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});
Don't forget to include the Content-Type header.
Related
This is my php codes to received and insert the data into the online database. I am very sure i these fabricated codes will not work but with you education and help i will get. thank you. insertdata.php
<?php
include 'connect.php';
include 'function.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["usersJSON"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storedata($data[$i]->callid,$data[$i]->pid,$data[$i]->pname,$data[$i]->medstay_amt,$data[$i]->med_amt,$data[$i]->imv_amt,$data[$i]->othermc_amt,$data[$i]->emtrans_amt,$data[$i]->outpden_am,$data[$i]->otherps_amt,$data[$i]->herb_amt,$data[$i]->medban_amt,$data[$i]->othermp_amt,$data[$i]->assist_amt,$data[$i]->code,$data[$i]->date);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->pid;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->pid;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>
You can do something like this:
$(document).on("click", ".BTN_Submit_Task", function () {
var AllTasks = ls.GetAllArr(LocalstorageName);
var id = $(this).attr("rec_id");
var result = $.grep(AllTasks, function(e){ return e.rec_id === id; });
$.ajax({
url: "url/of/php/file.php",
type: 'post',
dataType: 'json',
data: {usersJSON: [result]},
done: function(response) {
console.log(response);
}
});
});
And BTW you probably want to make AllTasks variable global and assign it once, then you can call it from both functions.
This question already has answers here:
How to pass parameters in $ajax POST?
(12 answers)
Closed 6 years ago.
im using ajax and php on my android app to query my database.
i am able to retrive all the results but dont know how to send a variable to my php so that i can use it as a custom query and retrive the results... something like this :
$id = $_POST['id'];
$sql = "SELECT * FROM mobile_app WHERE nome LIKE '{%id%}'";
but cant make my ajax post the variable and retrive the result...
this is my code :
my mobile app:
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON", // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.setItem('myData', JSON.stringify(data));
}
});
my php:
$sql = "SELECT * FROM mobile_app";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$output[] = array (
"nome" => $row['nome'],
"status" => $row['status'],
"hentrada" => $row['hentrada'],
"evento" => $row['evento']
);
}
} else {
echo "0 results";
}
$conn->close();
echo json_encode($output);
ajax() have a parameter
data:
by using this you can send as many param you want lik:
data:{
param1 : value1,
param2 : value2,
// and so on
}
In your case it is like:
data:{
id : value
}
and you can get this param in your php code like:
$id = $_POST['id'];
You need to add the following additional options to your $.ajax object:
type: 'post'
and
data: {
id: whateverVariableHasID
}
When I run the following javascript/php, I keep getting "undefined" when alerting the 'userid' property of the json object. However, if I stringify the json object, it returns "[{'userid':'1'}] which is the correct value.
Why am I getting undefined if I am trying to access the correct name of the json object?
Here is the ajax I am using to access the object:
$.ajax({
type: 'POST',
url: 'WebPHP/check_login.php',
contentType: "application/json; charset=utf-8",
data: finalObject,
async: false,
dataType: 'json',
success: function(data) {
if (data["result"] === false) {
alert("Invalid Email or Password");
} else {
var userID = data["result"];
alert(userID["userid"]);
var url = "AMessage.html";
alert(JSON.stringify(data["result"]));
}
}
});
And the php that connects to the db:
$json = file_get_contents('php://input');
$jsondata = json_decode($json);
$email = $jsondata - > email;
$password = $jsondata - > password;
$sql1 = " SELECT user_id as userid
FROM users
WHERE email = '$email'
AND password = '$password';
";
$result = mysqli_query($Thesisdb, $sql1) or die(mysqli_error($Thesisdb));
$rows = $result - > num_rows;
while ($row = $result - > fetch_assoc()) {
$response[] = $row;
}
$post_data = array();
if ($rows == 1) {
$post_data = array('result' => $response);
} else {
$post_data = array('result' => false);
}
echo json_encode($post_data);
mysqli_close($Thesisdb);
You can't access the userid property because your userID variable contains an array - that's what the [] brackets mean in the json response: [{'userid':'1'}]. Try accessing it this way: alert(userID[0]["userid"]);.
Better yet, don't return an array, since you're checkng that $rows == 1 anyway.
Yes, as said by #Jack you can not access userid property, your json response:[{'userid':'1'}] is in array form, so you need to go for the syntax: alert(userId[0].userid)
Hey helpful people I have an array in javascript and would like to send it to a php file currently the array is empty but could throw anything in it i suppose
here is the javascript
$scope.save = function(){
var savedArray = [];
var request = $http({
method: "post",
url:"test.php",
data: {
array: savedArray
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
request.success(function(data){
$scope.message = "FROM PHP FILE "+data;
});
}
the php code is
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
#$array = $request->array;
echo $array;
?>
now the problem is that no matter what data is returning all the html without it ever going to the php page i have tried commenting out echo $array and print_r on all the variables but nothing is returning anything
any suggestions on what to do next?
I am passing through The continent to the PHP file from a js file. Basically I need to insert the data to the database (put the continent in) and get the ID of it, but no matter what I do, it returns either an empty string or a 500 Internal Service Error.
Here is the PHP Code:
$continent = $_POST['continent'];
$sql = "INSERT INTO location_continent (`name`) VALUES ('". $continent ."')";
if(!$result = mysqli_query($con, $sql)){
die('There was an error running the query [' . $db->error . ']');
}
$sql = "SELECT id FROM location_continent WHERE `name` = '". $continent ."'";
$result2 = $con->query($sql);
if(!$result2){
die('There was an error running the query [' . $con->error . ']');
}
return $result2->num_rows;
Here is the JS Code:
$.ajax({
url: 'process.php?section=continent',
type: 'POST',
data: 'continent='+key,
success: function(res) {
continentid = res;
console.log(res);
},
error: function(res) {
console.log(res);
}
});
The Key that is passed through would be something like Africa.
I have tried the following in the php file:
return mysqli_insert_id($conn);
return $result;
$result = mysqli_query($con, $sql);
I have struggled for around 2 hours now. I cannot seem to find the error.
Note
Please note that the information is being inserted to the database just fine, just that I cannot get the ID.
In ajax you need to print/echo output for return data rather return statement so try to replace
return $result2->num_rows;
to
echo $result2->num_rows;
also you can send your query string like:-
$.ajax({
url: 'process.php',
type: 'POST',
data: {'section':'continent','continent':key},
success: function(res) {
continentid = res;
console.log(res);
},
error: function(res) {
console.log(res);
}
});
Then check your post data by echo if correct something wrong with query executing can't find $con and $db defined on posted code
You are returning but you are not in a function, so try echoing instead (echo mysqli_insert_id($conn);)