Validate Log in - php

I have this problem in my phonegap application. It seems like If-else method is not functioning here.
This is my code:
function onSuccess(position){
$("#Login").click(function(evt){
var username = $("#username").val();
var password = $("#password").val();
var d = new Date();
var date = d.getUTCDate();
var hour = d.getUTCHours()+8;
var minutes = d.getUTCMinutes();
var secs = d.getUTCSeconds();
var year = d.getUTCFullYear();
var mon = d.getUTCMonth() + 1;
var day = d.getUTCDay();
var time = year + "-" + mon + "-" + date + " " + hour + ":" + minutes + ":" + secs;
var sendData = {"username": username, "password" : password, "time" : time};
$.ajax({
type: "POST",
url: "http://192.168.254.107/webs/main/ajax/validateLogin.php",
data: sendData,
success: function(data) {
$("#info").html(data);
var ReturnMessage = data; // I also tried data.message here but it gives me "undefined"
if (ReturnMessage != "" && ReturnMessage != "Invalid Login!") {
alert(ReturnMessage);
localStorage.setItem("message", ReturnMessage);
document.location.href = "trackme.html";
} else {
alert(ReturnMessage);
}
}
});
});
}
What ever value of ReturnMessage is, it always do the method of if condition. If I got "Log in Succesful!" message from my php file it redirects to trackme.html, if I got "Invalid Login!", it also redirects to trackme.html which means If-else condition is not functioning. Thank you for your help

Please cross check the data you are getting. There must be some extra space of white space. Try trimming the data: http://en.kioskea.net/faq/1786-javascript-trim-function

HI the return value of ajax request was a OBJECT try to use JSON.stringify(ReturnMessage) and check

Related

PHP 'Insert Into' Query Returning error result on Ajax

I php code that will insert into database but it always returns false even if it is inserting values into the database.
Here is my code: PHP
<?php
require_once 'connection.php';
if (isset($_POST['borrowBook']))
{
newBorrowRequest();
}
function newBorrowRequest()
{
$b_id = $GLOBALS['db']->real_escape_string($_POST['b_id']);
$userID = $GLOBALS['db']->real_escape_string($_POST['userID']);
$dateBorrowed = $GLOBALS['db']->real_escape_string($_POST['dateBorrowed']);
$remarks = $GLOBALS['db']->real_escape_string($_POST['remarks']);
$sql = "INSERT INTO `tbl_requestbook`(`b_id`, `userID`, `dateBorrowed`, `remarks`) VALUES ('$b_id','$userID','$dateBorrowed','$remarks')";
if($GLOBALS['db']->query($sql))
{
$GLOBALS['db']->close();
header("location:../../admin/Book-Items.php?r=success", true);
}
else
{
header("location:../../admin/Book-Items.php?r=failed", true);
}
}
>?
And here is my Ajax Code:
<script>
$("#borrowBook").click(function(event) {
var bookID = $("#bookBorrow").val();
var userID = $("#borrowBook").val();
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
$.ajax({
url: '../assets/php/functions-book.php',
type: 'POST',
data: {borrowBook: 'true', b_id: bookID, userID: userID, dateBorrowed: output, remarks: $("#remarks").val() },
success: function(result) {
window.location.reload();
},
error: function(result) {
//window.location.reload();
console.log(result);
}
});
});
</script
There is something wrong with the php query, it will not iterate with the condition thus, it will call the ajax error function.
[EDITED]
I solved this by changing 'header("location:../../admin/Book-Item.php?r=success");' to 'header("location:../../admin/Book-Items.php?r=success");'. It was a wrong call.
My problem now is, after success the header remains. It can't be replace by the new header that I want to change. I already changed the php code to the latest.

Unable to send api key (authorisation token) in GET (JQUERY AJAX)

