Send parameters via POST HTTPRequest (appcelerator titanium) - json

I have created a page on my server (index.php) that when access by the app (via appcelerator titanium) via createHTTPClient (app.js and login.js), returns a JSON string. But i have problems when i login and send parameters via POST HTTPRequest.
index.php :
<?php
class Connect{
public function login($username, $password){
$db = mysqli_connect("mysql6.000webhost.com", "a8324766_user", "**********", "a8324766_db");
if (mysqli_connect_errno()) {
printf("Échec de la connexion : %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT *
FROM users
WHERE username ='$username'
AND password = '$password'";
$req = mysqli_query($db, $sql);
$data = mysqli_fetch_assoc($req);
if(isset($data['username'])&& !empty($data['username']) && isset($data['password'])&& !empty($data['password'])){
if (mysqli_num_rows($req) > 0){
$response = array(
"logged" => true,
"name" => $data['name'],
"email" => $data['email']);
echo json_encode($response);
}
else
{
// Else the username and/or password was invalid! Create an array, json_encode it and echo it out
$response = array(
"logged" => false,
"message" => 'Invalid Username and/or Password'
);
echo json_encode($response);
}
}else{
echo "login ou mot de passe est incorrecte";
}
}
}
$user = new Connect();
$user->login($_POST['username'], $_POST['password']);
?>
app.js :
Titanium.UI.setBackgroundColor('#fff');
var tabGroup = Titanium.UI.createTabGroup();
var login = Titanium.UI.createWindow({
title:'User Authentication Demo',
tabBarHidden:true,
url:'login.js'
});
var loginTab = Titanium.UI.createTab({
title:"Login",
window:login
});
tabGroup.addTab(loginTab);
tabGroup.open();
login.js :
var win = Titanium.UI.currentWindow;
var username = Titanium.UI.createTextField({
color:'#336699',
top:10,
left:10,
width:300,
height:40,
hintText:'Username',
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(username);
var password = Titanium.UI.createTextField({
color:'#336699',
top:60,
left:10,
width:300,
height:40,
hintText:'Password',
passwordMask:true,
keyboardType:Titanium.UI.KEYBOARD_DEFAULT,
returnKeyType:Titanium.UI.RETURNKEY_DEFAULT,
borderStyle:Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
});
win.add(password);
var loginBtn = Titanium.UI.createButton({
title:'Login',
top:110,
width:90,
height:35,
borderRadius:1,
font:{fontFamily:'Arial',fontWeight:'bold',fontSize:14}
});
win.add(loginBtn);
var xhr = Ti.Network.createHTTPClient({timeout:50000});
xhr.onload = function(e) {
Ti.API.info("Received text: " + this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.logged == true){
alert("Welcome " + response.name + ". Your email is: " + response.email);
} else {
alert(response.message);
}
};
xhr.onerror = function(e) {
Ti.API.info('Error >>>> ' + JSON.stringify(e));
};
loginBtn.addEventListener('click',function(e){
xhr.open("POST","http://lahcene.comli.com/index.php");
var params = {
username: username.value,
password: password.value
};
alert(username.value);
alert(password.value);
xhr.setRequestHeader( 'Content-Type','application/json' );
xhr.send(params);
});
The result :
http://i.stack.imgur.com/OfByi.png
The result whene i login with username and password :
http://i.stack.imgur.com/9qm1m.png
any idea please.

The most simply answer for fix cross-domain is a LAMP or use Domain Server at Website:
Install Lamp (Linux) , Install Mamp (Mac OS) & Install Xampp (Windows)
When you install this software bundle, use your html in it :)
1º You have a problem in your send due to Content-Type must be application/x-www-form-urlencoded
2º Your function php login() return a JSON or String... must be JSON always because you use JSON.parse at xhr.onload().
echo "login ou mot de passe est incorrecte"; change to
$response = array(
"logged" => false,
"message" => 'login ou mot de passe est incorrecte'
);
echo json_encode($response);

Related

Ajax post using json doesnt send data or show error messages

I'm trying to send contact form data to database and get response with json.
Only error what I get is:
SyntaxError: Unexpected token T in JSON at position 0
My ajax:
$(document).ready(function(){
$('#send').on('click',function(e){
e.preventDefault();
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url : '<?php echo $baseurl;?>/contactus.php',
type: 'post',
dataType : 'json',
data : {name:name,email:email,phone:phone,subject:subject,message:message},
success:function(response){
if(response.type == 'error'){
output = '<div class="error">'+response.text+'</div>';
}else{
$('#form')[0].reset();
output = '<div class="success">'+response.text+'</div>';
}
$("#contact_results").html(output);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
});
My PHP:
header('Content-Type:application/json');
include('include-global.php');
if($_POST){
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
print "Can't access directly!";
exit;
}
$sender_name = $_POST["name"];
$sender_email = $_POST["email"];
$phone_number = $_POST["phone"];
$subject = $_POST["subject"];
$message = $_POST["message"];
if(strlen($sender_name)<3){
$output = json_encode(array('type'=>'error', 'text' => 'First and lastname is too short!'));
die($output);
}
if(strlen($subject)<3){ //check emtpy subject
print json_encode(array('type'=>'error', 'text' => 'Subject too short'));
exit;
}
if(strlen($message)<3){ //check emtpy message
print json_encode(array('type'=>'error', 'text' => 'Message too short'));
exit;
}
try{
$database = new Connection();
$db = $database->openConnection();
$sql = "INSERT INTO contact SET name = :name, phone = :phone, subject = :subject, email = :email, message = :message";
$qry = $db->prepare($sql);
$qry -> bindParam(':name', $sender_name, PDO::PARAM_STR);
$qry -> bindParam(':phone', $phone_number, PDO::PARAM_STR);
$qry -> bindParam(':email', $sender_email, PDO::PARAM_STR);
$qry -> bindParam(':subject', $subject, PDO::PARAM_STR);
$qry -> bindParam(':message', $message, PDO::PARAM_STR);
$qry -> execute();
} catch (PDOException $e) {
echo "There is some problem in connection: " . $e->getMessage();
}
if(!$qry){
print json_encode(array('type'=>'error', 'text' => 'Error.'));
exit;
}else{
print json_encode(array('type'=>'message', 'text' => 'Thank you '. $sender_name . '.'));
exit;
}
}
I dont understand what I'am doing wrong...
Code and JSON seems to be correct, I got example from google.
Im using dataType, header content type json but still shows error.

Slim API, doesn't work after connection

I'm trying to make an API. I've follow a tutorial in OpenClassRoom to make request with MySQL, and I want an API with Slim v3.2.
So I receive the answer of the connexion, but when I want to recover data from a get I have a "Slim Application Error" And I don't know what to do with that.
I'm using MAMP instead of "php -S localhost:8080 -t public public/index.php " because I have the good connection with my database.
I show you my API:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '/Users/kravennagen/Downloads/Api/api/racehistory/vendor/autoload.php';
$app = new \Slim\App();
echo "hello";
try{
$bdd = new PDO('mysql:host=localhost;dbname=racehistory;charset=utf8', 'root', 'root', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
echo "connexion...";
}
catch(Exception $e){
die('Erreur connexion BDD:' . $e->getMessage());
}
echo "avant le get";
$app->get('/', function(){
$reponse = $bdd->query('SELECT * FROM user');
while($data = $reponse->fetch()){
echo $data['mail'];
echo $data['password'];
}
$reponse->closeCursor();
});
$app->get('/connexion/{identifiant}/{password}', function($login, $pass){
$reponseMail = $bdd->query('SELECT mail FROM user');
$reponsePass = $bdd->query('SELECT password FROM user');
echo "test1";
While($donnees = $reponseMail->fetch() && $donnees = $reponsePass->fetch()){
if($donnees['mail'] == $login && $donnees['password'] == $pass){
echo "true";
//return true;
}
else{
echo "false";
//return false;
}
}
$reponsePass->closeCursor();
$reponseMail->closeCursor();
});
$app->get("/register/{identifiant}/{password}", function($login, $pass){
$add = 'INSERT INTO user(mail, password) VALUES ($login, $pass)';
if(!preg_match("#^[a-z0-9._-]+#[a-z0-9._-]{2,}\.[a-z]{2,4}$#", $login))
$errors['mail'] = 'adresse mail non valide';
else if (!preg_match("#^(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*\d)([\w]{8,15})$#", $pass))
$errors['password'] = "le mot de passe n'est pas conforme(majuscule au debut, de 8 a 15 caractères)";
else if($bdd->exec($add) === false){
echo "ERREUR INSERTION";
}
else{
echo "User bien ajouté la base de donnée";
}
});
$app->run();
?>
You have to inject your $bdd connection object to the route by using "use":
$app->get('/', function() use ($bdd) {

Send JSON from HTTPS to HTTP

I use Request solution for ajax-request, but I get an error:
reqwest.min.js:6 Mixed Content: The page at 'https://...' was loaded
over HTTPS, but requested an insecure XMLHttpRequest endpoint
'http://...'. This request has been blocked; the content must be
served over HTTPS.
Server-side code (i'm using wordpress plugin for this):
add_action('wp_ajax_nopriv_wpse144893_search', 'wpse144893_search_data'); // allow logged out users
add_action('wp_ajax_wpse144893_search', 'wpse144893_search_data'); // allow logged in users
function wpse144893_search_data(){
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
$errors = array();
$data = array(
'status' => 'error',
'message' => '',
'result' => array()
);
if(!isset($_REQUEST['term']) || empty($_REQUEST['term']))
$errors[] = 'No search term given!';
if(!isset($_REQUEST['limit']) || empty($_REQUEST['limit']))
$limit = 10;
else
$limit = (int) $_REQUEST['limit'];
if(empty($errors)){
$term = sanitize_text_field($_REQUEST['term']);
// setup query data
$args = array(
'posts_per_page' => $limit,
's' => $term
);
$query = new WP_Query($args); // run query
$results = array();
if($query->have_posts()): while($query->have_posts()): $query->the_post();
$post_item = array(
'title' => get_the_title(),
'excerpt' => get_the_excerpt(),
'permalink' => get_permalink()
);
$results[] = $post_item;
endwhile;
$data['status'] = 'success';
$data['message'] = 'Results found!';
$data['result'] = $results;
else:
$errors[] = 'No post found!';
$data['message'] = $errors;
endif;
}
echo json_encode($data); // print json
die(); // kill the script
}
Client-side code (request plugin):
reqwest({
url: 'http://...'
, type: 'json'
, method: 'get'
, crossOrigin: true
, withCredentials: true
, error: function (err) { alert('1'); }
, success: function (resp) {
alert('2');
}
})
I tried use this header('Content-type: application/json');header('Access-Control-Allow-Origin: *'); (see in server code above) but it does not solve the problem.
Problem is solved by moving second server to HTTPS...

Returning a json Response from a laravel project "Cannot read Property of Null"

I have here in my php file (laravel ) after i send an email and get a response to the mobile application
$msg ="email sent " ; $erreur=false ;
return response()->json(['Message' => $msg, 'erreur' => $erreur]);
But, When I get a response using this code in my javascript file
sendButton.onload = function(e)
{
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response.erreur == false)
{
alert("a Password has been send to you email ");
}
else
{
alert(response.Message);
}
};
I get this error
The error is pretty straight forward the response is null
sendButton.onload = function(e)
{
Ti.API.debug(this.responseText);
var json = this.responseText;
var response = JSON.parse(json);
if (response !=null && response.erreur == false)
{
alert("A password has been sent to your email.");
}
else
{
console.log(response); //probably doesnt have Message either
}
};
#MikeMiller
here is my Js code that communicates with my API
loginBtn.addEventListener('click',function(e)
{
if ( email.value!='')
{
try {
loginReq.open("POST","http://192.168.0.105/appcelerator/public/");//my local ip im testing on my computer
var params = {
email:email.value,
};
loginReq.send(params);
}catch (e)
{
alert(e.message);
}
}
else
{
alert("All fields are required");
}
});
now here is my code in my API (php laravel )
public function getPassword(Request $request)
{
$email = $request["email"];
$user = \DB::table('users')
->where('email', $request['email'])
->first();
$email = $user->email;
session()->put('email',$email);
if (!$user)
{
$msg = 'invalid email adresses';
$erreur = true ;
}else
{
Mail::send('emails.test',['password' => $this->generatePass() ],function($message )
{
$message->to(session()->get('email'),'Bonjour')->subject('welcome:');
});
$msg = 'Password has benn send to your email ';
$erreur = false;
}
return response()->json(['Message' => $msg, 'erreur' => $erreur]);
}
when it's executed i get the email in my email adresse but the response as you know is null. that's my problem

JSON variable is not passed to ajax function

Here is the Ajax Code. I am using this ajax code to pass the details to the php page and the php file is supposed to return an array value as true or false depending on the condition. I have used json_encode but it doesn't seem to work
$.ajax({
url: "join_form.php",
type: "POST",
dataType: 'json',
data: {
name: name,
email: email,
contact: contact,
role: role,
dialcode: dialcode,
countrycode: countrycode
},
cache: false,
// var data = JSON.parse(data);
success: function(data) {
data = $.parseJSON(data);
console.log(data);
if(data.status == 'false')
{
alert("Something went wrong");
}
else
{
alert("Message submitted successfully");
$("#joinForm").trigger("reset");
}
// alert(dialcode+countrycode);
}
});
$("#joinForm").trigger("reset");
});
Here is the Php file (join_form.php).
This php file checks for validity of fields and stores a false value
in the
array on which I use json_encode function so that it can
be returned to ajax. But on returning nothing happens.
It shows blank function.
if else functions are not executed. Please help
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "kites";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
alert("Connection failed");
}
else
{
$response = array();
// Check for empty fields
if(
empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['contact']) ||
empty($_POST['role']) ||
empty($_POST['dialcode']) ||
empty($_POST['countrycode'])
)
{
echo "No arguments Provided!";
$response['status']='false';
}
else{
$name = $_POST['name'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$role = $_POST['role'];
$dialcode = $_POST['dialcode'];
$countrycode = $_POST['countrycode'];
$stmt = $this->conn->prepare("SELECT email from join_form WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// user existed
// $stmt->close();
$response['status'] = 'false';
} else {
// user not existed
// $stmt->close();
$response['status'] = 'true';
}
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($response);
$sql = "INSERT INTO join_form (name,email,contact,role,dialcode,countrycode)
VALUES ('$name','$email','$contact','$role','$dialcode','$countrycode')";
if (mysqli_query($conn, $sql)) {
$response['status'] = 'true';
}
else {
echo "Please do it again";
$response['status'] = 'false';
// echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
header("Content-Type: application/json; charset=utf-8", true);
echo json_encode($response);
}
}
?>
Remove all the un-needed echos from your php, and keep only the last one 'echo json_encode($response);'.
Than you don't need to parse the returned response in your ajax call. So you will get your status and you can do something with it.
Alternatively if you wnat also to return the messages you are echoing than you can do the following:
$response['status'] = 'false';
$response['message'] = 'No arguments Provided!';
echo json_encode(response).
And than in your ajax call response:
if(data.status == 'false')
{
alert(data.message);
}
}
NOTE: remove the 'HEADER's from your php, you also don't need this. In the ajax call you have set 'data-type = json' and this is enough. The data will be sent back with the appropriate headers automatically!
You are passing the variable to your your data:
data: {
name: name,
email: email,
contact: contact,
role: role,
dialcode: dialcode,
countrycode: countrycode
},
from where do you get those values?
If they are coming from a form you will need to refer to them:
var name = $('#name').val()
... and so on.
Maybe you already did that but You are not posting your complete code n order to give me the possibility to spot your problem. And by the way, down voting the answer before you will post the complete code in here don't really help.
If you don't post also your HTML I can not see that.
NOTE: You answer with a 'Nothing worked' doesn't really help, and you don't mention the errors you are eventually receiving, so I still have to guess.