Ajax call using angular js - php

I am a new Angularjs user.I am facing a problem,when i submit a signup form,I have applied validation using AngularJs. At the same time if all the input fields are valid then i have send an $http Ajax call to check the email address,already exist or not.The issue is my php file did not receive email data.
$http({
method : 'POST',
async: false,
url: 'http://localhost/angular/signup/emailcheck.php',
data: { email: $scope.user.email }, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data)
{
$scope.info = data;
if($scope.userForm.$valid && $scope.info === '0') {
alert('our form is amazing' + $scope.info);
}
else{
alert('Already exist');
}
}).error(function(response,status)
{
console.log('ERROR HERE'+ status);
});
My Php file code:
$email = $_POST['email'];
$sql = "SELECT * FROM user where username = '".$email."'";
$result = mysql_query($sql);
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
....
....
....
....
....
}
I have checked and found that php file did not receive email value at all.

$http({
method : 'POST',
async: false,
url: 'http://localhost/angular/signup/emailcheck.php',
data : $.param($scope.user), // this will definitely wor
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data)
{
$scope.info = data;
if($scope.userForm.$valid && $scope.info === '0') {
alert('our form is amazing' + $scope.info);
}
else{
alert('Already exist');
}
}).error(function(response,status)
{
console.log('ERROR HERE'+ status);
});

Try removing http://localhost from url and then see it may be CORS.

Just a guess: your url is pointing to localhost but has no port number, this is unusual, maybe you forgot it?

data: $.param({
email:$scope.user.email
})
Or this way: (modify the php)
Angular HTTP post to PHP and undefined

I have just found that in php file,
$_POST or $_GET will not work, to receive data.
Use the following:
$data = file_get_contents("php://input");
$objData = json_decode($data);
$email = $objData->email;
In my case it works.

Related

PHP can't read email address from $http post method of angular

Everything works fine except email address. When i post email address to server and just echo it, recieve nothing. Only problem in # symbol, rest are ok.
angular:
$http({
method: 'POST',
url: 'http://______.org/_____.php',
data: {
signInSubmitBTN: '', email: 'joe#g.com'
}
}).success(function (data) {
alert(data); //alert empty when joe#g.com but joeg.com is ok
});
PHP
if (isset($_POST['signInSubmitBTN'])) {
$email = $_POST["email"];
echo $email;
}
NOTE - already configure app
app.config(function ($httpProvider, $httpParamSerializerJQLikeProvider) {
$httpProvider.defaults.transformRequest.unshift($httpParamSerializerJQLikeProvider.$get());
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
})
You need to encode using base64:
signInSubmitBTN: '', email: window.btoa('joe#g.com')
And don't forget to decode on the server side using atob()
Use this code in back end to get POST data back in PHP.
if(isset($_POST)){
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo $request->email;
}

How to get data using php and angylarJS

I hope that you are in good mood :). I'm trying to return data which depend on text from user using AngularJS and php. So I create file php which contain my query and using $http.get in AngularJS. My problem is I want to integrate value of input in mysql query, but always using angular. I tried many times but nothing works To be more clear, here is muy code:
app.js
app1.controller('autoCompleteCTRL',function($scope,$rootScope,$http) {
$scope.search = function(){
$scope.$watch('searchText', function() {
console.log($scope.searchText);
});
$http({
method: "get",
url: "../SearchResultsQuery.php",
dataType: 'json',
data: { 'userText': $scope.searchText},
async: false,
params: {action: "get"}
}).success(function(data, status, headers, config) {
alert(data);
}).error(function(data, status, headers, config) {
alert(error);
});
};
}
index.html
<input type="text" placeholder="Search for items" id="textFiled" class="input" ng-model="searchText" ng-change="search()" />
app.php
<?php
$conn=pgsqlCon();
$searchText = mysql_real_escape_string(userText);
$query='SELECT * FROM planet_osm_roads AS a, to_tsquery_partial(\'%.$searchText.%\') AS query
WHERE ts_road ## query';
$result = pg_query($conn,$query);
$myarray = array();
while ($row = pg_fetch_row($result)) {
$myarray[] = $row;
}
pg_close($conn);
echo json_encode($myarray);
?>
I hope that you understand me Thanks for advance :)
try to make your http request like this:
app.controller('TestCtrl', function ($scope, $http){
$scope.search = function(){
$http.post('../app.php', {searchText: $scope.searchText})
.success(function (response){
console.log(response);
})
.error(function (response){
console.log(response);
});
}
});
app.php
<?php
$data = file_get_contents("php://input");
$searchText = mysql_real_escape_string($data['searchText']);
/* database code */
?>
This should work.
In your app.js file, instead of this line:
data: { 'userText': $scope.searchText}
write:
params: { 'userText': $scope.searchText}
and remove this line:
params: {action: "get"}
This way it will transfer userText variable through request URL as a GET parameter.
In your app.php file, instead of:
$searchText = mysql_real_escape_string(userText);
write:
$searchText = mysql_real_escape_string($_GET['userText']);
This will populate your $searchText php variable with text from client application (AngularJS). I'm not sure about your postgresql query. Your question title is mysql - How to get data..., but in your php code sample you use postgres extension to build query. But that's a different story I guess.

jQuery Ajax sending empty data

