Jump to content
Rayj00

Newbee Needs Help With Javascript/PHP/Mysql

Recommended Posts

Ok, I consider myself a dabbler in programming so bear with me.

What I need to do sounds fairly simple, but I cannot figure it out.

I have an html page.  Inside is some basic html and some Javascript. 

The javascript basically generates a random value consisting of numbers and characters in:  var = randomToken.

The length of the random value generated is 11 characters on chrome and 19 on FF? I have no idea why the discrepancy between browsers, but that's not a problem.  I'll look into that later.

What I'm having trouble doing is right now,  I need to take that random value  that was generated by a javascript function and save it out to a database, so on the other end, when someone browses

to another page, I need to retrieve the saved value from the database.   I've looked at many examples but they always include a bunch of stuff I don't need, like tables, multiple stuff in the database, etc.

All I need to do is be able to store a variable and later read it out of a database.  The database just needs a field to store the random value.  Nothing else is needed in the database (for now anyway).

I know I need php, but i am super green at using it. 

I have a mysql database/table built with field:  randomVar

So in a nutshell: 

The starting html page needs to:

  • Generate random value in Javascript. Save it in a variable.  Done.
  • Pass it to php Not Done
  • Update the database randomVar with the random value Not Done
  • Zero out the randomVar field in the database at some point. (when originator hits stop button or closes the page.)  Not Done

Another html page needs to:

  • PHP Read the  randomVar from the database;  if > 0 use it Not Done
  • If  = 0,  echo back some text to the html page....like "Try Later...  Not Done
  • Pass it to javascript Not Done

I am not looking for the exact code unless you want to supply it?  :)

Thanks,

Ray

 

 

 

Share this post


Link to post
Share on other sites

A few things you may or may not understand that are important:

HTTP is stateless.  There is a request/response protocol built into HTTP that you need to understand for clarity on many issues involving web applications.

This is important to you for these reasons:

  1. User A makes HTTP GET request to your page, returns HTML.  Closes connection.
  2. User A's browser now runs your javascript code, generates random var.  
  3. User A (I assume but you did not state this explicitly) makes HTTP GET request to other page.  However, server has no way of knowing that this is still user A.

FIrst to the cut and dried answer:

To pass your javascript variable to the database, you need to use AJAX.  The typical way of doing this would be to have it use the POST method.  Your PHP script that will be the target of the Ajax call, will read the value from the $_POST superglobal, so you can write that first.

Again the problem is that, if this is a multi user application, how do you identify one user from another?  You need some sort of id to tell them apart, and this has to be a candidate key in the database, or you will have no idea in Page 2 etc which row you should be reading back.

In general, PHP sessions solve many problems for this application, and in an unauthenticated scenario, might remove the need entirely for a database.  You could simply save the javascript variable as a session variable and read that in Page 2 etc.

Like all things, the devil is in the details.  Oftentimes people are coy about the nature of the requirement, and don't understand that there are caveats and use cases for many features.  Very few of the people who answer the vast majority of questions here have the patience to exhaustively cover every possible scenario and solution in the hopes that one of them will match the problem.   

 

Share this post


Link to post
Share on other sites
Posted (edited)

OP, What is the point of adding another layer (Javascript) just to get a random value? Why not just generate in Php?

And rather than tell us about your attempted solution to the real problem, how about tell us what the real problem is.

Edited by benanamen

Share this post


Link to post
Share on other sites
17 hours ago, gizmola said:

A few things you may or may not understand that are important:

HTTP is stateless.  There is a request/response protocol built into HTTP that you need to understand for clarity on many issues involving web applications.

This is important to you for these reasons:

  1. User A makes HTTP GET request to your page, returns HTML.  Closes connection.
  2. User A's browser now runs your javascript code, generates random var.  
  3. User A (I assume but you did not state this explicitly) makes HTTP GET request to other page.  However, server has no way of knowing that this is still user A.

FIrst to the cut and dried answer:

To pass your javascript variable to the database, you need to use AJAX.  The typical way of doing this would be to have it use the POST method.  Your PHP script that will be the target of the Ajax call, will read the value from the $_POST superglobal, so you can write that first.

Again the problem is that, if this is a multi user application, how do you identify one user from another?  You need some sort of id to tell them apart, and this has to be a candidate key in the database, or you will have no idea in Page 2 etc which row you should be reading back.

In general, PHP sessions solve many problems for this application, and in an unauthenticated scenario, might remove the need entirely for a database.  You could simply save the javascript variable as a session variable and read that in Page 2 etc.

Like all things, the devil is in the details.  Oftentimes people are coy about the nature of the requirement, and don't understand that there are caveats and use cases for many features.  Very few of the people who answer the vast majority of questions here have the patience to exhaustively cover every possible scenario and solution in the hopes that one of them will match the problem.   

 

Here is the ajax in my index.html file:

var test = randomvalue;
$.ajax({
                              url: "index.php",
                              method: "POST",
                              data: {"test": test }
                      })

 

...and here is the code in the php file:

$stream1 = $_POST[test];

$sql = "UPDATE broadcast SET streamID='$test'";
if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";

Other code connects to the database where I have created the database/table/field = streamID

So,  does this look right, functionally?

Share this post


Link to post
Share on other sites
17 hours ago, benanamen said:

OP, What is the point of adding another layer (Javascript) just to get a random value? Why not just generate in Php?

And rather than tell us about your attempted solution to the real problem, how about tell us what the real problem is.

I already had the javascript code for this so I used it.

Share this post


Link to post
Share on other sites

When you do this update query WHICH record are you updating?

Share this post


Link to post
Share on other sites
Posted (edited)
On 6/22/2019 at 9:13 AM, ginerjm said:

