Using angular.js to send data to a php file - javascript

Right so I have a angular function that is sending data to a php file using the http method.The php code I want to process the data and echo it back onto the page to confirm that the php file has processed it. I'm currently getting undefined alerted back to me, surely I should be getting the vaule of email back to me?. Thanks all
I'm following this tutorial https://codeforgeek.com/2014/07/angular-post-request-php/
var request = $http({
method: "post",
url: "functions.php",
data: {
email: $scope.email,
pass: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
//.then occurs once post request has happened
//success callback
request.success(function (response) {
alert(response.data);
},
//error callback
function errorCallback(response) {
// $scope.message = "Sorry, something went wrong";
alert('error');
});
My php code...
//receive data from AJAX request and decode
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
#$email = $request->email;
#$pass = $request->pass;
echo $email; //this will go back under "data" of angular call.

From the documentation:
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
Your code should look like this:
request.then(
function( response ) {
var data = response.data;
console.log( data );
},
function( response ) {
alert('error');
}
);
Now, you need to encode the response from the server in a JSON format, so replace echo $email; with:
echo json_encode( array(
'email' => $email
) );
And you can access the email property from the angularjs $http.success promise callback function (it's the first function inside the then closure) by response.data.email

Related

if else statement in AJAX success

This is how i am trying to check json data. If the data inserts correctly i want the mentioned jquery in success code. But if it is not inserted then i want else code to run. But the if else conditions are not working properly.I am including php code and ajax code which i have tried. Am i doing it right?
AJAX
$( "#frm_add" ).on('submit',(function(e) {
e.preventDefault();
var img= new FormData(this);
datas = $("#frm_add").serializeArray();
$.each(datas,function(key,input){
img.append(input.name,input.value);
});
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
//data:new FormData(this),
data:img,
// data: {img:img,datas:datas}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) // A function to be called if request succeeds
{
if(data == true)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
});
}));
php
function insertCategories($params)
{
$fileName = $_FILES['cat_image']['name'];
$name = $params['cat_name'];
$type = $params['cat_type'];
$switch = $params['cat_switch'];
$chk=mysqli_query($this->conn,"select * from categories where cat_name='$name'");
if(mysqli_num_rows($chk)==0)
{
$sql = "INSERT INTO `categories` (cat_name,cat_image, cat_type, cat_switch) VALUES('$name','$fileName', '$type','$switch'); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert Categories data");
if ($result) {
if (file_exists("images/" . $_FILES["cat_image"]["name"])) {
echo $fileName . " <span id='invalid'><b>already exists.</b></span> ";
} else {
$sourcePath = $_FILES['cat_image']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "images/" .$fileName; // Target path where file is to be stored
move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
}
}
echo json_encode($result);
}
}
Add the error command in your ajax call to execute if the command fails or returns no data in general
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:img,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data), // A function to be called if request succeeds
{
if(data)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
error: function (data)
{
$("#namerr".html("<p id='error' style='color:red'>"+data+"</p>");
}
});
I think You have problem with response convention: Sometimes You call die() method (PHP: 12 line), sometimes You call json_endcode() (PHP: 25 line), sometimes echo with plain string.
In this type of actions You should:
Always output JSON from backend script. Mixing response types is really pain in the ass, it's hard to parse and test.
Use response object with uniform structure - that might help with building complex applications and easy to modify
Example pseudocode:
PHP
if($success) {
die(json_encode([
'error' => false,
'message' => 'Thank You',
'data' => $some_extra_data
]));
} else {
die(json_encode([
'error' => true,
'message' => 'Sorry',
'data' => $some_extra_data
]));
}
Then in ajax.success() method, its really easy to handle:
success: function (data) {
try {
var response = JSON.parse(data)
if(response.error == true) {
$('#nameerr').text(response.message)
} else {
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
} catch (err) {
alert('Sorry. Server response is malformed.')
}
}

Fetch api doesn't send POST data

I'm trying the Fetch API for the first time and I'm trying to POST a variable to a PHP script. I did this same this with jQuery.ajax() which did work.
var myRequest = new Request('invoeren.php', {method: 'POST', body: JSON.stringify({name: name})});
fetch(myRequest).then(function(response) {
console.log(response);
});
This returns to me Undefined index 'name'.
What am I doing wrong?
The working jQuery code:
$.ajax({
url: "invoeren.php",
method: "POST",
data: { name : name}
}).done(function( msg ) {
console.log(msg);
}).fail(function( jqXHR, textStatus ) {
alert( "Naam is niet ingevoerd door een probleem: " + jqXHR );
});
The PHP Script:
try {
$dbh = new PDO('mysql:host=localhost;dbname=ajaxoef', $user, $pass);
$stmt = $dbh->prepare('INSERT INTO names(name) VALUES (:name)');
$stmt->bindParam(':name', $name);
$name = json_decode($_POST['name']);
$stmt->execute();
echo "Naam is ingevoerd.";
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
The working jQuery code
data: { name : name}
… so when you used jQuery you send WWW URL Form Encoded data (the default jQuery encoding).
body: JSON.stringify({name: name})
… but when you switched to fetch, you also converting the object to JSON.
JSON is not WWW URL Form Encoded!
You, presumably, haven't rewritten the PHP to expect JSON, and are probably trying to read from $_POST (which is empty, because PHP doesn't support JSON encoded requests by default).
You can construct a FormData object which will be encoded in a way that PHP will parse by default.
var body = new FormData;
body.append("name", name);
//...
body: body

$http ajax AngularJS POST returns undefined index in PHP

I'm sending data to an API REST service via the ajax $http service of AngularJS but php always says that the index is undefined. I've checked a lot of posts on SO that ask for the same error and I tried everything that they say but I still get the same error.
How I'm using the $http service:
$http({
method: 'POST',
url: window.location.pathname+'/../../api/tasks/'+$id,
data: {
'title': $scope.allData.taskData[0].title,
'content': $scope.allData.taskData[0].content,
'usersInTask': $scope.allData.taskUsers
},
contentType: 'application/json',
dataType: 'json',
headers: {'Content-Type': 'application/json'}
})
.then(function success(response){
$scope.closeDialog();
}, function error(response){
console.log("Error:" +response.statusText);
});
How I try to get values in PHP:
$title = $_POST['title'];
$content = $_POST['content'];
$users = $_POST['users'];
In this case, for example, it always says that title is an undefined index of $_POST
To read data first you need to decode it in POST format.
$json_input = file_get_contents('php://input');
if ($json_input) {
$_REQUEST = json_decode($json_input, true);
}
Since you are posing data it application/json format you need to read it from raw POST data. Try this:
$postData = json_decode(file_get_contents("php://input"));
$title = $postData->title;
$content = $postData->content;

Angular Js $http.post method unable to access data in Zend Framework

This is my Angular js Function
$scope.submitform = function () {
$http.post('http://localhost:90/vendor/dashboard/accountinfosave/',
{'uname': 'vikrant', 'pswd': '111', 'email': 'bhallavikrantvir#gmail.com'}
).success(function(data) {
alert("success");
}).error(function(data) {
alert("error occured");
});
};
This is my Zend Framework Controller Function .
public function accountinfosaveAction(){
$data = $this->getRequest()->getPost();
print_r($data);// not working
print_r($_POST);// not working
}
The problem is I want to access the data(uname,pswd,email) I sent from Angular Js using $http.post function to zend framework .
If I use $.ajax function it works fine . But $http.post Does not work .
Please help me out.
you can use this to get post request
$postdata = file_get_contents("php://input");
First of all, check post url is correct or not using test echo in function or a contructor
Try like this way,
var request = $http({
method: "post",
url: "http://localhost:90/vendor/dashboard/accountinfosave/",
data: {
uname : 'vikrant',
pswd : '111',
email : 'bhallavikrantvir#gmail.com'
}
});
request.success(
function( data ) {
$scope.data = data;
alert('success');
}
);

AJAX GET JSON seems to returns nothing

I am creating an Android application using Intel XDK and for some reason It seems to work on the emulator but on the mobile it seems to fail. Below are the screenshots of what it looks like on the emulator and on the device.
Both are using the exact same code and are pointed to the correct database and server. Below is the code I'm using, the PHP and JavaScript code.
function getSessionData(callback) {
$.ajax({
url: 'http://sm.script47.net/api/v1/modules/sessionData/sessionData.php',
"type": "GET",
dataType: "json",
async: true,
success: function (data) {
callback(data);
},
error: function (xhr, textStatus, error) {
alert(xhr.statusText);
alert(textStatus);
alert(error);
},
});
}
Then in another file called home.js.
window.onload = function () {
getSessionData(function (data) {
window.token = data.token;
window.userID = data.userID;
window.username = data.username;
window.emailAddress = data.emailAddress;
alert(window.userID);
getElement("userDetails").innerHTML = "Hello <strong> " + window.username + "</strong>"
});
};
Then to get the session data I'm using the below on a PHP server hosted by namecheap (shared hosting).
<?php
session_start();
// I added the code below in the comment block to try and make it work.
/******************************************************/
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
/******************************************************/
$sessionData = array(
"token" => htmlspecialchars(trim($_SESSION['token'])),
"userID" => htmlspecialchars(trim($_SESSION['userID'])),
"username" => htmlspecialchars(trim($_SESSION['username'])),
"emailAddress" => htmlspecialchars(trim($_SESSION['emailAddress']))
);
echo json_encode($sessionData, JSON_PRETTY_PRINT);
I don't know why it won't work or what is causing it to not work which is why I'm not sure what the fix is. I've talked to the namecheap customer support and they said AJAX requests should work, and they do as I use them to login/register but getting the JSON session data on an actual mobile device doesn't seem to work. Also the success/error callback doesn't return anything either.

Categories