Comparing $.ajax result - php

I would just like to know how to go about comparing the resulting echo from a $.ajax call in JavaScript. I attempted this and even though I get 1, it doesn't actually compare the results correctly.
jQuery:
$.ajax({
type: "POST",
url: "login.php",
data: user,
dataType: 'html',
success: function(result)
{
alert(result);
if(result == '1')
{
alert("logged in :D");
//document.location.replace('home.php');
}
else
{
alert("not logged in :<");
}
},
failure: function()
{
alert('An Error has occured, please try again.');
}
});
PHP:
<?php
session_start();
$host = "localhost";
$user = "root";
$passw = "";
$con = mysql_connect($host, $user, $passw);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$json = $_REQUEST['json'];
$json = stripslashes($json);
$jsonobj = json_decode($json);
$password = $jsonobj->password;
$email = $jsonobj->email;
mysql_select_db("tinyspace", $con);
$result = mysql_query("SELECT 1 FROM users WHERE email = '"
. $email . "' AND password = '" . $password . "'");
while($info = mysql_fetch_array( $result ))
{
if($info[0] == 1)
{
echo '1';
}
}
?>

There's probably a space or line break after the '1' that is echoed. Check if there's no space before the opening <?php tag and remove the closing ?> tag (you're allowed to do that, and it will prevent accidental whitespace being outputted.
You should be able to check by changing the javascript to:
alert('X' + result + 'X');
You'll see soon enough if there's any whitespace around result.

try to send json response
php:
echo json_encode(array(
'status' => 'ok',
));
js:
dataType : "json",
success : function(response) {
if (response.status == "ok") {
alert('success');
} else {
alert('error');
}
}

Related

PHP variable to JS variable using AJAX

I'm trying to convert a PHP variable to a JS variable so I can use it in a game I'm making. When I check the map code it is just undefined. Thanks in advance. FYI the PHP works.
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: $mapCode,
used: $used,
active: $active,
},
dataType: "text",
});
}
</script>
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
?>
I understand that the PHP Code is hideous but it works and I'm going to 'pretty it up' later when the whole thing is working
If the file extension is .php and not .js then this should work
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: "<?php echo $mapCode; ?>",
used: "<?php echo $used; ?>",
active: "<?php echo $active; ?>",
},
dataType: "text",
});
}
</script>
If you have .js file then declare javascript variable before including your js in .php file
<script>
var mapCode = "<?php echo $mapCode; ?>";
var used = "<?php echo $used; ?>";
var active = "<?php echo $active; ?>";
</script>
then in .js file you will get easily
<script>
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
mapCode: mapCode,
used: used,
active: active,
},
dataType: "text",
});
}
</script>
You only need to use <?php echo $mapCode;?> instead $mapCode. .... php variables can't be reed whithout open Php tag
My current project is actually dealing with lots of ajax calls,
here is the simplified version of what I use to communicate with server:
// php
// needed functions
function JSONE(array $array)
{
$json_str = json_encode( $array, JSON_NUMERIC_CHECK );
if (json_last_error() == JSON_ERROR_NONE)
{
return $json_str;
}
throw new Exception(__FUNCTION__.': bad $array.');
}
function output_array_as_json(array $array)
{
if (headers_sent()) throw new Exception(__FUNCTION__.': headers already sent.');
header('Content-Type: application/json');
print JSONE($array);
exit();
}
// pack all data
$json_output = array(
'mapCode' => $mapCode,
'used' => $used,
'active' => $active
);
// output/exit
output_array_as_json( $json_output );
// javascript
function _fetch()
{
return $.ajax({
url: 'getMapCode.php', // url copied from yours
type: 'POST',
dataType: 'json',
success: function(data, textStatus, req){
console.log('server respond:', data);
window.mydata = data;
},
error: function(req , textStatus, errorThrown){
console.log("jqXHR["+textStatus+"]: "+errorThrown);
console.log('jqXHR.data', req.responseText);
}
});
}
window.mydata = null;
_fetch();
I have not tested this, but let me know I'll fix it for you.
How did i get you, you need to get the result from ajax request, to do it, you should first setup your php outputs your results, so the ajax can get outputed results from php like this:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
mysqli_select_db($conn, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// echo "Connected successfully";
$query = "SELECT mapCode FROM mapCodes";
$result = mysqli_query($conn, $query);
$mapCode = mysqli_fetch_row($result);
$query1 = "SELECT used FROM mapCodes";
$result1 = mysqli_query($conn, $query1);
$used = mysqli_fetch_row($result1);
$query2 = "SELECT active FROM mapCodes";
$result2 = mysqli_query($conn, $query2);
$active = mysqli_fetch_row($result2);
mysqli_close($conn);
// Outputing results:
echo json_encode(array('mapCode'=>$mapCode[0], 'used'=>$used[0], 'active'=>$active[0]));
?>
Then in ajax, use success for listening return message after ajax finished:
<script>
var mapCode;
var used;
var active;
function downloadCode() {
$.ajax({
type: 'GET',
url: 'getMapCode.php',
data: {
/** Your data to send to server **/
},
dataType: "text",
success: function(data) { /** Here is data returned by php echo **/
var temp = $.parseJSON(data);
mapCode = temp['mapCode'];
used = temp['used'];
active = temp['active'];
}
});
}
</script>

Send GET in Ajax call and PHP script

I want to POST data from form. It works fine.
In the other functionality i want to get data from database.
I don't know where is mistake. I suspect that AJAX call is fine.
My PHP code:
<?php
$uuid = $_POST['uuid'];
$minor = $_POST['minor'];
$mayor = $_POST['mayor'];
$lokalizacja = $_POST['lokalizacja'];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "Polaczono";
}
$sql = "INSERT INTO beacons (uuid, major, minor, lokalizacja)
VALUES ('$uuid', '$minor', '$mayor', '$lokalizacja')";
if ($conn->query($sql) === TRUE) {
echo "Dane dodano prawidłowo";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlget = "SELECT uuid, major, minor, lokalizacja FROM beacons";
$result = $conn->query($sqlget);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode(array("value" => "UUID: " . $row["uuid"]));
}
} else {
echo "Brak rekordów w bazie";
}
$conn->close();
?>
AJAX call:
$('#admin').submit(function(e){
e.preventDefault();
if( ($("input[name=uuid]").val().length) > 40 || ($("input[name=minor]").val().length) > 5 || ($("input[name=mayor]").val().length) > 5 || ($("input[name=lokalizacja]").val().length) > 20){
$(".error-pola").show();
} else{
$.post('administrator-connect.php', $(this).serialize() )
.done(function(){
$(".success-wyslanie").show();
})
.fail(function(){
$(".error-wyslanie").show();
});
}
});
$(document).ready(function() {
$.ajax({
type: "GET",
url: 'administrator-connect.php',
dataType: 'json',
success: function(data)
{
alert("fsdfsd"+ data);
},
error: function(){
alert("not");
}
});
});
I am using:
echo json_encode(array("UUID" => $row["uuid"]));
and in ajax:
var jqxhr = $.get( "administrator-get.php", function(data) {
var jsonx = JSON.parse(JSON.stringify(data));
$( "#data-listing" ).html(jsonx);
});
But I get response:
{"UUID":"B9407F30-F5F8-466E-AFF9-25556B57FE6D"}
How to get only string ?
If you write this
dataType: 'json',
It expect for JSON value not string be sure to return only JSON.
You returns string value not JSON.
With like this code
echo "Polaczono";
Any echo would be the return value for ajax
At last you should return only one value like this.
echo json_encode($result);//an array result
You can check by string return. By removing dataType

