Jump to content

Pass PHP variables to JavaScript


Go to solution Solved by maxxd,

Recommended Posts

I am trying to build a website, where:

 

1) User logs in (UserA)

2) Inserting a name in the search box and pressing "Search", a list of all users matching that name is shown

3) The user selects a user (UserB) from that list (among several results)

4) By selecting the user (UserB) , a message box appears to insert text

5) The user(UserA) types the message

6) The user(UserA) presses the SUBMIT button and sends the message to the other user(UserB)

 

The problem i face is how to pass the variables from my PHP script to the JavaScript script. Its easy for me to get the values of input fiedls, select fields or any other DOM element value. But if the value i need to pass to Javascript file to perform an AJAX call isnt inside a DOM element, how do i do it?

 

For example, for me to determine the user that will send the message (userA), i will need several data. This data, i have them inside the PHP script as variables, but dont know how to pass them to Javascript file.

 

Getting the data from the URL, or from a hidden input field or any other DOM element, is a solution, but i want to know the way that is safer and better.

 

To summarize:

 

-->[pass necessary data from PHP to JavaScript file]-->[perform an AJAX call] --> [return data to PHP Script]

 

How do i do it?

 

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/291926-pass-php-variables-to-javascript/
Share on other sites

A variable doesn't have to be in a DOM element to read it from AJAX, you can simply read it in from php via Ajax or by pulling the data in indirectly from a DOM element (In you case it would probably be a form element input?) using a keyboard press (I believe Google's search engine does something like that). 

I am a bit confused (if not a lot).

 

I have the main PHP script (lets name it main.php) where i somehow calculate/extract from my database the following values:

userA_id (a.k.a sender_id)

userB_id (a.k.a receiver_id)

message (a.k.a message)

 

In my script file i have the following:

 

$(document).ready(function(){

 

 $('input#submit').click(function(){

      

      var sender_id = ???

      var receiver_id = ???

      var message = ???

 

      $.post('js/ajax/sendmessage.php', {sender_id:sender_id, receiver_id: receiver_id, message:message}, function(output) {....do something with output});

 

  });

});

 

The sendmessage.php script, is a script that given the values sender_id, receiver_id, message, performs some actions and sends the message to userB.

 

My issue here (or the thing i dont understand), is how i can send these values from the PHP script (main.php) to the JavaScript file.

 

Sure i can use a hidden input field and collect these values from there (is it a correct method or a method at all??), but is there any other way i could perform this?

 

Do i get it all wrong? Any help will be much appreciated..

OK - you're having an issue before the ajax call, right?

 

So how is the sender (userA) selecting a recipient (userB)? If they're typing a name into a text input, you can use the value of that text input in the sendmessage.php script to find the ID. If you're using a select element, the ID (or a proxy) should be printed directly into the markup as the value of the option element - main.php (or another script that's calling main.php to get the data) is going to print userB's id in the option element value. You'd then send that with $('#recipientSelect')val() from the JS to sendmail.php.

 

UserA has to be logged in to send a message, right? If so, I'd think you'd have their user ID in session and can grab that in sendmessage.php without having to define it in the javascript at all. And obviously the message value is the $('#message').val() of the message text area.

 

Is that the question you had, and if so, does that make sense at all?

You ask how to send php vars/values to your JS code which is being output by this same php script, no?  If 'main.php' is building that js code and outputting it, then that JS code is eventually going to call sendmessage.php.  Since any php value has to be determined before the script finishes and can't be determined on the client, then it seems all you have to do is hard-code them in your js code when you output it.

 

Either that or you are mis-speaking on your intent

My comments in red:

 

OK - you're having an issue before the ajax call, right?

Yes. I need to know the best way of sending data from PHP over to JavaScript.Maybe some ways are better and more secure than other.

 

So how is the sender (userA) selecting a recipient (userB)?

UserA types a string inside a search box, hits Search, and results are displayed below (most of the times more than 1 result).

 

If they're typing a name into a text input, you can use the value of that text input in the sendmessage.php script to find the ID.

This is not good for me. If i search a user with the name John, and get 2 results, then each John is a different user with a different ID.I need to exactly identify each user.

 

If you're using a select element, the ID (or a proxy) should be printed directly into the markup as the value of the option element - main.php (or another script that's calling main.php to get the data) is going to print userB's id in the option element value. You'd then send that with $('#recipientSelect')val() from the JS to sendmail.php.

This is what i am trying to do now, but using radio buttons instead. Each radio button will have the value of the ID of (each) UserB. By selecting the UserB i want, i will be able to know who he is, by accessing the value of that radio button selected.

 

UserA has to be logged in to send a message, right? If so, I'd think you'd have their user ID in session and can grab that in sendmessage.php without having to define it in the javascript at all.

So in other words, to start a session inside main.php, save the UserA_ID into a session variable and then start a session in sendmessage.php and get that variable?

If this a solution, then why not to send all variables i want over to sendmessage.php using sessions? Is there a security issue?

 

And obviously the message value is the $('#message').val() of the message text area.

Yes this is how i grab the message value.

 

Is that the question you had, and if so, does that make sense at all?

