Reputation: 3
I know this had been disputed a lot and the short answer would be that I can't simply pass a javascript variable to a php variable in the same file. So instead here would be what I want to try: My user inputs a code, I send it to a php file by POST
. There I check if the code matches a code from my database and I post again a boolean from there. Then in my first file, I tell the user whether the code is correct or not. Can this be achieved this way? I am a webdev newbie and I am trying to learn.
Upvotes: 0
Views: 150
Reputation: 1523
jQuery:
$.get( url, { userinput: value }, function( response ) {
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
}
javascript:
function get( url ) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false );
xhr.send();
return xhr.responseText;
}
var response = JSON.parse( get( url ) );
if( response.status ) alert( "Matches found" );
else alert( "No matches" );
php:
header( 'Content-type: text/json' );
if( get_matches( $_GET['userinput'] ) ) exit( '{ "status": true }' );
else exit( '{ "status": false }' );
Upvotes: 0
Reputation: 2806
You can post that code through AJAX to your server, have your server return a boolean, and then output a message to your user, this is quite common.
Common implementations of this logic include autosuggest, username validity verifications, simple turn on / turn off interfaces, etc.
Workflow:
Edit: Even though i advice you to try doing it with pure javascript first (for educational reasons), you should use jQuery or other equivalent framework if you are on a schedule.
Upvotes: 0
Reputation: 43850
To pass a value from the client side to the server you can either send it on the URL or as a post variable.
This can be accomplished easily with ajax.
I recommend using jquery. example:
$.get("http://example.com/?var1=value&var2=othervalue", function (data) {
// your response
});
Upvotes: 1