0

hi everybody,

i encounter a problem regarding PHP when i am doing my internship.

i have a javascript which looks like this.

<Script Language = "JavaScript">
function sent()
{
var text1, fTxt,dT;
text1 = document.form1.EPTextField.value;
dT = new Date();
fTxt =("You entered" + ": " +  text1 + "   " + ":" + dT);
document.form1.EPText.value = fTxt;
}
</script>

where it will be called by onClick of a button

<input type="button" name="EPButton" id="EPButton" value="Send" onClick = "sent()"/>

However i need to save the fTxt into a database MySQL. my in charge called me to use php.

$con = mysql_connect("localhost","host"); //connect database
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
 mysql_select_db("chat",$con); //select database
 mysql_query("INSERT INTO chat (Name, Date, Content, Time)
    VALUES ('fTxt')"); //insert

    mysql_close($con);

?>

BUT here is the problem, my supervisor says that php doesn't understand what is the javascript value. so i need a platform like AJAX; i saw the ajax tutorial, i totally can't get it into my mind. so is there another way i can get it to work? or perhaps i can change the javascript function into a php function. but i tried googling "how to declare a var as a textbox value in php" and didnt get what VAULT said. I hope i can get some help here.

Edited by mike_2000_17: Fixed formatting

5
Contributors
18
Replies
19
Views
7 Years
Discussion Span
Last Post by umandajayo
0

i am doing a LAN MESSENGER which look like a facebook taskbar. GUI done... send button done... now it's how to throw the result tat is generated by javascript and store it inside MYSQL database using PHP.... any1 can guide me?

0

You can write the php code as a seperate file and use the $_GET method to get the value from the url

<Script Language = "JavaScript">
function sent()
{
var text1, fTxt,dT;
text1 = document.form1.EPTextField.value;
dT = new Date();
fTxt =("You entered" + ": " + text1 + " " + ":" + dT);
document.form1.EPText.value = fTxt;
[B]window.location="update.php?value="+fTxt;[/B]
}
</script>

It will open update.php page with the follwing url

http://localhost/update.php?value=test;

where test is the value of ftxt. you can utilize the value by $value=$_GET;

0

thanks raja for ur reply. so i should create a new file call update.php??? what shld i put inside?

0
$value=$_GET['value'];
echo $value; //Ensure that you received the value by print on the page
$con = mysql_connect("localhost","host"); //connect database
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("chat",$con); //select database
mysql_query("INSERT INTO chat (Name) VALUES ('$value')"); 
mysql_close($con);
?>

Edited by rajarajan07: n/a

0

as i you see your trying to implement a chatting system. Use form submission, instead of onclick events

<?php

if($_POST['btnsubmit']){

$user = $_POST'user'];
$msg = $_POST['msg'];

$con = mysql_connect("localhost","host"); // i hope you can already connect successfully
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

$now = time(); // now

$date = date("Y-m-d",$now);
$time = date("h:i:s",$now);

mysql_select_db("chat",$con);
mysql_query("INSERT INTO chat (Name, Date, Content, Time) VALUES ('".$user."','".$date."','".$msg."','".$time."')"); // i hope you set your date field to data type date, and you set your time field to data type time

mysql_close($con);

}

?>
<form method="post">
User: <input type="text" name="user" /><br />
Message: <textarea name="msg"></textarea><br />
<input type="submit" name="btnsubmit" value="send" />
</form>

but if the scenario really require onclick events then, ill re-design the code, the reason why i abandon your javascript coz im kinda puzzled on what you really tryin to save, like this part

fTxt =("You entered" + ": " + text1 + " " + ":" + dT);

i assume you storing ftxt to string, something like "You entered: hello!:Wed Jun 30 2010 17:18:23 GMT+0800 (Taipei Standard Time)" the Date() in javascript returns a formatted date, unlike PHP date which returns timestamp. and your insert is incorrect

mysql_query("INSERT INTO chat (Name, Date, Content, Time)
VALUES ('fTxt')"); //insert

your inserting ftxt to where? it should be

mysql_query("INSERT INTO chat (Name, Date, Content, Time)
VALUES ('your_name','the_date','your_content','the_time')")// just a sample

Edited by vaultdweller123: n/a

0

Thanks raja and vault for ur kind reply : ) i can feel some warm from this forum : )