Thanks a lot for your time. Some times you may have the answer, but in order to be sure you need to ask around people with more experience than you! :)

  • Solution

OK - now we're getting there. It sounds like you're on the right track. Using radio buttons and associating each possible recipient's id to the value attribute is exactly how I'd go in this situation. Pass the user-defined information (recipient(s) and message) via AJAX, but keep the system defined information (your sender's ID) in $_SESSION. That way you're not mucking about too much with the session data and, more importantly, when you go back to the code in six months to a year, you can clearly follow the data chain. In addition, you can then move and repurpose the AJAX script without having to worry about any hard-coded $_SESSION calls. Think of it as decoupling the script from the site.

Just echo out the PHP variables into your Javascript.

      var sender_id = <?php echo $sender_id; ?>;
      var receiver_id = <?php echo $sender_id; ?>;
      var message = <?php echo $sender_id; ?>;

You can create JavaScript from PHP, but not the other way around.  PHP is parsed FIRST.  You can have PHP output whatever you want, anywhere you want. pretty much.

OK - now we're getting there. It sounds like you're on the right track. Using radio buttons and associating each possible recipient's id to the value attribute is exactly how I'd go in this situation. Pass the user-defined information (recipient(s) and message) via AJAX, but keep the system defined information (your sender's ID) in $_SESSION. That way you're not mucking about too much with the session data and, more importantly, when you go back to the code in six months to a year, you can clearly follow the data chain. In addition, you can then move and repurpose the AJAX script without having to worry about any hard-coded $_SESSION calls. Think of it as decoupling the script from the site.

Lets say i manage to send all PHP values over to JavaScript and i dont need to use SESSIONS to send any values to sendmessage.php script.

 

Is it a good practice to send all these values to sendmessage.php using SESSIONS and then compare them to the one send to this script using the AJAX method?

 

For example:

 

sendmessage.php

 

Receiving values via SESSIONS:

 

$senderID = $_SESSION['senderid'];

$receiverID = $_SESSION['receiverid'];

$message = $_SESSION['message'];

 

Receiving values via AJAX[using post method]

 

$senderIDAJAX = $_POST['sender_id'];

$receiverIDAJAX = $_POST['receiver_id'];

$messageAJAX = $_POST['message'];

 

if($senderID == $senderIDAJAX && receiverID == receiverIDAJAX && $message == $messageAJAX)

{

     do something

}

 

Does this add on security?

 

Thanks!

It is difficult to follow you here.  Now it appears that you use main.php to create a page that has a js function that will call sendmessage when activated by the user's actions.  So if you truly want sendmessage to return some results to your currently displayed page, then you simply echo that data back to the ajax caller.  That's how stuff is sent back.  I believe that it can be secured somewhat if you use php to json encode it before sendmessage echos it out and then use the receiving js function (the ajax caller) to un-enccde it.  Simply encode your values and echo them back at the end of sendmessage.

 

Or am I reading you wrong again?

tsangaris, while I'm sure it couldn't hurt, I'd think it more important to make sure at least the sender and recipient IDs are legit, active IDs in your system before sending anything. Keeping the processing php script in a directory above the web root won't immediately make it safe, but it does make it a bit more difficult to call the file directly from outside your server. You should probably create a nonce in the source form html, store it in session, pass the value from the form with the other values and check that in the processing script to make sure that the request is coming from your form and not somewhere else. This doesn't mean a human being isn't logged in to your site sending bad messages, but at least it means you can be a bit more sure of the fact that request originated on your site.

 

And, of course, sanitize and validate any and all data supplied by an end-user. Or another system. Or anywhere, really.

Thank you all for your answers!

 

It is difficult to follow you here.  Now it appears that you use main.php to create a page that has a js function that will call sendmessage when activated by the user's actions.  So if you truly want sendmessage to return some results to your currently displayed page, then you simply echo that data back to the ajax caller.  That's how stuff is sent back.  I believe that it can be secured somewhat if you use php to json encode it before sendmessage echos it out and then use the receiving js function (the ajax caller) to un-enccde it.  Simply encode your values and echo them back at the end of sendmessage.

 

Or am I reading you wrong again?

No this is how i want it to work. My problem (lets say my luck of knowledge) was how to send php data over to Javascript. With the help with all of you now i get it! :)

tsangaris, while I'm sure it couldn't hurt, I'd think it more important to make sure at least the sender and recipient IDs are legit, active IDs in your system before sending anything. Keeping the processing php script in a directory above the web root won't immediately make it safe, but it does make it a bit more difficult to call the file directly from outside your server. You should probably create a nonce in the source form html, store it in session, pass the value from the form with the other values and check that in the processing script to make sure that the request is coming from your form and not somewhere else. This doesn't mean a human being isn't logged in to your site sending bad messages, but at least it means you can be a bit more sure of the fact that request originated on your site.

 

And, of course, sanitize and validate any and all data supplied by an end-user. Or another system. Or anywhere, really.

You are correct!  I am just a little paranoid when it comes to security! :) I already have protection from session hijacking, session fixation, CSRF, XSS, SQL injections, etc.

 

Thanks for your time and your answers. They helped me a lot!

This thread is more than a year old. Please don't revive it unless you have something important to add.

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.