This question already has answers here:
jQuery AJAX cross domain
(15 answers)
Closed 8 years ago.
I'm starting developing an app and I'm having trouble with the login.
I have a form with an Ajax call to a PHP service to validate the user, I uploaded both files to my server and it works perfect. I input user and password, goes to the PHP file and validate the user, so far so good.
The problem is that these two files will be in different servers. Now I have the PHP file hosted on my server, and the form/ajax call localhost and it doesn't work.
Here's the code:
PHP:
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "****";
$password = "****";
$database = "*****";
$con = mysql_connect($server, $username, $password) or die ("Error: " . mysql_error());
mysql_select_db($database, $con);
$user = mysql_real_escape_string($_POST["user"]);
$pass = mysql_real_escape_string($_POST["pass"]);
$result = mysql_query("SELECT * FROM Usuarios WHERE IdUsuario = '" . $user . "' AND Clave = '" . $pass . "'");
$numResults = mysql_num_rows($result);
echo $numResults;
mysql_close($con);
?>
JS:
$( document ).ready(function() {
$('form').submit(function(event){
event.preventDefault();
var user = $(this).find("#user").val();
var pass = $(this).find("#pass").val();
$.ajax({
type: 'POST',
crossdomain: true,
data: 'user=' + user + '&pass=' + pass,
url: 'http://www.url.com/login.php',
success: function(data){
if(data == 1){
alert("YES!");
}else{
alert("NO");
}
},
error: function(){
alert('Error');
}
});
return false;
});
});
I have also tried with dataType: "json" and "jsonp"
You need to change
data: 'user=' + user + '&pass=' + pass,
to
data: {user : user, pass : pass},
Related
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
}
});
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.
Okay my problem is the following:
I am trying to access a variable I defined with javascript in my executing php-script.
// CLIENT SIDE CODE
function deleteEntry() {
var action = '_includes/deleteEntry.php';
var method = 'post';
var data = '2';
$.ajax({
url: action,
type: method,
data: data
}).done(function(data){
$('.main').empty();
$('.main').append(data);
});
};
Now I want to make use of my data in a php-script (deleteEntry.php)
// SERVER SIDE CODE
<?php
// VERBINDUNG //
$connection = mysqli_connect('localhost', 'root', '', 'aufgabenplaner');
// if (!$connection){
// die('Verbindung nicht möglich : ' . mysql_error());
// }
// SQL-ABFRAGE //
$query = "DELETE FROM aufgaben WHERE job_nr =" ."DATA GOES HERE!!!";
$result = mysqli_query( $connection, $query );
include 'main-content.php';
?>
Where it says "DATA GOES HERE!!!" I want to make use of the data value, but I don't know how.
Normally you pass a JSON object as your POST
$.ajax({
url: action,
type: 'post', //put your declaration here for readability
data: {'var' : 2}
})
Then you would use $_POST['var'] in your PHP to get the value
You have to prepare data object so it has key - value pairs. This way you'll be able to access data in your PHP script. JavaScript:
function deleteEntry() {
var action = '_includes/deleteEntry.php';
var method = 'post';
var data = { number: '2'};
$.ajax({
url: action,
type: method,
data: data
}).done(function(data){
$('.main').empty();
$('.main').append(data);
});
};
PHP:
// SERVER SIDE CODE
<?php
// VERBINDUNG //
$connection = mysqli_connect('localhost', 'root', '', 'aufgabenplaner');
// if (!$connection){
// die('Verbindung nicht möglich : ' . mysql_error());
// }
// SQL-ABFRAGE //
$number = (int)$_POST['number']; // make sure it's no malicious input from user
$query = "DELETE FROM `aufgaben` WHERE `job_nr` = '" . $number . "'";
$result = mysqli_query( $connection, $query );
include 'main-content.php';
?>
Basically I have a php script located on a sever that generates a JSON file listing places from a mysql database. Using jQuery Mobile I am developing an application to display these places. My code works in Chrome & Safari, however when I port it over to Phonegap it doesn't work. I have searched all over the internet but can't find an answer :(.
The php file for generating JSON (json.php):
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "xxx";
$password = "xxx";
$database = "xxx";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT * FROM places ORDER BY name ASC";
$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) . ');';
?>
My Javascript file located within my app (Loads JSON and displays it):
$('#places').bind('pageinit', function(event) {
getPlaces();
});
function getPlaces() {
var output = $('#placeList');
$.ajax({
url: 'http://www.mysite.com/json.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<li><a href="">'+item.name+'<span class="ui-li-count">'
+ item.checkins+'</span></a></li>';
output.append(place);
});
$('#placeList').listview('refresh');
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
The HTML looks like this:
<div data-role="content">
<h3>Places</h3>
<ul data-role="listview" id="placeList" data-inset="true">
</ul>
</div><!-- /content -->
This code works in Chrome & Safari, however when run in the xCode simulator with Phonegap it doesn't load the JSON.
Any help would be much appreciated :)
This has probably something to do with the whitelisting, Apple has no faith in any type of uncontrollable data (like iframes or feeds). So they reject every external connection.
Take a look at phonegap.plist in your project rootfolder (xcode) and add your website url to the array 'ExternalHosts'. This will probably work fine after.
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.