Will this huge javascript array loaded from a database crash my website? - javascript

So on this website I'm making (who knows if i'll actually finish it lol) when someone opens up the new user page, php echos into a javascript script all the usernames from the database to create an array.
<script type="text/javascript">
var allUsers = ['!' <?php
$result = mysql_query("SELECT username FROM users ") or die("error " .mysql_error());
$usersArray = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$usersArray[] = $row['username'] or die("error ". mysql_error());
}
foreach ($usersArray as $name) {
echo ',' . json_encode($name );
}
?> , ];
the point of this is to have a live checker so if you type in a username that already exists, red text shows up next to the username input. But let's say I get 1,000,000 users (completely theoretical). Fortunately, the array only gets created at the beginning of the web page load. But will the function that checks if the username already exists in the huge array and gets called everytime someone changes the text in the username input put too much stress on the script and crash the website? If so, is there a better way to do what I'm describing?
Here's the rest of the code
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
function onUserChange() { //gets called onkeypress, onpaste, and oninput
if(contains(allUsers, str)) {
div.innerHTML = "Username already exists";
div.style.color = "red";
userValid = false;
}
}
</script>

Something along these lines. ( with jQuery and PDO ) - note - code is not tested.
var keyTimer, request;
$('namefield').blur(function(){
onUserChange();
});
$('namefield').keyup(function(){
onUserChange();
});
function onUserChange() { //gets called onkeypress, onblur
keyTimer = setTimeout(function(){
if(request && request.readystate != 4){
//cancel a previous request if a new request is made.
request.abort();
}
request = $.post(
'http://yoursite.com/location/of/username/script.php', //post data to server
{username : $('namefield').val()},
function(data){
if(data == 0 ) { //might be a string here
alert( 'the name is ok to use.' );
}else{
alert( 'someone has this name already.' );
}
}
);
}, 500); //overwrite previous timeout if user hits key within 500 milliseconds
}
Then in the backend
$sql = 'SELECT id FROM users WHERE username = :username';
//insert from post username but we are good programers and are using PDO to prevent sql injection.
//search for the username in the db, count the number of users or rows should be 1 someone has it 0 no one has it assuming its unique.
$stmt = $Pdo->prepare($sql);
$stmt->execute(array(':username', $_POST['username']));
echo $stmt->rowCount();
exit();
etc.....

Do not do it. My counsel is to use ajax to load the php file that will make a query asking only for the user that was typed in the input and retunr only a boolean value(exists=true / notexists=false)
Code example:
HTML(yourFile.html):
<script>
jQuery(document).ready(function(){
//When the value inside the input changes fire this ajax querying the php file:
jQuery("#inputUser").change(function(){
var input = jQuery(this);
jQuery.ajax({
type:"post",
url:"path/to/file.php",
data:input.val(),
success: function(data){
//if php returns true, adds a red error message
if(data == "1"){
input.after('<small style="color:#ff0000;">This username already exists</small>');
//if php returns false, adds a green success message
} else if(data == "0"){
input.after('<small style="color:#00ff00;">You can use this username</small>');
}
}
});
});
});
</script>
<input id="inputUser" type="text" name="username" value="">
PHP(path/to/file.php):
<?php
$username = $_REQUEST['username']; // The value from the input
$res = mysqli_query("SELECT id FROM users WHERE username='".$username."'"); // asking only for the username inserted
$resArr = mysqli_fetch_array($res);
//verify if the result array from mysql query is empty.(if yes, returns false, else, returns true)
if(empty($resArr)){
echo false;
} else{
echo true;
}
?>

As I can see you need to load the PHP code when your website is loading.
First, I recommend you to separate the code. The fact that you can mix Javascript with PHP doesn't mean it is the best practice.
Second, yes, it's not efficient your code since you make Javascript load the result so you can search into it next. What I suggest you is making the search in the server side, not in client side, because as you say, if you have 100 elements maybe the best is to load all the content and execute the function, but if you have 1,000,000 elements maybe the best is to leave the server to compute so it can make the query with SQL.
Third, you can do all this using Ajax, using Javascript or using a framework like jQuery so you don't have to worry about the implementation of Ajax, but you only worry about your main tasks.

Related

php file's code not executing through ajax call

