Angular $http post not working with a https url - php

In my ionic app I have the following code:
$http({ url: "http://someurl/script.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({param1:$localStorage.test.paramtest})
}).success(function(data) {
//console.log(data);
$scope.data = data;
}).error(function(data) {
//console.log("error:" + data);
alert("error:" + data);
})
.finally(function (data) {
//console.log("ok:" + data);
alert("ok:" + data);
});
The code above is working fine and I'm able to post en retrieve data from my database.
When I change the http:// url to a https:// url all of a sudden it is not working anymore. The error function gives me the error "error: null"
When I manually define the id in the php script and run de script with the https url in my browser it is also working.
This is mij script.php code:
<?php
//variables
$id = $_POST["param1"];
//$id = "12047";
// databse connection variables
$hostname = "...";
$username = "...";
$password = "...";
$database = "...";
// Create connection
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully<br>";
// show all database entries
$sql = "SELECT * FROM table1 WHERE field1_id='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rows = [];
while($row = $result->fetch_assoc()) {
// Add all rows to an array
$rows[] = $row;
}
// Json encode the full array
echo json_encode($rows);
} else {
//echo "0results";
}
$conn->close();
?>
I have setup my hosting to work with https and installed a SSL certificate on my server.

I found out that my hosting provider doesn't support SSL database connections in there hosting packages. It appears that this is only possible with dedicated servers.

Related

Why isn't the response from Ajax showing?

I'm passing values using ajax from a web page to a php file. The purpose is to pass database credentials to be able to test the database connection and get the result in return. I'm passing server name, username and password to the php file. The problem is that I'm not able to see the database connection response from the php file.
This is how I call the function within document ready:
$('#dbconn').click(db_connect)
Here is my ajax code:
function db_connect(dbserver, dbuser, dbpassword) {
var dbserver;
var dbuser;
var dbpassword;
dbserver = $('input:dbserver').val();
dbuser = $('input:dbuser').val();
dbpassword = $('input:dbpassword').val();
$.ajax({
url : "script/create_db.php",
type : "POST",
cache : false,
data : {
dbserver : dbserver,
dbuser : dbuser,
dbpassword: dbpassword,
success: function(result){alert ("response")}
}
});
};
And this is my php code:
$servername = $_GET["dbserver"];
$username = $_GET["dbuser"];
$password = $_GET["dbpassword"];
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
echo "Connection succsess";
}
Any help is highly appreciated
success: function(result){alert ("response")}
When you get the response you alert the string "response".
You ignore the value of result entirely.
You don't see the response because you aren't looking for it.

Retrieve ID number from MYSQL using AJAX & PHP then hashchange URL using retrieved ID

I'm trying to retrieve the latest video ID number from my database and then use that ID number to hashchange my URL and display the corresponding video. My PHP is working and returning a result but I'm not sure how to take that result and use it in jQuery so that I can use it for the hashchange. I haven't used jQuery much before so any detailed help would be amazing! Please find my current code below. The main question I have is how do I pass the $vidarray to jQuery so I can use that variable?
videoprocess.php
<?php
// Connect To DB
$hostname="localhost";
$database="MYDB";
$username="root";
$password="";
#$conn = mysqli_connect($hostname, $username, $password)
or die("Could not connect to server " . mysql_error());
mysqli_select_db($conn, $database) or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
// Display Error message if fails
echo 'Error, could not connect to the database please try again again.';
exit();
}
$query = "SELECT VIDEOID FROM JubileeTouchVideo ORDER BY ID DESC LIMIT 1";
$result = mysqli_query($conn, $query) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$vidarray = array();
while($row = mysqli_fetch_assoc($result))
{
$vidarray = $row;
}
echo json_encode($vidarray);
//close the db connection
mysqli_close($conn);
?>
videoprocess jquery
$.ajax({
url: "data.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//Not sure what to do after this
}
});
This is how you can pass data to ajax.
$.ajax({
type: "POST",
url: url,
data: <?php echo $vidarray["id"]; ?>,
dataType: "text",
success: function(result) {
//result downloaded so we call parseJSON function
//and pass downloaded result
var json = $.parseJSON(result);
//Not sure what to do after this
}
});