Ajax PhoneGap always error

I must make an application, and I've decided to use PhoneGap, but my Ajax always say "ERROR", and I don't know why, because the insert works very well...
$("#test").click(function() {
var name = $("#name").val();
var password = $("#password").val();
alert(name+' '+password);
$.ajax({
type: "POST",
url: "http://191.165.1.16/PULZ/ajax_action.php",
// contentType: "application/json; charset=utf-8",
dataType: "json",
data : {
actionname : 'insert',
name:name,
password:password
},
success: function(data) {
alert("work");
},
error: function(data) {
alert("There was an error loading the feed");
}
});
});
And my PHP code
if (isset($_POST["actionname"]) && !empty($_POST['actionname'])){
$actionname = $_POST['actionname'];
if($actionname == 'insert'){
$connect = new PDOsql();
$name = $_POST['name'];
$password = md5($_POST['password']);
$sql="INSERT INTO user(name,password) VALUES(?,?)";
$opt = array($name, $password);
$connect->query($sql,$opt);
$connect = null;
die(
json_encode(
array(
'state'=>'success'
)
)
);
}
}
Try this
JAVASCRIPT
$("#test").click(function() {
var name = $("#name").val();
var password = $("#password").val();
alert(name + ' ' + password);
$.ajax({
type: "POST",
url: "http://191.165.1.16/PULZ/ajax_action.php",
// contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
actionname: 'insert',
name: name,
password: password
},
headers: {
'Content-Type': 'application/json'
}
success: function(data) {
alert("work");
},
error: function(data) {
alert("There was an error loading the feed");
}
});
});
PHP
if (isset($_POST["actionname"]) && isset($_POST['name']) && isset($_POST['password'])){
$actionname = $_POST['actionname'];
$name = $_POST['name'];
$password = $_POST['password'];
if($actionname == 'insert'){
$connect = new PDOsql();
$name = $_POST['name'];
$password = md5($_POST['password']);
$sql="INSERT INTO user(name,password) VALUES($name,$password)";
$opt = array($name, $password);
$connect->query($sql,$opt);
$connect = null;
die(
json_encode(
array(
'state'=>'success'
)
)
);
}
}
You can't use "empty()" with a non variable element, you will receive a internal server error "500", always.
Note: Prior to PHP 5.5, empty() only supports variables; anything else
will result in a parse error. In other words, the following will not
work: empty(trim($name)). Instead, use trim($name) == false.
PHP Manual - empty