Using AJAX I am trying to initiate a GET request to a rest API. I am passing access token in the header. The whole setup is working very fine in the localhost (Xampp).
PHP code used in API is working fine as I have checked it with postman.
Then I tried it on a web host (000webhost.com) and I am getting 400 error. On further investigation I found that the api is returning "API Key is missing"
GET https://alientechno.000webhostapp.com/step_muzic/v1/get_owner_main_page?_=1519553873190 400 ()
<script>
var status = checkLoginStatus();
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (2*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
$(document).ready(function() {
//var api = getCookie("api_key");
//alert(api);
//if(status==true)
var api = getCookie("api_key");
$.ajax({
type:'GET',
url :'https://alientechno.000webhostapp.com/v1/get_owner_main_page',
result: "{}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
headers: {"Authorization": api},
success: function(result) {
var output="";
var output_school="";
for (var i in result.MF)
{
output+="<tr><td>" + result.MF[i].id + "</td><td>" + result.MF[i].name + "</td><td>" + result.MF[i].net_royalty +"</td><td>"+ result.MF[i].royalty_to_owner +"</td></tr>";
}
output+="<tr><td style='background-color:#aabb05;text-color:white;box-shadow:2px 2px;'>TOTAL</td><td></td><td style='background-color:#aabb05;color:white;'>"+result.total_mf_royalty+"</td><td style='background-color:#aabb05;color:white;'>"+result.total_mf_royalty_to_owner+"</td></tr>";
for(var i in result.Schools){
output_school += "<tr><td>" + result.Schools[i].id + "</td><td>" + result.Schools[i].name + "</td><td>" + result.Schools[i].credit+"</td><td>"+ result.Schools[i].debit+"</td><td>"+result.Schools[i].net_income+"</td><td>"+result.Schools[i].royalty_to_owner+"</td><td>"+result.Schools[i].royalty_other+"</td></tr>";
}
output_school+="<tr><td style='background-color:#aabb05;text-color:white;box-shadow:2px 2px;'>TOTAL</td><td></td><td style='background-color:#aabb05;color:white;'>"+result.total_school_credit+"</td><td style=''></td><td style=''></td><td style='background-color:#aabb05;color:white;'>"+result.total_school_royalty_to_owner+"</td><td style='background-color:#aabb05;color:white;'>"+result.total_school_royalty_other+"</td></tr>";
$('#mfTable').append(output);
$('#schoolTable').append(output_school);
},
error:function(exception){alert('Exeption:'+exception);}
//var tokenString = ;
});
});

jQuery AJAX not working on Firefox

I have a function and an AJAX call. After clicking it gets the function and function works fine, on alert it shows the data, but after that it does not send the data to PHP. Any ideas why this happens on Firefox? It works well in IE and Chrome.
function siparisolustur() {
var toplamsiparis = $('.urunrow').length;
var i = null;
var siparisid = $("#siparis_id").text();
var name = $("#siparisad").val();
var surname = $("#siparissoyad").val();
var tel = $("#siparistel").val();
var adres = $("#sepetadres").val();
var semt = $("#sepetilce").val();
var sehir = $("#sepetsehir").val();
var notlar = $("#siparisnotu").val();
var odeme = $('input[name="odemeyontemi"]:checked').attr("id");
bilgiDataString = '&siparisid=' + siparisid + '&name=' + name + '&surname=' + surname + '&tel=' + tel + '&adres=' + adres + '&semt=' + semt + '&sehir=' + sehir + '&notlar=' + notlar + '&odeme=' + odeme;
alert(bilgiDataString);
$.ajax({
type: "POST",
url: "https://www.xxxxx.com/procc/xxxxxxxxxx.php",
data: bilgiDataString,
cache: false,
success: function (html) {
}
});
$("#payForm").submit(function (e) {
var siparisdurdur = 0;
var ad = $("#siparisad").val();
var soyad = $("#siparissoyad").val();
var tel = $("#siparistel").val();
var adres = $("#sepetadres").val();
var ilce = $("#sepetilce").val();
var sehir = $("#sepetsehir").val();
var sepeturunadetget = parseInt($("#sepeturunsayisi").text());
if (ad == "" || soyad == "" || tel == "" || adres == "" || ilce == "" || sehir == "" || sepeturunadetget < 1) {
siparisdurdur = 1;
}
if (ad == "") {
e.preventDefault();
$("#siparisad").css("border- color", "#cd2828")
} else {
$("#siparisad").css("border-color", "#d1d2e6");
}
if (soyad == "") {
e.preventDefault();
$("#siparissoyad").css("border-color", "#cd2828")
} else {
$("#siparissoyad").css("border-color", "#d1d2e6");
}
if (tel == "") {
e.preventDefault();
$("#siparistel").css("border-color", "#cd2828")
} else {
$("#siparistel").css("border-color", "#d1d2e6");
}
if (adres == "") {
e.preventDefault();
$("#sepetadres").css("border-color", "#cd2828")
} else {
$("#sepetadres").css("border-color", "#d1d2e6");
}
if (ilce == "") {
e.preventDefault();
$("#sepetilce").css("border-color", "#cd2828")
} else {
$("#sepetilce").css("border-color", "#d1d2e6")
}
if (sehir == "") {
e.preventDefault();
$("#sepetsehir").css("border-color", "#cd2828")
} else {
$("#sepetsehir").css("border-color", "#d1d2e6")
}
if (blocksubmit == 1) {
e.preventDefault();
$("#personalinfosubmit").fadeOut("fast").fadeIn("fast").fadeOut("fast").fadeIn("fast");
}
if (sepeturunadetget < 1) {
e.preventDefault();
$("#shoppingcost").css("color", "#cd2828");
$("#shoppingcost").fadeOut("fast").fadeIn("fast").fadeOut("fast").fadeIn("fast");
}
if (blocksubmit == 0 && siparisdurdur == 0) {
siparisolustur();
}
});
I solved the problem.. Submit goes to other page before ajax is done proessing the data.. I delayed the redirect for like half second and it worked.. Its about speed of FF
I see that you've posted a solution already:
Submit goes to other page before ajax is done proessing the data.. I delayed the redirect for like half second and it worked.
Seriously, you should not be relying on a solution like this.
Timing issues like this are known as a "race condition", ie where two events are effectively in a race to see which one will finish first; you're expecting one to always win, and you get a bug if they finish in the wrong order.
It's a very well defined category of bug (even if Ajax is fairly new, situations like this have existed since the begining of computer science), and the solution is not to slow down one of the events in the hope that you'll force it to always lose. That is always the wrong solution.
The correct solution is usually to trigger the second event only after the first one has finished. In your case, this would mean firing the submit event from inside the ajax success method.

passing parameters to a php from javascript

I've done this before but for some reason the parameters are being passed oddly.
I have a javascript function that I've used to pass parameters, I've ran some tests and in the function the variables are correct.
These are just a few snippets of the js that relate to the issue:
var tdes = document.getElementById("taskDescription1").value;
var tnam = document.getElementById("taskName1").value;
var shif = document.getElementById("shift1").value;
var ttyp = document.getElementById("taskType1").value;
var date = document.getElementById("datepicker").value;
var ooc = document.getElementById("ooc1").value;
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
xmlhttp.open("GET","subTask.php?q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true);
I ran a web console and this is what is actually getting passed...
http://***************/****/********/subTask.php?taskName1=test+taskname+works&taskDescription1=test+des&shift1=All&ooc1=Open&taskType1=normal&datepicker=06%2F28%2F2013
I'm not sure what's going on in between the xmlhttp.open and the GET method in php. None of these variables are getting passed.
Why not use jQuery - very straightforward format (I prefer POST...):
$(document).ready(function() {
var tdes = $("#taskDescription1").val();
var tnam = $("#taskName1").val();
var shif = $("#shift1").val();
var ttyp = $("#taskType1").val();
var date = $("#datepicker").val();
var ooc = $("#ooc1").val();
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
$.ajax({
type: "POST",
url: "subTask.php",
data: "q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true),
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END document.ready()
Notice how easy the success callback function is to write... anything returned by subTask.php will be available within that function, as seen by the alert() example.
Just remember to include the jQuery library in the <head> tags:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
Also, add this line to the top of your subTask.php file, to see what is happening:
<?php
$q = $_POST["q"];
$w = $_POST["w"];
die("Value of Q is: " .$q. " and value of W is: " .$w);
The values of q= and w= will be returned to you in an alert box so that (at least) you can see what values they contained when received by subTask.php
Following script should help:
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
var ajax = ajaxObj("POST", "subTask.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
console.log( ajax.responseText )
}
}
ajax.send("u="+tdes+"&e="+tnam+ ...... pass all the other 'n' data );

Very basic PHP array issue

I am creating a form where the user selects check boxes of "services" that they might be interested in, then the form gets emailed to me. The problem is weather a box is checked or not, all of the results are being filled in. How do I properly do this?
There are about 25, but here is just a few:
$services = array();
if($_POST['master_planning']) {$services[] = "Master planning";}
if($_POST['snow_plowing']) {$services[] = "Snow plowing";}
if($_POST['fine_gardening']) {$services[] = "Fine Gardening";}
if($_POST['deer_protection']) {$services[] = "Deer Protection";}
$interested = implode(", ", $services);
I know it is a very basic thing, but I can't seem to solve it on my own
HTML is like:
<li><label for="planting"><input type="checkbox" name="planting" id="planting" value="x" /> Planting</label></li>
Ok, I figured (I think) out why all the values are returning true, even if the checkboxes arent clicked, now how do I solve it....
I guess I should of mentioned that this is page 2 of the form (process.php), the actual form is index.php, and I am using an ajax script to pass values.
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var name = $('input[name=name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var master_plan = $('input[name=master_plan]');
var front_foundation = $('input[name=front_foundation]');
var backyard_plan = $('input[name=backyard_plan]');
var specialty_garden = $('input[name=specialty_garden]');
var lawn_cutting = $('input[name=lawn_cutting]');
var lawn_plant_health_care = $('input[name=lawn_plant_health_care]');
var organic_property_care = $('input[name=organic_property_care]');
var seasonal_clean_ups = $('input[name=seasonal_clean_ups]');
var pruning = $('input[name=pruning]');
var fine_gardening = $('input[name=fine_gardening]');
var deer_protection = $('input[name=deer_protection]');
var snow_plowing = $('input[name=snow_plowing]');
var planting = $('input[name=planting]');
var walk = $('input[name=walk]');
var terrace = $('input[name=terrace]');
var wall = $('input[name=wall]');
var outdoor_kitchen = $('input[name=outdoor_kitchen]');
var fireplace = $('input[name=fireplace]');
var driveway = $('input[name=driveway]');
var fencing = $('input[name=fencing]');
var pergola = $('input[name=pergola]');
var swimming_pool = $('input[name=swimming_pool]');
var irrigation = $('input[name=irrigation]');
var lighting = $('input[name=lighting]');
var grading_drainage = $('input[name=grading_drainage]');
var newsletter = $('input[name=newsletter]');
var comments = $('textarea[name=comments]');
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
var data =
'name=' + name.val() +
'&phone=' + phone.val() +
'&email=' + email.val() +
'&master_plan=' + master_plan.val()+
'&front_foundation=' + front_foundation.val()+
'&backyard_plan=' + backyard_plan.val()+
'&specialty_garden=' + specialty_garden.val()+
'&lawn_cutting=' + lawn_cutting.val()+
'&lawn_plant_health_care=' + lawn_plant_health_care.val()+
'&organic_property_care=' + organic_property_care.val()+
'&seasional_clean_ups=' + seasional_clean_ups.val()+
'&pruning=' + pruning.val()+
'&fine_gardening=' + fine_gardening.val()+
'&deer_protection=' + deer_protection.val()+
'&snow_plowing=' + snow_plowing.val()+
'&planting=' + planting.val()+
'&walk=' + walk.val()+
'&terrace=' + terrace.val()+
'&wall=' + wall.val()+
'&outdoor_kitchen=' + outdoor_kitchen.val()+
'&fireplace=' + fireplace.val()+
'&driveway=' + driveway.val()+
'&fencing=' + fencing.val()+
'&pergola=' + pergola.val()+
'&swimming_pool=' + swimming_pool.val()+
'&irrigation=' + irrigation.val()+
'&lighting=' + lighting.val()+
'&grading_drainage=' + grading_drainage.val()+
'&newsletter=' + newsletter.val() +
'&comments=' + encodeURIComponent(comments.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
if (html==1) {
$('.form').fadeOut('slow');
$('.done').fadeIn('slow');
} else alert('Sorry, unexpected error. Please try again later.');
}
});
return false;
});
});
</script>
Could this be why every result is displaying?
The check you have is incorrect. Lets assume you have this HTML code for the checkbox inside your form:
<input type="checkbox" name="master_planning" value="yes" />
Then on your PHP you want do the check like this:
if(isset($_POST['master_planning']) && $_POST['master_planning'] == 'yes'){
array_push($services, "Master planning"];
}
The function array_push adds the given element or elements at the end of the array, so that would be an easy way to "dynamically" populates an array.

Categories