When you do this update query WHICH record are you updating?

I want to update the streamId

Edited by Rayj00

Share this post


Link to post
Share on other sites

But - which RECORD?  Is there only one record in your table?

Share this post


Link to post
Share on other sites

Right now I have only two records....Id, and streamID  I want to update the steamId.

So this is only one issue.  Worse than this is I cannot seem to get a $.ajax to work! No matter 

what I try,  I cannot see the ajax being executed?

 

Share this post


Link to post
Share on other sites
Posted (edited)

You have only 2 RECORDS or 2 FIELDS?  Makes a big difference.  Records are "rows" in your table.  Fields are "columns" within each and every record.  By telling me that you "have only two records .... Id and streamID" you are saying that you have two fields in your record definition.  Which is why I am asking how you are picking the record to be updated since your query statement does not have a "where" clause.

PS - your line referencing the $_POST[test] value works but really REALLY should use quotes on the index value.  Yes - php will eventually default to the proper element but it works better and faster and is more readable when you properly quote the index name as in $_POST['test'].  This is basically true for all array references unless the index value is a variable name.

Edited by ginerjm

Share this post


Link to post
Share on other sites

So you have to bear with me as I am not a programmer or developer.  I'm kinda learning as I go.

But here is the database:

mysql> SELECT * from broadcast;
+----+----------+
| id | streamID |
+----+----------+
|  1 | 23456    |
+----+----------+
1 row in set (0.00 sec)

I need to update the streamID using, I assume,  ajax.

Share this post


Link to post
Share on other sites

Ok - so you have defined your table to have 2 field/columns.  And currently you have only one record.   So when you want to update a specific record you really need to use a key value to identify the exact record you want to update.  If you don't then every record that you may have in that table will be updated with the same streamid value.  Is that what you want, assuming that there will be multiple records in this table at some future time?   I assume that the "id" field is some kind of key value so perhaps you want to add that to your query statement to help it choose the record to be modified.  Of course you have to make sure that this "id" will be unique in the table so the query will properly work 

Share this post


Link to post
Share on other sites

For now I will only have the one record so id is not used.

How do I update the streamId using ajax?

Share this post


Link to post
Share on other sites

Show us the php file in total, if it's not a lot of code.  That or run it as a stand-alone script, providing the input value directly instead of from the POST array and add some output to it to display what is going on.   It's called debugging.

Share this post


Link to post
Share on other sites

Here is my connUpdate.php:

<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "WebRTCApp";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$stream1 = $_POST['streamId'];

$sql = "UPDATE broadcast SET streamID='stream1' WHERE id=1";

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();
?>

And my javascript:

 $.ajax({
                type: 'POST',
                url: 'connUpdate.php',
                data: {streamId : streamId}
                )}.done(function(){
                alert('AJAX was successfull!');
                alert('Data to the db was successfull!);
                }).fail(function(){
                alert('There was some error performing the AJAX call!');
                });

One thing that is really bugging me is I can never see or find any error logging.  And yes, my php.ini file is configured for logging errors with E_ALL.

Share this post


Link to post
Share on other sites
Posted (edited)

This is not what you had referenced before.  So - what is the problem now?  What message do you get back from your ajax call?

 

The default error log name is "error_log" and would be located in the same folder as your php script resides in.

Edited by ginerjm

Share this post


Link to post
Share on other sites

Sorry.  I originally posted what I tried at that time.  What I posted above is what I am trying to get to work right now.

I am not getting any messages back.  And the database is not updated.

 

Share this post


Link to post
Share on other sites

Note that the above mentioned javascript is included, along with my html in a file called index.php.

 

Share this post


Link to post
Share on other sites
Posted (edited)

As I said before - run the script yourself without the ajax call.  Add a line to set your variable instead of looking for a post value.  Add some echos to output things that may be relevant and echo out the results to the screen.  Run it as if ajax was not involved and see what happens.  Maybe make a new copy of it and play with it until you fix it and understand how it works.  Maybe you just want a script that does exactly what you are saying you want to happen.  

BTW - is this script in your root folder and is "index" your default script name for php?  That is not good if so.

Edited by ginerjm

Share this post


Link to post
Share on other sites

So, are you saying the code I posted looks ok?

Like I said.  Everything works as coded...WITHOUT the ajax code.  My only problem is with the ajax....which I have been trouble shooting for a few days now.

Share this post


Link to post
Share on other sites

So you are saying that your js code may be the problem here and NOT the php code?   You have tested the php script previously and only now you can't get it to be triggered by an ajax call?  Then maybe you s/b posting in a JS forum.

Share this post


Link to post
Share on other sites

So, I said everything works WITHOUT the ajax code.   How does that equate to my javascript being the culprit?

Share this post


Link to post
Share on other sites

The php script that you call index.php is the php script and it does not have any ajax code in it.   The calling script (whatever it's name is) is using JQ to make the ajax call and you say you are getting no response back from the "index.php" script.  That tells me that (if it all works as you have said) it must not even be getting called, hence the problem is with the AJAX JQ call.  

Try this - change the ajax call to some dummy php script such as ajaxtest.php.  Create that one-line script to simply echo back a message to prove it got called and then test the whole thing out.  If you don't get a message back then the call didn't go thru.  IF you do get a message back then the problem is with the script that you says "works fine".

Share this post


Link to post
Share on other sites

Sorry...I misunderstood.   The html/javascript and $.ajax are all in the index.php file.  I have a separate file for connecting and updating the database called connUpdate.php

Share this post


Link to post
Share on other sites

Am I mis-reading the ajax call where it says to call index.php?

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.