Example user enters "Hello! how are u guys doing. : Wed Jun 30 2010 17:18:23 GMT+0800" into the textarea1.. it will appear in textarea2. The text that the user entered, must be save into a database. but i encounter some problem when i am thinking about it. my table 'chat' has 4 table / attributes(Name,Content,Date,Time), how am i going to split a full text string, "You entered: Hello! how are u guys doing. : Wed Jun 30 2010 17:18:23 GMT+0800" into 4 different short string like "You entered: " , "Hello! how are u guys doing." , "Wed Jun 30 2010" , "17:18:23 GMT+0800" and store inside my tables?

0

thanks vault. i got some questions for you. a little background: my lan messenger looks like facebook messenger, when u click a small tab. it pops up a division; into the division there is a textarea2(displaying message in textarea1) and textarea1(message).
1. i tried using submit, however after i click submit, the division disappear. therefore i change to a 'button'. so shld i stay on my 'button' / 'submit'?
2. .$user. << why does the php var has 2 dots. what does it means?
3. should i redo my javascript function into PHP function?

0

There are a few things:

- How are you planning to reload the page, because if you do that every so many seconds, the user gets extremely annoyed due to the fact that he can't type and his text may be gone

- Shouldn't you just simply use AJAX? Two functions are only needed: GetMessages() and SendMessage(txt). GetMessages only refreshes the value of the textarea (without page reload!) in case of a new message. SendMessage is pretty straightforward.

- The correct usage of mysql_connect is: mysql_connect('localhost', 'mysql_user', 'mysql_password');

- Use events rather than form submission

~G

0

thanks for ur reply graphix. izzit a preset function? (getMessage() , sendMessage(txt)) if it is where can i learn more about it? sorry about it... i am just a beginner in programming

Edited by hongchai: n/a

0

It's not a standard function, you need to write it yourself. Here is how it should be:

function SendMessage(mes) {

// Making the xmlhttp object....

var ajax = false;

// Create the object:

// Choose the objecttype, depending on what is supported:
if (window.XMLHttpRequest) {

    // IE 7, Mozilla, Safari, Firefox, Opera, most browsers:
    ajax = new XMLHttpRequest();

} else if (window.ActiveXObject) { // Old IE-browsers

    // Make the type Msxml2.XMLHTTP, if possible:
    try {
        ajax = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e1) { // Else use the other type:
        try {
            ajax = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e2) { }
    }

}

if (ajax) {

   var url = "message_send.php?message=" + encodeURIComponent(mes); // Send the message that was given as paramater for the function

   // Sends request
   ajax.send(null);

   // Function that handles response
   ajax.onreadystatechange=function(){
    // If everything is OK:
    if ( (ajax.readyState == 4) && (ajax.status == 200) ) {
       // Do something if the request was succesfull
       alert("Message was send.");
    }
   }

   ajax.open('get', url);
   ajax.send(null);

}

Now you only need to write the GetMessages() function:

function GetMessages() {
// Make ajax object
// Make a url to messages.php or something
// Create a onreadystatechange function that does something with the ajax.ResponseText which contains the messages
// Open the request
// Send null
}

send_message.php needs to:

- Save the $_GET into a variable
- Save that message in the database

messages.php needs to:

- Retrieve all messages from the database (or a limit of the last 10)
- Echo them separated by a new line or something

~G

Edited by Graphix: n/a

0

thanks for ur reply graphix. do i need to create another file call message_send.php? i am starting to get this AJAX idea.... izzit separating the function into a php file and use the AJAX to call it back and execute?

0

You use JavaScript functions to open the php-pages that sends the message or retrieves and returns them.

JavaScript function -> Calls PHP-page, which is executed -> PHP-page returns ResponseText

SendMessage(mes) -> Call PHP-page with a GET-data -> Returns nothing, or perhaps something like "Succes" to let you know the message was succesfully stored in the database

GetMessages() -> Calls PHP-page -> PHP-page returns ResponseText that contains the messages -> You set the value of a textarea (or the innerHTML of a div) ResponseText

~G

0

thanks for ur reply and advice graphix. i think i can discuss with my supervisor. Thanks for ur help graphix, vault and raja. will be back for more questions : )

0

a chatting system cannot be achieved by javascript or PHP alone, you need a combination of both which is AJAX.

What do you think I explained in my posts... Read before you post?

-1

1. If you use "submit" the page try to refresh. You can Use "button" and you can pass the value its onClick event.

2. It is the right way to wright php variables with in sql.

3. you can use either php variable with js or js variable with php.

Votes + Comments
This completely adds nothing to the discussion and 2&3 are very strange advices?
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.