Javascript missing ) after argument list - php

I have this function, and I call it from PHP with onClick="login_f('.$return.')"
But in Firefox it gives me an error "javascript missing ) after argument list"
Any help?
function login_f(return_v){
email = document.login.email.value;
email2 = document.login.email2.value;
if(email == "" || email2 == ""){
if(readCookie("lang") == "it_IT")
msg('<span style="color:#D90909">Compila tutti i campi!</span>');
else
msg('<span style="color:#D90909">Fill in all fields!</span>');
}
else if(email != email2){
if(readCookie("lang") == "it_IT")
msg('<span style="color:#D90909">Le email non coincidono!</span>');
else
msg('<span style="color:#D90909">The emails do not match!</span>');
}
else{
var date = new Date();
date.setTime(date.getTime() + (365*24*60*60*1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "email=" + email + expires + "; path=/sbm/";
if(return_v == "" || return_v == null)
window.location.href = "http://www.xriuk.com/sbm/";
else
window.location.href = return_v;
}
}

It looks like (based on where it is used) $return (and therefore return_v) is a string.
If that's the case, then it needs quotes around it.
I highly recommend using json_encode to embed ANY kind of variable, not least because it greatly helps prevent XSS.
So your PHP becomes:
echo '...... onClick="login_f('.htmlspecialchars(json_encode($return),ENT_QUOTES)."');"....';

you could do like:
echo '<a ... onClick="login_f(\''.$return.'\')">....</a>';

Related

Problem creating a login authentication using ajax

I'm trying to create an AJAX script that calls a PHP script to check the entered username and password. The PHP script simply returns "true" if the entered details are correct and false if otherwise.
At the end of the AJAX script, I've placed a simple if else condition for true/false returns. Every time the PHP script returns true, the AJAX scripts jumps to else part overlooking the if.
I know there might be some stupid mistake or it is probably a ludicrous question but I'm stuck on it since many days. Stack is the last resort!
Here's my AJAX SCRIPT
function authenticate()
{
//XMLHttpRequest Object
var xhttp = new XMLHttpRequest();
var email = document.getElementById('email').value;
var pass = document.getElementById('pass').value;
var url = "php/user_authentication.php";
var url2 = "php/user_authentication.php?email=" + email + "&pass=" + pass;
var result = "";
xhttp.open("GET", url2, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
xhttp.onreadystatechange = function f()
//f() would be called everytime the onreadystatechange property changes the value
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
alert(this.responseText);
result = this.responseText;
if (result == "true")
//!! -> NOT ENTERING THIS PART EVEN WHEN result="true" !!
{
alert("Inside true");
document.getElementById('email_pass').innerHTML = 'login successful';
} else {
document.getElementById('email_pass').innerHTML = 'login failed';
alert("2 " + xhttp.responseText);
}
}
}
}
Here's the PHP script [user_authentication.php]
<?php
//User Authentication
//1.Including the database_connection.php
include "database_connection.php";
//2.1.Fetching the user id and password from the form
$email = $_GET['email'];
$pass = $_GET['pass'];
//2.2.Defining th select query
$qry = 'select * from user_auth where Email="'.$email.'" and Password = "'.$pass.'"';
//3.Executing the query and storing it to result
$result = mysqli_query($connection,$qry);
//authenticating
if(mysqli_num_rows($result)>0)
{
echo "true";
}
else
{
echo "false";
}
?>
Obligatory comment about prepared statements in php and sql PHP Manual.
But I would try to cast the comparison
if (result == "true")
to boolean like so
if (Boolean(result) === true)
I admit, my knowledge of ajax and JS is limited but in such cases Ive learned to not trust JS automatic type casting. Note also that I would definately use 3x= if we are casting result to a boolean.
The issue was,
I was getting some extra spaces along with my responseText that made the following condition false every time I got "true" in my responseText.
if (result == "true")
//Turns false because result.length = 11 (extra empty spaces due to some unknown reasons)
The solution was as follows :
Changing the return value in my PHP to 't' and 'f'
Using the slice method to slice the first variable of responseText to eliminate all the white-spaces in the string and then making further comparison
xhttp.onreadystatechange = function f()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
result = this.responseText;
var temp = result.slice(0,1);
//This will only select the first char in the result string
if (temp == "t")
document.getElementById('email_pass').innerHTML = 'login successful';
else
document.getElementById('email_pass').innerHTML = 'login failed';
}
}
$result not getting "true" make sure or double check below:
Html element IDs are (email, pass)
Database connection work properly,
$qry: select query related fields have matched with table columns
$result will get true only if requested email and password exits in database user_auth table
I think it may help...good luck