PHP/JSON/ANDROID - why my JSONArray getting error

i try to displaying value of my table in android, and i put my code into hosting,
but when i try to running my app, my link doesn't work,
and i tried to create new link that displays the same output , and its works fine,
this is my code to encode json
send_data.php
<?php
include 'dbconfig.php';
$con = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "select id,ask from pertanyaan";
$result = mysqli_query($con, $query);
while ($r = mysqli_fetch_array($result)) {
extract($r);
$rows[] = array(
"id"=>$id,
"ask"=>$ask
);
}
header('Content-Type: application/json');
echo json_encode($rows);
mysqli_close($con);
?>
did I'm doing something wrong??
because I want to set the output from the database
This is just a suggestion without seeing your AJAX code:
Add this code to the top of your PHP code:
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
And use this code as an example of AJAX:
var poutput = $('.itemsHolder');
$.ajax({
url: 'https://yourdomain.com/php/YOUR-PAGE.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(pi,item){
str = item.id;
var products = '<div id="'+item.id+'">'+
'</div>';
poutput.append(products);
});
},
error: function(){
//alert('There was an error loading the data.');
}
});
Don't forget to add an element with the class name of itemsHolder to your page.

Angular $http - function/response undefined

I've been unable to retrieve data from a json or php file because angular keeps yelling at me that either the function or response is undefined.
I want to pull up the navigation items from MySQL, when it failed to load php I've put the contents in a regular json file to see what was the problem it seems something in angular itself.
PHP:
<?php
header('Content-type:application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = 'SELECT * FROM navigation';
$result = $conn->query($sql);
$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
$conn->close();
?>
Which results in:
[{"nav_id":"0","nav_name":"Home","nav_link":""}, {"nav_id":"1","nav_name":"Contact","nav_link":"contact"}]
So far so good?
Here's my angular code that gets the file:
(function() {
var app = angular.module("headerControl", []);
app.directive("headerNavigation", function() {
return {
retrict:'E',
templateUrl:'views/partials/header-navigation.html'
};
});
app.controller("navController", function($scope, $http) {
$scope.navlist = {};
$http.get('phpservices/nav.php')
.success(function(response) {
alert('success');
})
.error(alert('error'));
});
})();
When I load the page it first gives me the error response and after that the success response... in the console angular tells me this:
Error: [ng:areq] http://errors.angularjs.org/1.4.2/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20undefined
whats wrong about this? I can't seem to figure it out...
The problem is that you are not passing error callback function properly. It should be:
.error(function() {
alert('error')
});
Otherwise you just invoke alert immediately (note ()) and since it doesn't return anything (so it "returns" undefined) error handler receives undefined in it. However, it expects a function. That's why you get this error.

How can I work on the output of jsonp in phonegap?

I am working on a PhoneGap with Android project. I have designed a login page in which I want to show an alert box for a valid and invalid user. I am using PHP for database validation.
This is my php page:
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id, name,password FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
This is my java script function:
function onDeviceReady(){
var output = $('#output');
var id = document.getElementById('userid').value;
var pass = document.getElementById('password').value;
// webcam.set_api_url( 'test.php?filename=' + escape(filename));
$.ajax({
url: 'http://192.168.1.214/sample/dologin.php?id='+id+'&password='+pass,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
console.log('entered success============');
$.each(data, function(i,item){
var logi=item.id;
if(logi!=null)
alert("valid user");
else
alert("invalid user");
});
},
error: function(){
console.log('entered success====================');
output.text('There was an error loading the data.');
}
});
}
This is not working properly for an invalid user. Whenever I enter a valid user name and password then it displays the valid user message box. When I enter an invalid user name and password then it doesn't display anything.
Thank you in advance...
Try debugging this in a browser and perhaps send the returned jsonp data to the console from within your ajax's success call console.log(data).
It's quite possible that your jsonp is returning some data as opposed to null... even if it is simply undefined or an empty string. Your conditional is most likely the culprit.

Categories