Store jquery variable, transfer to php and check - php

Ok, so I'm trying this again. I'm trying to validate a users age by country - all selected from dropdowns.
First I use the dropdown to select country, the value of each is 16/17/18 etc so I'm using this script to capture that:
function displayVals() {
var singleValues = $("#country").val();
}
then I'm sending that variable to php:
$countryAge = $_GET['singleValues'];
next I want it to be the result of this function:
function age_required() {
return absint($countryAge);
}
It's just reloading the page, so not throwing any errors that I can see, but also not displaying the notifications that the person is too young etc. It was working before I started meddling.
Any ideas of why it doesn't work? What am I doing wrong? I'm NOT a php/js guru.

$_GET retrieves the value from a querystring, so when you are posting or some other way going to your PHP page, you need to make sure the url includes "?SingleValues=(YOURVALUEHERE)".
http://php.net/manual/en/reserved.variables.get.php

It sounds to me like you may be a bit confused over the role that both JavaScript and PHP play in web applications.
JavaScript runs in the client (i.e. the browser). The source code lives on your webserver, and then gets downloaded in whole to the browser before it gets executed.
By contrast, PHP runs on the server. Its purpose is to create X/HTML markup as output, which the web server then sends to the browser.
In order to get data from the browser to PHP and then back again you need to generate a request. This can be done on the fly (read: without a new page load) using AJAX. There's lots of questions here on SO about AJAX, so I suggest that you begin exploring those questions/answers.
To help you off, here's a few tutorials:
AJAX Using Native JavaScript
AJAX Using jQuery Framework

Related

Writing PHP output into textfield

I've tried looking around for the answer to this but I can't seem to find it.
I have a database which takes in two pieces of information and returns it either as successful or unsuccessful.
I would like to be able to press a button "Submit" and then run my PHP query(which is fine) to print out an echo into a textbox once it has been completed.
echo '<form name="enrolled" method="post" action="<MY FUNCTION HERE>"><select name="course">';
Once my function is complete, it will echo something out. I would like for a textbox display that echo.
The problem I have been having is that it wasn't working in realtime, I could easily get an echo to display on a textbox but I cant get it to stay blank and then once the function has completed, populate the box.
Thanks for taking the time to read.
As nathan says you seem tobe a bit confused about php works. It writes HTML (or other stuff) which is sent to the browser where it is rendered. Until you send another request back to the server, PHP sits idle. If you don't want to transition from the current page but update it's contents then you need to create javascript that, when triggered makes a request to the server (and takes appropriate action when the server responds.
If you Google for PHP Ajax tutorial you'll find lots of examples.
Not elegant at all but just echo the whole field...
echo "<input type='text' name='something' value='the value you want to echo'>";
Not really sure what you are trying to do in your PHP.
The html form action attribute it is supposed to be a URI, not a javascript function.
For update in realtime a form, or just a input, you can use javascript and perform ajax request. If you want make it fast and quickly I recommend you use Mootools Request class for make a ajax update in your form.
You can see a full demo example of ajax real time updates (HTML, PHP, Javascript) in Mootools site.
Two ways of doing it:
Via Post and refresh:
your form you be something like
script.php
<?php
$result = "Hello world!"; //Do your logic anywhere but be sure to set the result here
?>
<form method="post" action="script.php">
....
<input type="text" value="<?= $result?>" readOnly>
<input type="submit">
</form>
the other way is via AJAX
that will take a lot more research. Try this one, it's much simpler!
You need to post your form using AJAX and then display results in the box. It's easy done with jQuery library. To include jQuery library just add this to your html head
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
Then you can submit your form using this script
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'post.php',
$(this).serialize(),
function(data){
$("#result").html(data)
}
);
return false;
});
});
post.php in the name of the script you are calling that will receive the form and return the answer. myform is id of the form and result is id of the box you want to display results to.
You are thinking about PHP the wrong way; PHP doesn't interact with the web browser directly. What you need is AJAX. Here's why:
The client (web browser) sends a request to the web server (apache, lighttpd, etc.)
The web server interprets that request, and (in this case) hands it over to PHP
PHP echoes the result based on the input given to it by the web server
The web server sends that result back to the web browser
The web browser determines what to do with that information
Now, if this is you navigating to a web page, the web browser renders the content generated by your web server (which used PHP to generate it). If the web server has already responded, that's it - you've got your response. To get more information, you'll have to make a new request, which means you have to do one of these two things (typically):
Navigate in your browser by submitting a form, reloading, navigating to a new page, etc.
Use Javascript (which is executed by the client, not the server) to make a "background" request
The technique of using Javascript to make a request "in the background" and update the page without reloading is called AJAX, and there are many ways to accomplish the task, but by far the easiest and most popular method is to use the JQuery library, which is a wonderful kit of useful functions and additions to Javascript that make it less painful (even enjoyable!) to work with - including a simple function for making AJAX requests using the POST method.
There is a lot to learn on the subject, but hopefully this will give you a solid enough understanding of what you need to know to accomplish this task.