I have a button in my PHP file, and when I click on that button, I want another PHP file to run and save some data in a MySQL table. For that I am using AJAX call as suggested at this link (How to call a PHP function on the click of a button) which is an answer from StackOverflow itself.
Here is my show_schedule file from which I am trying to execute code of another PHP file:
$('.edit').click(function() {
var place_type = $(this).attr("id");
console.log(place_type);
$.ajax({
type: "POST",
url: "foursquare_api_call.php",
data: { place_type: place_type }
}).done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
});
});
here 'edit' is the class of the button and that button's id is being printed in the console correctly.
here is my foursquare_api_call.php file (which should be run when the button is clicked):
<?php
session_start();
include('connection.php');
if(isset($_POST['place_type'])){
$city = $_SESSION['city'];
$s_id = $_SESSION['sid'];
$query = $_POST['place_type'];
echo "<script>console.log('inside if, before url')</script>";
$url = "https://api.foursquare.com/v2/venues/search?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&v=20180323&limit=10&near=$city&query=$query";
$json = file_get_contents($url);
echo "<script>console.log('inside if, after url')</script>";
$obj = json_decode($json,true);
for($i=0;$i<sizeof($obj['response']['venues']);$i++){
$name = $obj['response']['venues'][$i]['name'];
$latitude = $obj['response']['venues'][$i]['location']['lat'];
$longitude = $obj['response']['venues'][$i]['location']['lng'];
$address = $obj['response']['venues'][$i]['location']['address'];
if(isset($address)){
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude, address) VALUES ($name, $latitude, $longitude, $address)");
$result = $statement->execute();
}
else{
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude) VALUES ($name, $latitude, $longitude)");
$result = $statement->execute();
}
}
}
?>
none of the console.log is logged in the console and also the 'temp' table is not updated. Can anyone tell me where I am making mistake? Or is it even possible to execute the code of a PHP file like this?
Your JavaScript is making an HTTP request to the URL that executes you PHP program.
When it gets a response, you do this:
.done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
}
So you:
Alert something
Show a model
At no point do you do anything with data, which is where the response has been put.
Just sending some HTML containing a script element to the browser doesn't cause it to turn that HTML into a DOM and execute all the script elements.
You'd need to do that explicitly.
That said, sending chunks of HTML with embedded JS back through Ajax is messy at best.
This is why most web services return data formatted as JSON and leave it up to the client-side JS to process that data.
to return the contents of php code you can do something like this
you can use any call to this function
function check_foursquare_api_call(place_type) {
var place_type= encodeURIComponent(place_type);
var xhttp;
//last moment to check if the value exists and is of the correct type
if (place_type== "") {
document.getElementById("example_box").innerHTML = "missing or wrong place_type";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("example_box").innerHTML = xhttp.responseText;
$('#userModal_2').modal('show');
}
};
xhttp.open("GET", "foursquare_api_call.php?place_type="+place_type, true);
xhttp.send();
}
this will allow you to send and execute the code of the foursquare_api_call file and return any elements to example_box, you can return the entire modal if you want,
you can use any POST / GET method, monitor the progress, see more here
XMLHttpRequest

Data from jQuery callback is failing to compare

I'm trying to make a "sign in status" thing.
Here is a summary of what is happening.
User fills our field and jQuery request is sent.
Credentials are validated.
Screen displays a welcome message.
So I can get the welcome message sent back to me if the credentials are valid (or error if credentials are false), but here is where the issue resides...
I am having a really difficult time storing anything in PHP as a global variable using my only jQuery (no included file) approach... So my workaround was to take the passed message (Let's just say when credentials are valid, I pass back something like "X" or "1"), and then when the data comes back in the jQuery, I put an if statement in the callback, but it isn't working.
I know that the data being passed is matching what is being compared, and i've tested many different things to pass back, but the comparison is not being done.
Perhaps it isn't possible to do things like if statements in a jQuery callback, but also maybe I'm doing something wrong.
HTML:
<label>Sign In</label>
<br>
<label>Username</label>
<input type="text" id="name1">
<label>Password</label>
<input type="text" id="pass1">
<br>
<button type="submit" id="button2">Sign In</button>
<div id = "xx1">Status: Offline</div>
<div id = "xx2"></div>
jQuery:
$(document).ready(function(){
$("#button2").click(function(){
var name1=$("#name1").val();
var pass1=$("#pass1").val();
var key = "signIn";
$.ajax({
url:'rpc.php',
method:'POST',
data:{
name1:name1,
pass1:pass1,
key:key
},
success:function(data){
if(data === '1')
{
document.getElementById('xx1').innerHTML = "Status: Online";
}
document.getElementById('xx2').innerHTML = data;
//var p = data;
}
});
});
});
(xx2 is updating by the way)
Lastly, relevant bits of my rpc.php:
else if($_POST['key'] === "signIn")
{
$name1=$_POST['name1'];
$pass1 = $_POST['pass1'];
if($name1 !== "" && $pass1 !== "")
{
$sql = "SELECT * FROM whatever";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if($name1 === $row["username"])
{
$UNTrue = true;
if (password_verify($pass1, $row['password'])) {
$PassTrue = true;
}
}
}
} else {
//echo "0 results";
}
if($UNTrue === true && $PassTrue === true)
{
echo "1";
$conn->close();
}
else
{
echo "<p align=center style = 'color:#ba261b'>(Incorrect Username or Password) </p>";
$conn->close();
}
}
else
{
echo "<p align=center style = 'color:#ba261b'>(Please Fill Required Fields) </p>";
$conn->close();
}
}
So data is "1" in this scenario, as displayed to my via xx2, and xx1 remains as "Status: Offline".
I'm wondering if I have to store the data in a JavaScript variable first, and then later somehow referencing it again ASAP.
The other option would be to figure out how to use PHP global variables without file inclusion.
Is it possible even though you're echoing "1", it's getting interpreted as a number? Assuming the data response you get in the success callback is literally just what your PHP script echoes, that's the first thing that jumps out to me, since (1 === "1") is false.

