-1

I'm trying to assign the return value of a php script to a js variable. I have this:

    var email = jQuery("input[name=email]").val();
    var emailRegex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,})?$/;
    var exists='<?php 
                    $query = "SELECT * FROM rss_members WHERE email_id=\"something@email\"";
                    $results = mysql_query($query);
                    $results = mysql_num_rows($results);
                    echo $results;
                ?>';
    console.log(exists)

The query works and I get the correct results back, but I want to replace "something@email.com" with the email variable, but if I write something like email_id=\"'+email+'\"..., the query result comes back incorrect. What am I doing wrong?

  • 2
    Just so you know, it's generally a bad idea to construct server-side code on the client. It's better if you keep that code on the server then just send up the email address or something. – Mike Cluck Mar 30 '16 at 19:42
  • 4
    PHP runs and is finished before any JS code is executed. You can not do is this way - you need to make a new request to the server (f.e. via AJAX), send the variable value as a parameter, and then have that PHP script return the correct value. – CBroe Mar 30 '16 at 19:44
  • Start learning AJAX. It will help you out a lot. – dokgu Mar 30 '16 at 19:49
  • Thanks guys, I will definitely start learning some AJAX. – user3330863 Mar 30 '16 at 19:51
  • Possible duplicate of [How to pass JavaScript variables to PHP?](http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php) – Adam Konieska Mar 30 '16 at 19:51

1 Answers1

1

You aren't taking in consideration execution time. When you make a request to a server (enter www.google.com for example) the server gets a request, and replies with a HTML page. The server in your case is in PHP and it sends a HTML page with some javascript included in it. After the browser receives the HTML page, it then interprets it, and run javascript code.

So basically, your php code ran without access to the email variable. If you wanted to have access to server-side information after the page loaded, you would need to make an ajax request

iagowp
  • 2,428
  • 1
  • 21
  • 32