How to get data using php and angylarJS - php

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.

Related

Return data AJAX PHP

By defaut, when my system loads some data is filtered in my db and shown to the user. But my doubt is how can I call AJAX to filter some new data, and return it, changing the default values that are already set on my variables.
This is my AJAX call:
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
data: {rede: $("#dropdown-parceria").val()},
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And this is what I got from trying to filter some data to return it,
but nothing worked:
<?php
require_once('../../includes/conecta.php');
$rede = $_POST['rede'];
function buscaDados($conexao){
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
}
Any idea?
Thanks!
You should add echo at the end :
echo json_encode($dados);
So the $dados array will be sent back to the ajax request as JSON response.
Parse the response to json uisng $.parseJSON() :
.done(function(resposta){
resposta = $.parseJSON(resposta);
console.log(resposta);
})
Hope this helps.
in your ajax code u add a success.
$("#botao-filtrar").click(function(){
$(".mask-loading").fadeToggle(1000);
$.ajax({
url: 'datacenter/functions/filtraDashboardGeral.php',
type: 'POST',
dataType: 'json',
data: {rede: $("#dropdown-parceria").val()},
success: function (data) {
//You do not need to use $.parseJSON(data). You can immediately process data as array.
console.log(data)
//if you have a array you use the following loop
for (var j =0;j < data.length;j++) {
console.log(data[j]);
// u can use data[j] and write to any fields u want.
// e.g.
$('.somediv').html(data[j].myarraykey);
}
})
.done(function(resposta){
console.log(resposta);
})
.always(function(){
$(".mask-loading").fadeToggle(1000);
})
});
And for the php codes (i did not check whether your code is valid or not), you need to add the echo and a die to end the call.
$rede = $_POST['rede'];
$dados = array();
$resultado = mysqli_query($conexao, "SELECT * FROM evolucao_originacao WHERE rede = {$rede}");
while($valores = mysqli_fetch_assoc($resultado)){
array_push($dados, $valores);
}
echo json_encode($dados);
die();

Ajax call using angular js

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.

return response correctly for jquery autocomplete in Codeigniter

I am new to jquery and am having trouble with the autocomplete function. edit:I should mention I am using MVC with Codeigniter. My AJAX response is returning like this [{"customer_name":"Adecco Management & Consulting S.A."}]. It is also not all in a row it is each character in the dropdown like this
[
{
"
c
u
s
t
and so on. Here is my autocomplete script.
$('#cust_name').autocomplete({
source: function(request,response){
var request = {
toSearch: $('#cust_name').val()
};
$.ajax({
url: '/researchDB/index.php/rdb_con/autoComplete',
data: request,
datatype:"json",
type: 'POST',
success: function(data){
response(data);
}
});
}
});
and my controller:
function autoComplete(){
$data['id'] = $this->rdb_mod->autoComplete();
echo json_encode($data['id']);
}
model:
public function autoComplete(){
$toSearch = $_POST['toSearch'];
$this->db->select('customer_name');
$this->db->like('customer_name', $toSearch, 'after');
$query = $this->db->get('research');
return $query->result();
}
input in view:
<input data-input-type="cust_name" id="cust_name" class="ids form-control search-query " type="text" name="customer_name">
I am not sure I set up the jquery function correctly but the response includes the desired results, in the wrong format, when I type in the input. Thanks for any help you can give!
I received the answer outside of SO and want to post the solution here for others.
controller: I needed to put the results into an array and pass that to the ajax response as one object.
function autoComplete(){
$data['id'] = $this->rdb_mod->autoComplete();
$results = array();
foreach($data['id'] as $row){
$results[]=$row->customer_name;
}
echo json_encode($results);
}
jquery: As far as I understand this section, I wasn't making use of the built in functions and therefore overwriting the request variable that autocomplete sets up.
$('#cust_name').autocomplete({
source: function(request,response){
$.ajax({
url: '/researchDB/index.php/rdb_con/autoComplete',
data: request,
datatype:"json",
type: 'POST',
success: function(data){
var items = JSON.parse(data);
response(items);
}
});
}
});
model: didn't change much. I added distinct to limit dup values.
public function autoComplete(){
$toSearch = $_POST['term'];
$this->db->distinct();
$this->db->select('customer_name');
$this->db->like('customer_name', $toSearch, 'after');
$query = $this->db->get('research');
return $query->result();
}
Thanks to all those who helped me with this!

Ajax update table with php content

How to make an animated table only animate when a new record is added to the database.
Ajax/Js (in index.php):
$.ajax({
url : 'Not sure what goes here?',
data : {Not sure what goes here?},
dataType : 'application/json', // Is this correct?
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
var newitem = function(response){
var item = $('<div>')
.addClass('item')
.css('display','none')
.text(response)
.prependTo('#scroller')
.slideDown();
$('#scroller .item:last').animate({height:'0px'},function(){
$(this).remove();
});
}
My php (latest.php):
include ('db.php');
$sql2 = "SELECT * FROM `feed` ORDER BY `timez` DESC";
$res2 = mysql_query($sql2) or die(mysql_error());
while($row3 = mysql_fetch_assoc($res2)){
$user = $row3['username1'];
$action = $row3['action'];
$user2 = $row3['username2'];
echo ''.$user.''.$action.''.$user2.'<br>'; // Needs to be a json array?
I can't get this to work, here's how the table operates http://jsfiddle.net/8ND53/ Thanks.
$.ajax({
url : your_php_file.php',
data : {data you'r going to send to server}, // example: data: {input:yourdata}
success: function(response) {
$('#table_id').append('<tr>'+response+'</tr>'); // response is the date you just inserted into db
}
});
in your_php_file.php:
add the item into db
echo that inserted data # if you echo, then you can catch this with ajax success function then you append it into your table.
try to fill as below:
$.ajax({
type: "post"
url : 'locationOfphpCode/phpCode.php',
data : {data you want to pass}, //{name: "dan"}
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
in your php code you need to receive the data you have passed from the ajax call:
<?php
$name = $_POST['name'];
...
?>
you may add some validations in your php code.
hope this will help you.
the example you have given is using setInterval(newitem, 2000)
so you have to call ajax function on some fixed interval.

Xml reply from PHP to post of jquery Ajax

i have a javascript code that requests a php page to provide it with list of names that are currently online and update a Table, but i have a problem sending it back in form of an array, someone told me that this is usually done using XML, but i dont know how to start.
javascript Post method:-
$.post( "updateTable.php", POSTdata,
function( data ) {
$("#mytable").last().append('<tr><td>'+data+'</td></tr>');
}
);
the php file:-
include("connect.php");
$query1 = "SELECT * FROM formtable";
$result_id = mysql_query($query1, $global_dbh)
or die ("display_db_query:" . mysql_error());
while ($table_array = mysql_fetch_object ($result_id))
{
$rows[] = $table_array;
}
foreach ($rows as $temp ) {
if ($temp->isOnline==1)
$newRow[] = $temp->name;
}
echo "$newRow";
mysql_close($global_dbh);
Please excuse any syntax or semantics in my code, i am a beginner.
How can i populate my table using ajax callback function, and in what form the data will arrive there, and how can i use xml to help me.
Many thanks in advance.
A quick example of json:
var table = $("#mytable").last();
$.ajax({
type: 'post',
url: "updateTable.php",
dataType: 'json',
data: POSTdata,
success: function(data){
jQuery.each(data, function(i, row){
//console.log(row);
table.append('<tr><td>'+row.name+'</td></tr>');
});
}
});
and in php file, instead of :
echo "$newRow";
replace with:
echo json_encode($newRow);
That's it!

Categories