php ajax login form

i want to make login form with session (with PHP + ajax), i send username from controller with json but it doesn't work. i don't know whats wrong, please help
this is the function in controller :
public function actionLogin()
{
$username = isset($_POST['username'])?$_POST['username']:null;
$password = isset($_POST['password'])?sha1($_POST['password']):null;
$json = new JsonHelper();
$result = array();
if($username && $password !=''){
$checkLogin = Administrator::model()->findByAttributes(
array('username'=>$username, 'password'=>$password));
$checkUser = Administrator::model()->findByAttributes(
array('username'=>$username));
$checkPass = Administrator::model()->findByAttributes(
array('password'=>$password));
$login = count($checkLogin);
$user = count($checkUser);
$pass= count($checkPass);
if($login==1)
{
$result['status'] = 'success';
$result['username'] = $username;
$json->addData('ajax', $result);
}
elseif($user == 1 && $pass == 0)
{
$result['status'] = 'wrongPass';
$json->addData('ajax', $result);
}
elseif($user == 0 && $pass == 1)
{
$result['status'] = 'wrongUser';
$json->addData('ajax', $result);
}
}
echo json_encode($json->getJson());
}
and this is the form_login.js file :
function login(){
var form = $('#login-form');
var formId = form.attr('id');
var action = form.attr('data-action');
var method = form.attr('data-method');
var formData = serializer(form); //don't mind this function
$.ajax(
{
url: action,
cache: false,
processData: false,
contentType: false,
type: method,
data: formData,
success: function(json)
{
// AJAX SUCCESS
var json = JSON.parse(result);
if(json['result']['ajax']['status']=='success')
{
//$_SESSION['username'] =json['username'];
window.location = baseUrl + "/appsterize/dashboard/index";
}
else if(json['result']['ajax']['status']=='wrongPass')
{
// Password wrong
alert("The password you entered is incorrect.");
}
else if(json['result']['ajax']['status']=='wrongUser')
{
// Username isn't exist
alert("Username isn't exist");
}
},
error: function(xhr, status, error)
{
// AJAX ERROR
var string = "<strong>Error!</strong> " + xhr['responseText'];
$(alertError).attr('data-text', string);
$(alertError).click();
},
});
}
some error is 'Uncaught ReferenceError: alertError is not defined'
Have an element with id = 'alertError'?
Could this be the solution:
$("#alertError").attr('data-text', string);
...
Basically, what #serakfalcon said above:
...
error: function(xhr, status, error)
{
// AJAX ERROR
var errorMsg = "<strong>Error!</strong> " + xhr['responseText'];
alert(errorMsg);
},
...

PHP jQuery AJAX

Trying to pass data to the server but it keeps returning a "Parameter Missing"
So either the data is not being passed to the PHP script or I am doing something wrong.
Here is the jQuery:
function quickJob(obj) {
var quickJobNumber = $(obj).text();
//alert(quickJobNumber)
$.ajax({
type: "GET",
url: "quickJobCB.php",
data: quickJobNumber,
success: function(server_response)
{
$("#message").removeClass().html(server_response);
}
});
}
Ok....when tracing the issue I created an alert as seen below. The alert is producing the expected results.
Here is the PHP script:
<?php
require_once("models/config.php");
// Make the connection:
$dbc = #mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if (isset($_GET['quickJobNumber'])) {
$quickJobNumber = trim($_GET['quickJobNumber']);
$quickJobNumber = mysqli_real_escape_string($dbc, $quickJobNumber);
$query = "SELECT * FROM projects WHERE projectNumber = '" . $quickJobNumber . "'";
$result = mysqli_query($dbc, $query);
if ($result) {
if (mysqli_affected_rows($dbc) != 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo $row['projectName'];
}
} else {
echo 'No Results for :"' . $_GET['quickJobNumber'] . '"';
}
}
} else {
echo 'Parameter Missing';
}
?>
<?php include("models/clean_up.php"); ?>
data: quickJobNumber,
should be
data: { 'quickJobNumber': quickJobNumber },
You'll need to pass the data either as a query string like so
data: "quickJobNumber="+quickJobNumber,
or a map like so
data: data { quickJobNumber: quickJobNumber },
If you want to use the GET request, use $.get
$.get("/get_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_GET['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
If you want to use the POST request, use $.post
$.post("/post_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_POST['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
P.S. or you can use $_REQUEST in php.

Categories