Calling PHP function after jquery code

Dear Firends I have large number of forms on a single web page all of them calls a single PHP function. However what I want is that the forms should call a jquery function and if there is a need then jquery should let it call the PHP function.
I do not want to use Ajax just want to create a PHP function call if the matter can not be solved by jquery.
Each of the form is associated with some data. how ever all the data that is displayed on the page is not available all the time. So what I want is
if (data == available) { call PHP}
elseif (data != available) { jquery alert('sory bro');}
if data can not be seen now just use jquery to say sorry (no need to check from server). When a page is loaded we know which all pieces of data can not bee seen and are given in different color.
The forms are generated using a PHP loop with each form showing different data but of same type (each form is assocaited with a sort of Article).
All the questions that I have seen are about Ajax. Where as my current PHP code is working fine. all I want it that before making a trip to server if the data is not available the jquery shoould say so. We already know which data is not avaiable so far.
I hope I have explained it
Thanks a lot
**I think I have not made my point clear.. When the page is loaded is already know which data is not available for display and it is marked in seperate color and the div has different arrtibute...*is there some way so that I do not call PHP function for those forms?
PHP executes on the server side. Javascript (jQuery) executes on the client-side. So PHP is completely done executing before Javascript starts executing.
That's why everyone is saying you need to use AJAX. AJAX is a way to make a call back to the server in order to execute PHP code. PHP code only executes on the server. So in order to execute PHP, you have to make a call back to the server.
According to your logic, the data is present on the server.
If you want to know if the data is available or not then you have to contact the server right.
If that's the case how can it be solved without sending an ajax request..
You need to make the request as jQuery is a client side code and cannot contact the server directly.. You need the server side script to execute it which is PHP in your case
The easiest solution:
if (data == available) { $("form").trigger('submit') }
elseif (data != available) { jquery alert('sory bro');}
Obviously you need to adapt the selector according to your specific form / requirements.
Just make sure your form does not get submitted accidentally when you press submit by adding something like event.preventDefault(); in your function.

Submitting form without refresh

I am retrieving Google's weather API XML and using PHP. I'm retrieving the weather for any searched city.
Now, this "app" is under a tab and whenever I submit the form it refreshes and I want to prevent this.
Is it possible? This will be implemented in a dashboard - thats the reason I want to prevent the refresh.
This is what I mean: http://www.screenr.com/30As
The entire code is here: http://jsfiddle.net/ZshpF/
Simply, copy paste the code in a php file and it will work.
You'll want to use AJAX. Since you mention jQuery in the tags, it has a very handy function for making the call to the server. But making the call from the JavaScript is only half the story, you'll also need something on the server listening for that call. It would essentially be another PHP script which acts as a page in and of itself, but would return data in the form of (most likely) JSON instead of HTML. It's not meant to be human-readable, but rather to be a sort of web service for your JavaScript code to use.
You can find a simple example here.
I think you can use jQuery ajaxForm

PHP onclick get text and make a variable