Uncaught SyntaxError:

The code should make a pop up window, asking for confirmation "press ok to confirm the action for user" but it doesn't. i'm all out of ideas.
function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
if(conf != true){
return false;
}
$(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "php_parsers/friend_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "friend_request_sent"){
$(elem).innerHTML = 'OK Friend Request Sent';
} else if(ajax.responseText == "unfriend_ok"){
$(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $u; ?>\',\'friendBtn\')">Request As Friend</button>';
} else {
alert(ajax.responseText);
$(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type="+type+"&user="+user);
}
</script>
PHP code:
<?php
$friend_button = '<button disabled>Request As Friend</button>';
$block_button = '<button disabled>Block User</button>';
// LOGIC FOR FRIEND BUTTON
if($isFriend == true){
$friend_button = '<button onclick="friendToggle(\'unfriend\',\''.$u.'\',\'friendBtn\')">Unfriend</button>';
}
else if($user_ok == true && $u != $log_username &&
$ownerBlockViewer == false){
$friend_button = '<button onclick="friendToggle(\'friend\',\''.$u.'\',\'friendBtn\')">Request As Friend</button>';
}
// LOGIC FOR BLOCK BUTTON
if($viewerBlockOwner == true){
$block_button = '<button onclick="blockToggle(\'unblock\',\''.$u.'\',\'blockBtn\')">Unblock User</button>';
} else if($user_ok == true && $u != $log_username){
$block_button = '<button onclick="blockToggle(\'block\',\''.$u.'\',\'blockBtn\')">Block User</button>';
}
?>
Opening up the console i see "Uncaught SyntaxError: Invalid or unexpected token"
The console issue is with lines 2 & 3 of your JavaScript code;
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
You have a multi-line String which the console is not interpreting as one String value. In order to resolve, ECMAScript 6 (ES6) introduced template literals which can be utilized like below to handle multi-line Strings;
var conf = confirm(`Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.`);
(i.e. use back-ticks rather than double quotes to start & end the multi-line String)
Or, if ES6 isn't supported you can use good old String concatenation like below;
var conf = confirm("Press OK to confirm the '"+type+"' action for user" +
"<?php echo $u; ?>.");

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.

sending php array to javascript function onclick

Little problem about sending PHP array to javascript function, i did homework looked everywhere and i know its not reliable to do this, but at this moment i do not know any other way , so try to just advice me how to finish it anyway.
I got php code executing first , idea is on page load i get some data from MySQL , i filled php array with IDs from that select statement.
<?php
include('config.php');
$TicketExist = "select BetSlipID,probatip1.betslips.MatchID as GameID,
TipID,tim1.Name AS HomeTeam ,tim2.Name AS AwayTeam, UserID
from probatip1.betslips
inner join probatip1.matches matches on probatip1.betslips.MatchID = matches.MatchID
inner join probatip1.teams tim1 on matches.HomeTeamID = tim1.TeamID
inner join probatip1.teams tim2 on matches.AwayTeamID = tim2.TeamID
where UserID = 1";
$TicketResult = mysql_query($TicketExist);
$TicketNum = mysql_numrows($TicketResult);
mysql_close();
if($TicketNum != 0)
{
$s=0;
while($s < $TicketNum)
{
$GameID = mysql_result($TicketResult,$s,"GameID");
$TipID = mysql_result($TicketResult,$s,"TipID");
$ArrayIDs[$s] = $GameID;
echo "<script>window.onload=GetInfo($GameID,$TipID); </script>";
$s++;
}
}
?>
So i got it everything i want filled and wrote on my page , idea now is on user click , to call javascript to take this '$ArrayIDs' and execute code from script
Here is code im calling script
<ul>
<li
id="ConfirmButton" name="Insert" method="post"
onclick="GetAllIDs(<?php $ArrayIDs ?>)"><a>POTVRDI</a></li>
</ul>
And my script code
function GetAllIDs(Ticket) {
$("td.ID").each(function () {
var MatchID = $(this).attr('id');
var lab = "Label";
var Label = lab + MatchID;
var Final = document.getElementById(Label);
var TipID;
if (Final.innerHTML == '1') {
TipID = 1;
}
else if (Final.innerHTML == 'X') {
TipID = 2;
}
else if (Final.innerHTML == '2') {
TipID = 3;
}
else {
return;
}
var request_type;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
request_type = new XMLHttpRequest();
}
var http = request_type;
var AlreadyPlayed = false;
if (Ticket != null) {
var TicketExists = Ticket;
for (var i = 0; i < TicketExists.length; i++) {
if (TicketExists[i] == MatchID) {
AlreadyPlayed = true;
break;
}
}
}
if (http != null) {
if (AlreadyPlayed == true) {
http.open('get', 'update.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
else {
http.open('get', 'insert.php?MatchID=' + MatchID +
'&TipID=' + TipID + '&UserID=' + 1, true);
}
http.send(null);
}
});
if (Ticket == null) {
alert('Tiket je napravljen');
}
else {
alert('Tiket je promenjen');
}
}
With this posted code when i am debugging code with firebug in mozzila i get that my 'Ticket' parameter that suppose to be '$ArrayIDs' is undefined.
Reason why i want to make array and send it to javascript onclick event is to check if user already placed a bet on some game , if he did i want to send all data for update and if he did not yet placed bet on some game to send data for insert in database.
So i need array and before anything just to check MatchID with all IDs in my array, so i know what to do.
Thanks all in advance for helping out
Your script could do with a bit of cleanup, but in essence you need to change
onclick="GetAllIDs(<?php $ArrayIDs ?>)">
to
onclick="GetAllIDs(<?php echo json_encode($ArrayIDs) ?>)">
I'd also reccomend not outputting
"<script>window.onload=GetInfo($GameID,$TipID); </script>";
for each row in mysql, instead create a single array of the values and create one script after the loop. Using mysql_fetch_row instead of mysql_numrows and mysql_result is probably neater.
while ($row = mysql_fetch_row($result)) {
//...do things here...
}
You need to output the array as valid JavaScript, use json_encode
GetAllIDs(<?php echo json_encode($ArrayIDs); ?>)

How to fix a not defined javascript error?

I am fairly new to Javascript and what I am trying to do is have a cookie set as soon as I click on a link. When I return back to the previous page from the link, I want the page to auto refresh and notify the user by color to show what link they just clicked. I used this example to guide me http://webdesign.about.com/od/cookies/a/aa083198.htm. But I am still not getting it.
The code below is what I have. The problem is that as soon as I click on the link firebug brings up the error "getLink not defined". Also through web developer on Firefox, it seems that my cookie is not actually being set even though I am calling it from the Html.I am also showing gave the most important part in my Html that calls the function.
The videoId i have in setCookie is a php variable that is defined somewhere else in my code. I would really appreciate it if someone can point me in the right direction. Thanks!
<head>
<script language="text/javascript">
var cookie_name = "watched";
function setCookie(cookie_name,cookie_value)
{
if (document.cookie!="") {
index = document.cookie.indexOf(cookie_name);
} else {
index = -1;
}
if (index == -1) {
var finish = 7200;
var cookie_value = videoId + "; expires=" + finish;
document.cookie=cookie_name + "=" + cookie_value;
}
}
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks;
}
else{
//alert("No color");
}
}
return colorLinks;
}
function colorLinks()
{
$('#' + videoId).css('background-color: pink');
}
</script>
</head>
<body onLoad=window.refresh>
<div id="page">
echo '<a href="' . $link . '" onclick="setCookie(); return true;">' . $this->Links
This does not make sense:
function getLink(cookie_value) {
if (document.cookie) {
index = document.cookie.indexOf(cookie_value);
if (index != -1) {
colorLinks; // you mean colorLinks(); ???
}
else {
//alert("No color");
}
}
// why return a function that sets color instead of just calling it?
return colorLinks;
}
and there is luckily nothing called window.refresh (unless you have created it yourself) or you would loop forever
In the code i don't see where videoId is given a value
You don't call the function setCookie(cookie_name,cookie_value); to set the cookie.
Please read about cookies: http://www.quirksmode.org/js/cookies.html
<script type = "text/javascript">
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
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,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
</script>

Categories