I have a question I have been struggling with for a while, I think I might be taking the wrong approach or not understanding the basics. But I am looking for a solution, so if I have it the "wrong way" please let me know.

I am building a login/registration system. The key to the "app" is that you don't input your own username in a textbox. Instead, I have built a jQuery application which helps you choose a username (the reason being that the target market is children).

At the jQuery stage, the app has three stored string variables = wordOne, wordTwo and wordThree.

I have already built a registration functionality (PHP & SQL) but at present it uses a standard text input to grab the username. So I wanted to change this up by passing the wordOne, wordTwo and wordThree to the username div, then use PHP to grab the value and use that to create the username entry (which is posted through a form).

One of the issues I am having is: how do I pass these three JavaScript variables from JS to PHP?

My research has given me the understanding that this must be done using an AJAX request as there needs to be communication between serverside and clientside. This works great for me because I am needing to use AJAX to reload the next section of the site.

So... my major question is how do I instruct a PHP function to process on the success of the AJAX, or what else do I link it to so that it runs when the page loads?

Here is what I am doing at present. In the AJAX call, I have added the variables mentioned above and reassigned their values to the PHP variables one, two and three

function saveUsername(wordOne, wordTwo, wordThree){

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("login-register-wrapper").innerHTML=xmlhttp.responseText;
    }
  }

As a closeup, here is the line that I (hope) assigns the JS variables to new PHP variables, or at least gives me a way to grab them in PHP.

    `xmlhttp.open("GET","register-form.php?one=wordOne&two=wordTwo&three=wordThree",true);`

This all works fine. But then I run into an issue. I want to do the following things to these variables. 1) Uppercase the first letter. 2) Concatenate them together into one string. 3) Assign this string to the variable $username

So I wrote this:

$_GET['one'], $_GET['two'] and $_GET['three'];

    // Capitalise first letter
    $one = ucfirst($one); 
    $two = ucfirst($two); 
    $three = ucfirst($three); 

    $username = $one . $two . $three;

I haven't been able to full test the code but you get the idea. ucfirst for the caps, then concatenate and store in the variable.

The thing I don't understand is where does this script go? where do I call this function? I know if this was JavaScript, I'd put it in here:

    if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {

        }

But I just can't get my head around where I call my little capital and concatenate script so that it runs as the AJAX page is loaded in.

If you look through the site, which will only take a few seconds, you will see what I am attempting to do. Am I going about this completely the wrong way? I've tried everything, asked on a bunch of forums and no one has the answer, or seems to be able to help me out. What would you do to:

1). Pass JS variables to PHP
2). Run an AJAX script to load a new file into the page asynchronously
3). Run a script which capitalises and concatenates
4). Store that in a variable.
5). Echo that variable on the newly loaded in page.

Dani AI

Generated

Short answer: PHP runs on the server when the AJAX request reaches it — you don't "call" a PHP function from the client after success. The correct flow is: send the actual JS values to a server endpoint, let that endpoint (PHP) capitalise/concatenate/validate and return the result, then your AJAX success callback updates the page. Good pointers from and about using callbacks are useful for the client side; they don't change that the processing must happen inside the server endpoint your request hits.

A simple client-side pattern (using modern fetch) — send the three values, then insert the returned username into the DOM:

fetch('register-username.php', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ w1: wordOne, w2: wordTwo, w3: wordThree })
})
.then(r => r.json())
.then(data => {
  document.getElementById('login-register-wrapper').innerHTML = data.username || data.error;
})
.catch(err => console.error(err));

Server-side: accept the POSTed data, trim/normalise each word, capitalise the first character safely (use multibyte functions if needed), join them and return JSON. Example idea (conceptual):

<?php
header('Content-Type: application/json; charset=utf-8');
$in = json_decode(file_get_contents('php://input'), true) ?: [];
$words = array_map('trim', [$in['w1'] ?? '', $in['w2'] ?? '', $in['w3'] ?? '']);
// use mb_ functions to capitalise first character for UTF-8 safety
// build username and echo json_encode(['username' => $username]);