I'm doing a code that send a data to a php file and send it back again and print it as a response however when i send the data it is sent as an empty data i did not know what is the problem this is the code that i tried:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi, "").split("\n");
function doRequest(index) {
// alert(resource[0]); The data here is ok and it is not empty whenever the data is sent the response is empty !
$.ajax({
url:'curl_check.php?email='+resource[0],
async:true,
success: function(data){
alert(data);
if (resource.length != 1) {
removeResourceLine();
doRequest(index+1);
}
}
});
}
doRequest(0);
since you're not sending the data using the data property of the ajax call object like so:
$.ajax({
...
data : { email : resource[0] }
...
});
you are sending it as part of the URL, so it should be picked up as a GET variable. in php, this looks like:
$email = isset($_GET['email']) ? $_GET['email'] : false;
that said, i'd suggest using the ajax data property and specifying the type property and setting it to GET or POST. you could also use $.ajaxSetup
Ok I am not sure what is wrong with what you are doing but I am going to give you code I use to send data to php and get a response. I am going to do it with json because it is awesome. I hope it helps:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi,"").split("\n");
function doRequest(index) {
$.post("curl_check.php", {
email: resource[0]
}, function(data, result, xhr){
if(result == 'success') {
console.log(data.success);
} else {
console.log('post failed');
}
}, "json");
}
The php code:
$json = array();
$email = $_POST['email']; //Please escape any input you receive
//Do what you have to do
$json['success'] = 'YAY IT WORKED';
die(json_encode($json));

Form submission in JSON format via AJAX

I'm trying to submit a HTML form to a server and it fails. I have several issues here.
I'm making a CORS request. It is a request by the client and I can't do anything about it.
( My app resides in localhost:3000/login.html & My server resides in http://localhost:3001/Login/auth )
The server in localhost:3001 accepts JSON requests and give back a JSON Responce.
(I have disabled the web-security in the browser to allow the CORS Requests)
So, I have created the HTML Form and tried to submit it with AJAX. Here you can see the code.
$(function(){
$("#loginform").submit(function(e){
e.preventDefault();
// var data = $("#loginform").serialize();
var data = {"username" : $("#username").val(),"password" : $("#password").val()};
alert(JSON.stringify(data));
$.ajax({
type: "POST",
url: "http://localhost:3001/Login/auth",
data: data,
contentType: "application/json",
crossDomain : true,
dataType: "json",
success: function(data) {
alert("success" + JSON.stringify(data));
},
error:function(data){
alert('error : '+JSON.stringify(data));
}
});
});
});
I have created the mock server in PHP (codeigniter). Here is the code for that.
public function auth(){
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$debug_export = var_export(file_get_contents('php://input'), true);
file_put_contents('new.txt',$debug_export . PHP_EOL, FILE_APPEND);
$user = 'admin';
$pass = 'admin';
$token = '1';
foreach($input_data as $key=>$value) {
if ($key === 'username') {
$this_user = $value;
}
if ($key === 'password') {
$this_password = $value;
}
}
if(isset($this_user) && isset($this_password)){
if($this_password === $pass && $this_user === $user){
echo json_encode(array('token'=>$token));
}else{
echo json_encode(array('token'=>'null'));
}
}
return 0;
}
When I submit a form, I get a response like this.
....
<p>Severity: Warning</p>
<p>Message: Invalid argument supplied for foreach()</p>
<p>Filename: controllers/Login.php</p>
<p>Line Number: 77</p>
....
My 'new.txt' file has the log details as following.
''
'username=admin&password=admin'
I have really no idea what I'm doing wrong here. Can anyone help me out here?

Pass data from JQuery to database via Javascript/AJAX/JSON/PHP

I am attempting to add data to my database from my HTML code via the use of JQuery, AJAX/JSON and PHP using an MVC model. Below is a small sample of what I am looking to achieve.
In my front end I have a checkbox with different options and a button named 'Add'. The selected elements from here are picked up by a Javascript function, which I have tested properly, once this is done I call another Javascript function to do the AJAX/JSON . What I am still fresh on is the actual AJAX/JSON process that sends the data to PHP.
My Javascript function:
function add_fruits(fruit_name, fruit_type){
var success = "Fruit added";
var error = "Fruit not added";
var params = {
'fruit_name' : fruit_name,
'fruit_type' : fruit_type
};
$.ajax({
type: "POST",
url: "add_fruits.php",
async: false,
data: params,
success: function(success){
alert(success);
},
error: function(error){
alert(error);
}
});
}
My PHP function:
<?php
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
require_once 'lib/connection_files.php';
if($_SERVER['REQUEST_METHOD'] =='POST')
{
$fruit_name = no_sql_injection($_POST['fruit_name']);
$fruit_type = no_sql_injection($_POST['fruit_type']);
$fruits = new fruits();
$result = $fruits->add_fruits($fruit_name, $fruit_type);
$tmp = mysql_num_rows($result);
if($result == 1)
{//RESULT must return 1 to verify successful insertion to database
//send confirmation to front end
}
else
{
//send error message to front end
}
}
else{
//tell front end there was error sending data via AJAX
}
?>
Note that the add_fruits() function takes care of doing the Queries to the database, I did not include it here because it is irrelevant to my issue.
Just do echo in your PHP:
PHP
else {
//send error message to front end
echo "Error Adding Fruits";
}
JS
success: function(data) {
if (data == "1") {
//data added to db
}
else {
alert(data);
}
}

Categories