Goal: I want to get the text from the selected element and then create a PHP variable from it.
I know how to do this using jQuery but can't wrap my mind around the idea of how to do it in PHP. Basically lets say I have a table with some data. When the user clicks on the data I would like to retrieve that text and then place it in a PHP variable. I could use .text(); from jQuery to create the variable but I could not pass that variable into PHP for further use.
I am very new to PHP (a front-end developer trying to learn back-end). So any explanation would be helpful also.
thanks!
***OK I now understand how to do it. Thanks for the input. I was not thinking. It makes perfect sense to create the variable using a _post and then returning the data via AJAX. Sorry for wasting your time. Thanks for replying.
There is no onclick event in the backend, at least not that works like in javascript
if you want to pass a variable to the server you can use a form and send the data through a GET or POST
Example:
<form action="index.php" method="get">
<input type="button" value="somevalue" name="action" />
</form>
when the user clicks you will see this in the url
www.example.com/index.php?action=somevalue
now you can retrieve this value in php using the $_GET global variable
$variable = $_GET['action'];
The same can be done using POST, this way the variable is not shown in the url
In order to have PHP gather any client side data you would have to pass that data back to the server.
To assign data from client action to a PHP variable, you would first have to capture that data using a front end solution (like your jQuery one above) then pass that information to your server application for processing using AJAX or form submission.
Your PHP data handler could then parse that information out from the data submission and push that info into a variable.
Your front end would look something like
$.ajax({
type: "POST",
url: 'your_file.php',
data: 'selected='+ captured_data,
});
and on your back end...
<?php
...some php code...
$var_to_hold_selected_thing = $_POST["selected"];
...more php code
?>
Specifics of how to do more than that would depend on your application...
You can do it with ajax:
$.ajax({
type: "POST",
url: 'your_file.php',
data: 'text='+ text,
success: function(data) {
alert(data);
}
});
After the .click() event you could have a dialog box appear, with Is this your text?. Then post it.
You could grab that text with jQuery using $(elem).text() as you've described and then pass the captured value to PHP using an AJAX request with jQuery (see $.ajax). The PHP script you pinged with AJAX (either via GET or POST) can then take the value you passed and push it into a $_SESSION variable.
session_start();
$_SESSION["text_clicked"] = $_GET["text_string"];
exit;
After you do this, any subsequent ajax calls made with jQuery (to any PHP script), can recall this variable, provide that you've properly initiated the session.
Stack 101's answer is the correct execution that you're looking for, however it sounds like you could use a little more background on the context first.
Basically, PHP is a server-side scripting language, which means that it gets executed before the page loads into your browser. Here it can look at a database, connect to other sites, or do a whole host of other stuff. Once it's in the browser, your HTML + CSS + jQuery is in charge of displaying + styling + and manipulating that information respectively.
AJAX is usually used to describe the act of posting data to a PHP script, and then re-loading it back into your page without the page refreshing. In other words, jQuery passes data to a PHP script that runs on the server, and then loads in whatever the PHP script outputted. Sometimes PHP can output an entire site (html tags, css, js, whatever). Other times it can simply access a few variables that it got from the POST array, and output a result. This is much more common with AJAX requests.
A quick search turned up this tutorial which might help (I haven't followed it)
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
Good luck!
I believe it could be done by sending all the required content through GET or POST, and then make PHP stuff it to a variable, however I'm not exactly sure.
PHP runs on the server. Variables come and go each request. Everytime you refresh a page (or send a request otherwise), a PHP script starts running, spits out a response, and stops again. So setting just a loose variable is not really an option.
The options you got are
- Use a cookie. You can set it from Javascript and it will automatically be sent with the next request. Your PHP script can read this cookie.
- Send the variable by doing an AJAX (asynchronous) request. You can send the value in the url or as posted data.
In either case, you can decide to use the variable only once, or store it in a session. I think the cookie will remain unless you explicitly clear it. So you could keep using that.

passing values from java script to php

can any one please help how to get the values from the javascript to php other than while using submit button.
scenario:
i am searching for record, if the record found then, i need confrim alert asking to continue or not, if he click continue how can i say he selected continue
If you want to check without having a page reload, you probably want to execute an AJAX call, then depending on the result returned by the underlying PHP script, take the appropriate action. If you have no knowldege of how to implement this, take a look here
You can never use JavaScript to communicate with the page while it is loading, you can only send a new request to the web server from the JavaScript layer... although you can send that request to the same script that's already running, it will still be a new instance of the PHP script, just like when you open a new browser tab to the same page.
The only way for JavaScript to communicate with PHP at all, is by sending an HTTP request. But you don't have to refresh the page in order to do that if you use AJAX.
AJAX is basically a word to describe JavaScript exchanging information with web pages without refreshing the page. But note that it will still not be able to change variables in the PHP script which is running when the JavaScript code is executed.
In the case of PHP, I've used the open-source library SAJAX which is quite simple. You will find it at http://www.modernmethod.com/sajax/
Hope it helps and good luck!
You can use this as an example using jquery and PHP:
$.post('searchimage.php', { action: 'searchimage', imgreference: $(this).val() },
function(data) {imgsample.html(data);}
);
Basically apply the above function in a document ready function so its run when the page loads.
This can be triggered using $("#prodcode").click() or what ever event handler you want to use.
The php page in my example will get sent the value from imgreference as a post, you can do whatever you want in the php page then return the value which gets added to the imgsample (in this case a td)
hope this helps.

Categories