Cannot Redirect when Logging in an Account using javascript and php

Currently, I am developing a website, for my own purposes. I am a beginner at web developing so please understand me if I am not getting this correct. Please Help.
I have a code for javascript when clicking an html element button
for logging in. see code below:
$(document).ready(function(){
$("#login").click(function(){
var username = document.getElementById("username").value;
var pword = document.getElementById("password").value;
validateUser(username,pword);
});
});
function validateUser(user,pass){
var username =user;
var pword =pass;
var datasend = "username="+ username + "&password=" + pword;
$.ajax({
type:'POST',
url:'../bench/php/login.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(msg){
alert("Hello World"); //Trying to pop up
$('#username').val('');
$('#pword').val('');
}
});
}
I successfully triggered the button for the second time I try to click it, and the hello world message will pop out, but it cannot redirect the page if it was successfully logged in using an account in MySQL in WAMP server. Here is the code in PHP below:
<?php
// require("php/config.php");
include("config.php");
session_start();
if($_POST['username'] != '' && $_POST['password'] !='') {
// username and password sent from form
echo $myusername = mysqli_real_escape_string($db,$_POST['username']);
echo $mypassword = mysqli_real_escape_string($db,$_POST['password']);
//$sql = "SELECT user_id FROM user WHERE username = '$myusername' and password = '$mypassword'";
$sql = "SELECT * FROM user WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($db,$sql);
$rows = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_regenerate_id();
$_SESSION['login_user'] = $myusername;
header("Location: index.html");
} else {
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>';
echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("Oops!","Your Account Credentials is Invalid, Please Try Again!","error");';
echo '}, 100);</script>';
}
}
?>
The problem is, the page does not redirect to the index.html even when the second click triggers the HELLO WORLD alert.
I don't know what I am doing wrong.
I don't why this is not working, I see the console, there is no error exist.
can someone help me with this? any help will much be appreciated. thanks and regards.
If you'd like to keep to using the AJAX setup you have at the moment (which is totally fine), what you'll need to do is to beef up the on-success function to read the returned results from your PHP.
A simple example
Instead of
header("Location: index.html");
write
echo "index.html";
exit;
and then add the following to your on-success function:
window.location.href = msg;
That will start to give you a flavour of how the relationship between an AJAX call and your PHP server should look like.
Next steps
Instead of having your AJAX return a string (index.html) have it
return an array of information, perhaps you want to welcome the user
with a personalised message?
You don't need to create a string (var datasend = "username="+ username + "&password=" + pword;) and feed that to your AJAX call, you can send an array.
Make sure your passwords are not stored in plain text on the server.
An ajax request will not follow the Location header of responses to redirect users.
You need to either redirect the user manually using JS in the success callback or change your form submission to use a classic HTML form
The first thing to make sure, PHP Redirect Header doesn't work when sending an Ajax Request.
So the solution to your problem is:
Change this part of your code in PHP file:
header("Location: index.html");
Into:
echo "Success";
exit();
And then in your Ajax Request Success Callback:
success:function(msg){
if (msg == 'Success') {
window.location = "/path/to/redirect";
}
}
Let me know if you have still confusion in this.

AJAX to PHP --> PHP not picking up the pass