Troubleshooting / gotchas:

  • Make sure you send the variable values, not the literal names (i.e. don't send the string "wordOne").
  • Prefer POST for this (keeps data out of the URL and fits mutation semantics).
  • Check the browser Network tab: request payload, response content-type, and raw response. PHP warnings/HTML before JSON will break parsing.
  • Use absolute/relative paths correctly from the page making the request.
  • Server-side must perform validation, uniqueness checks and escaping before committing to the database.

This separates responsibilities cleanly: client sends values and updates the UI; server performs the username construction and returns the ready-to-use result.

Recommended Answers

All 3 Replies

Just thought I'd add a few solutions I tried.

1). Just "require" the file and run the function at the top of the newly loaded in page:

Code

<?php
require "setUsername.php"
setUsername();
?> 

I put this at the top of the new page, with setUsername.php having the capitalisation stuff in it.

Why it didn't work

Weirdly, once this is loaded, the previously working AJAX request fails.

Instead of forwarding the section of the page to register-form.php as in the AJAX request, it tries to go to the full URL like a string.

Instead of trying to find register-form.php
It tries to find register-form.php?one=wordOne&two=wordTwo&three=wordThree

This page doesn't exist, and it won't (because it contains variables). So the AJAX load fails.

2) Run the function in the AJAX request:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("login-register-wrapper").innerHTML=xmlhttp.responseText;
    setUsername()
    }
  }

Why it didn't work

This one just makes the page go boom. I expect it can't find setUsername()

If you use a library like jQuery, you can easily have the results of one ajax call feed into another function for further processing.

http://api.jquery.com/jquery.ajax/ and scroll down to the entry for success.

Using a library like jQuery frees you up to concentrate on your code and leave the ajax and lots, lots more to the library. You can load jQuery from a CDN (jquery.com or google) so that it doesn't have to cost much in load time.

It is well worth it to have so much easy to use power at your fingertips.

Member Avatar for Member #120589

This sounds pretty convoluted. You say you're using jQuery, but you've used vanilla js for the ajax bit. Nothing wrong with that, but why not lever jQuery's 'easy' ajax handling into your script? You're going to drag words onto an input box?

There's no reason at all why this shouldn't be possible. So I'm assuming the kid needs a password too? Or is this username a throwaway one-time use?

Anyway. For anything that manipulate data, you should use POST. GET is used for retrieving data as a rule. An exception perhaps is a login form, where although you're only actually retrieving data, it's always sent as POST - you don't want your password showing up in the url!

OK waffling I know.

If you're using jQuery, here's how I set up my pages...(sorry not meant to be patronizing)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- put your meta stuff, title and links to css files here -->    
</head>
<body>
<!-- page content here -->

<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    //all the rest of my javascript
</script>
</body>
</html>

It's unclear how you're getting the variables wordOne, wordtwo and wordThree, that that doesn't seem to be an issue for you.

I like to keep my ajax routines separate to form events, but that's just my personal preference...

$('#submit').click(function(e)
{
    e.preventDefault();
    //maybe do other things before the submission?
    //get variables and send to sendUserName function
    sendUserName(wordOne, wordTwo, wordThree);
});

function sendUserName(w1, w2, w3)
{
    $.post( "register_handler.php", { word1: w1, word2: w2, word3: w3 })
      .done(function( data ) {
        //uncomment one of the below to see what's being returned
        //alert(JSON.stringify(data));
        //console.log(JSON.stringify(data));
        //place code here to decide what should happen next
    },"json");
}

The register_handler.php file:

$errors = array();
if(isset($_POST['word1'] && $_POST['word2'] && $_POST['word3']))
{
    $w1 = ucase(trim($_POST['word1']));
    $w2 = ucase(trim($_POST['word2']));
    $w3 = ucase(trim($_POST['word3']));
    if($w1 && $w2 && $w3)
    {
        $username = $w1.$w2.$w3;

        //pass any data back as an json encoded array
        //and echo it - this will be picked up by the 'data' js variable
        //in the .done routine
        //you can add loads of other stuff to the array - up to you
        echo json_encode(array('username'=>$username));
    }else{
        echo json_encode(array('error'=>'One or more of the words were empty'));
    }
}else{
    echo json_encode(array('error'=>'One or more of the words were not sent'));
}

That should work, but I've not tried it - off top of my head.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.