I am still a noobie and still learning, but I can't understand why the data from an AJAX call is not being passed successfully into the PHP.
Where have I gone wrong here? I have literally spent hours on hours and I can't understand why the AJAX call hasn't posted this into the PHP. I believe there must be something wrong with either the data attribute from " data: name+email" in the ajax call OR there is something wrong in the PHP side retrieving the data post from AJAX....
I am totally confused...
Thanks for your help (and go easy on me!)
Thanks
<?php
include_once 'db.php';
$fullname = $_POST['name'];
$email = $_POST['email'];
//this is the new stuff we are putting in
mysqli_select_db('table1');
if(isset($_POST['email']))
{
$checkdata = "SELECT signup_email_of_user FROM table1 WHERE signup_email_of_user = '$email'";
$query = mysqli_query($conn, $checkdata);
if(mysqli_num_rows($query) > 0)
{
echo "err";
exit();
}
else {
$sql = "INSERT INTO table1 (signup_name_of_user, signup_email_of_user) VALUES ('$fullname', '$email')";
mysqli_query($conn, $sql);
echo 'ok';
die;
}
}
?>
function submitform1(){
var reg = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var name = $('#signup_name_of_user').val();
var email = $('#signup_email_of_user').val();
if(name.trim() == '' ){
alert('Please enter your name.');
$('#signup_name_of_user').focus();
return false;
}else if(email.trim() == '' ){
alert('Please enter your email.');
$('#signup_email_of_user').focus();
return false;
}else if(email.trim() != '' && !reg.test(email)){
alert('Please enter valid email.');
$('#signup_email_of_user').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'test_signup.php',
data: name+email,
beforeSend: function () {
$('.btn-light').attr("disabled","disabled");
$('.sign-up').css('opacity', '.5');
},
success: function(msg){
if(msg == 'ok'){
$('#signup_name_of_user').val('');
$('#signup_email_of_user').val('');
$('.statusMsg').html('<span style="color:green;">Thanks for contacting us, we\'ll get back to you soon.</p>');
}else{
$('.statusMsg').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
}
});
}
}
This is indeed wrong:
data: name+email
Values are sent as key/value pairs. All you're sending is a value without a key. How would the server-side code know how to retrieve that value without a key? Instead, consider something like this:
data: { 'name': name, 'email': email }
Then server-side you can retrieve the values by their keys:
$_POST['name']
or:
$_POST['email']
Note: The keys don't need to be the same name as the variables which hold the values. They just seem to be reasonably applicable names in this case. You could just as easily do this:
data: { 'first': name, 'another': email }
and retrieve the values with the updated keys:
$_POST['first']
As your form grows in complexity, there are a variety of ways to create an object in JavaScript to define the keys and values. You could serialize an entire <form> in a single line of code, for example. Or perhaps define more complex objects in JSON, serialized, and then de-serialize them server-side. But starting with some simple key/value pairs would work just fine here.
Your data seems to be malformed, try this:
var data = {};
data.name = $('#signup_name_of_user').val();
data.email = $('#signup_email_of_user').val();
and in the ajax: data: data,
According to jQuery documentation data attribute accepts following formats:
Type: PlainObject or String or Array
where the PlainObject is the one we need here:
var data = {'objectmember': 'objectvalue'};

Validating Form With Two Ajax Variables

Please bear with me; trying my best to learn more Ajax. I am trying to Validate whether the Name of Event field in my form already exists in my table, but only if both were created by the same User. For example, if User 1 already has an event called Event1, the validation would check if there was a duplicate event name ONLY under User1.
I have the following snippet in a PHP/HTML form:
<div>Event Name: </div>
<input type="text" name="eventname" id="eventname" onblur="checkeventname()" onkeyup="restrict('eventname')" size="50" maxlength="75" />
<span id="eventnamestatus"></span>
This is my checkeventname function:
function checkeventname(){
var nameofevent = _("eventname").value;
if(nameofevent != ""){
_("eventnamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "eventcreationpage.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("eventnamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+nameofevent);
}
}
And here is the Ajax I put at the top of the page, which I am having trouble with:
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["eventnamecheck"])){
include_once("php_includes/db_conx.php");
$eventname = preg_replace('#[^a-z0-9]#i', '', $_POST['eventname']);
$sql = "SELECT id FROM users WHERE eventname='$eventname' && eventcreator='$eventcreator' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$eventname_check = mysqli_num_rows($query);
if ($eventname_check < 1) {
echo '<strong style="color:#009900;">' . $eventname . ' is not a duplicate name</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $eventname . ' is an event name already under your name</strong>';
exit();
}
}
?>
The webpage itself has the user variable carried over (eventcreationpage.php$eventcreator=User1) I am trying to send over the $eventcreator variable, which would be the User in this case, but I'm not quite sure how to do so.
Set
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
to show that this request will send form data. Next, on your server, you may use $_POST["userid"] to get the userid if you specified it via
ajax.send("userid=" + userid);
To send both userid and eventid, you may use
ajax.send("userid=" + userid + "&eventid=" + eventid);
If you get the userid only from PHP, you could render it into script. That would look like this:
ajax.send("userid=<?php echo $eventcreator; ?>&eventid=" + eventid);
which injects the user's name into the string. Make sure it is properly escaped though, if you allow special characters for user names though.

Categories