Posting AJAX variable to the same page's php [duplicate] - php

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I am trying to save the value I get from a drop-down list to a PHP variable. I am currently able to do so but through another page. However, I want to do more than just echoing the variable, I want to use it as a parameter for one of my PHP functions on the same page.
I've tried several other solutions I found online but all of them had a submit button, which I don't want. I just want the variable to change on the same page as soon as the drop-down value is selected.
I also tried replacing 'ClientAjax.php' with my current page 'Month.php' but all I get is the same page inside the '#result' div.
Dropdown menu: (Month.php)
Used to populate my dropdown with values from a database.
<select id="clientselect">
<option selected>ALL</option>
<?php echo getClients(); ?>
</select>
<div id="result"></div>
AJAX: (Month.php)
I post twice since I need to show the default selected value as soon as I refresh.
<script>
$(function(){
var displayclient=$("#clientselect option:selected").text();
$.post('ClientAjax.php',{postclient:displayclient},
function(data){
$("#result").html(data)
});
$("#clientselect").change(function (){
var displayclient=$("#clientselect option:selected").text();
$.post('ClientAjax.php',{postclient:displayclient},
function(data){
$("#result").html(data)
});
})
})
</script>
ClientAjax.php
<?php
$client = $_POST['postclient'];
?>

Before you can use $_SESSION variables you need to start a session. Use the PHP command 'session_start()' to do this, most likely on the page that will use the $_SESSION variable. Be sure to place the command at the very top of the PHP block.
Then in your AJAX php script you need to place this command after the variable value is set. $_SESSION["var_name"] = $variable;
Then in the function that will use the variable just replace whatever variable you are using now with $_SESSION["var_name"].
This will only work if you do a submit sometime after the AJAX call. The PHP function on the page will not run again until you submit. Maybe this approach is not for you?
Post back if you need any more help,
CharlesEF

Related

changing a PHP $SESSION value by clicking on a div

I'm trying to change the value of a PHP session variable when the user clicks on a div element.
There are several div elements on the page and each will change the session variable to a different value.
At the moment I have the following code under the first div as a test but can't get it to change the variable's value.
<div class="workpiece" onclick="<?php $_SESSION['pageRef'] = 1; ?>">
I would greatly appreciate any help as I'm very new to this.
Thanks
You are putting server side code in client side script. You cannot do this, as server side code executes before it is sent to the browser. What you can do, is send an ajax request to a PHP script on click.
<script>
function sendajax() {
$.post('scriptforsession.php', {}, function(response) {
console.log(response);
});
}
</script>
onclick='sendajax();'
Ajax would be one solution but I think what you are trying could also be handled by simply putting the page reference in a GET. Though this will make the page reload. Then in your PHP simple use the $_GET['pageRef']
<div class="workpiece" onclick="window.location='?pageRef=1';">

Repeated jQuery POST ajax calls to a php file with output only works once [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
So I have a few links that's values are stored in jQuery and then are used as a variable for the PHP file it calls. In that PHP file, it outputs the same exact links so the process can continue without refreshing the page. But, the second time clicking the links does not produce the jQuery POST ajax call to the php file.
Here is my jQuery code
jQuery('.wantedStatus').on('click', function(event)
{
var anime_id = <?php echo $anime_id; ?>;
var anime_list_entry_id = <?php echo $anime_list_entry_id; ?>;
var wantedStatus = jQuery(this).tex
jQuery.post("/path/to/php/file/updateStatus_animelist.php", {firstParam : anime_id, secondParam : anime_list_entry_id, thirdParam : wantedStatus}, function(data) {
//this is your response data from serv
console.log(data);
jQuery('#anime_list_update').html(data);
});
return false;
});
The links that activate this function.
Watching
Plan to watch
On hold
Dropped
Now these exact links are outputted from the updateStatus_animelist.php and so when they are clicked again, they don't work.
Because the elements are getting replaced on each call, you want to listen to click on either the parent or the document.
Please try:
jQuery(document).on('click', '.wantedStatus', function(event) {
...
});

PHP contact form needs to call Javascript to show a hidden div on main .html page

I have a one page website in the works that has a contact form where its contact error and contact thank you messages are placed further down the page as hidden divs.
The contact form calls an external php file that calls the anchor links of the error and thank you message divs in the index.html file.
www.photograsurfer.com/test/index.html
www.photograsurfer.com/test/code/contact-panel.php
Everything works successfully as long as the divs are not hidden. So now I need to use the following javascript to get the hidden divs to display when needed.
<script type="text/javascript">
function showContactPanelError() {
document.getElementById('contact-panel-error').style.display = "block";
}
</script>
My problem, besides being a complete PHP beginner, is that I don't know how to get the PHP file to reference the Javascript code to display the hidden divs properly on the main page.
Any help is appreciated.
Thanks.
Use jQuery forms (http://malsup.com/jquery/form/) to submit your form via AJAX, then show/hide divs depending on values you return from PHP scripts.
you could assign php variable to javascript as
var error="<?php echo $_GET['error']; ?>";
the $error is the data passed along with the url like wwww.example.com/test.php?error=1
Now you could check var error and call your function showContactPanelError().
I ended up going with a mixture of the 2 methods on these pages.
http://trevordavis.net/blog/ajax-forms-with-jquery
https://spruce.it/noise/simple-ajax-contact-form/#contact
Ditched the div idea since the Ajax method allowed me to not reload the page and enter error and thank you messages within the contact form itself. Seemed like an easier approach.
Thanks for all of the suggestions, as I never would have looked at using Ajax otherwise.
You can add a onclick event on submit button. On clicking it will create an ajax call send data to the required external PHP file and then on success will display the hidden division properly on the main page.
here's a sample code just for an explanation
**
* Description : Function that will trigger the AJAX request.
* #param none
*/
function CategorySubscriber_Unsubscribe(){
var data = {
'data-1': data-1,
'data-2': data-2,
// as per your need you can put any number of data
};
var url = // your url
jQuery.post(url, data, function(response){
jQuery.show("#your-div-id");
});
}
function(response) will be executed when ajax call will be in success status.
You can learn it from these links
http://www.w3schools.com/jquery/ajax_post.asp
http://api.jquery.com/jQuery.post/

Send PHP variable to JavaScript function [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a php file that generates a variable and I would like the variable to be put into a JavaScript function which is called by onclick on the main page. Is this possible to send from PHP to JavaScript?
You can do the following:
<script type='text/javascript'>
document.body.onclick(function(){
var myVariable = <?php echo(json_encode($myVariable)); ?>;
};
</script>
Just write:
<script>
var my_variable_name = <?php echo(json_encode($php_string)); ?>;
</script>
Now it's available as a JavaScript variable by the name of my_variable_name at any point below the above code.
Your JavaScript would have to be defined within a PHP-parsed file.
For example, in index.php you could place
<?php
$time = time();
?>
<script>
document.write(<?php echo $time; ?>);
</script>
If I understand you correctly, you should be able to do something along the lines of the following:
function clicked() {
var someVariable="<?php echo $phpVariable; ?>";
}
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username and password:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 'You are logged in';
This would deliver the message You are logged in to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data); line in the success function would alert that message. Of course, you can echo anything that you like, even large amounts of HTML, such as entire table structures.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).
The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.
In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.
You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.
<script type="text/javascript">
// Do something in JavaScript
var x = <?php echo $calculatedValue; ?>;
// etc..
</script>

HTML Select selected value in php variable

I have a drop down in html.
When I change the value of the drop down I want to store the selected value in a php variable
How can i achieve this ?
Technically it is impossible. PHP is server side, HTML is client side. When a user calls up a URL the server runs the PHP which gets sent to the HTML, so you can not go backwards.
You can however use ajax to get the value of the select box and use it in some meaningful way. What are you wanting to do with this variable?
EDIT
Using jQuery I would send the value of the select box to an ajax file, and then have the ajax file create the text box if the value is what you want it to be. Here is an example.
$("#selectEle").change(function() {
$.ajax({
type: "POST",
url: "yourajaxpage.ajax.php",
data: {selectVal: $(this).val()},
success: function(response) {
$("#textBoxArea").html(response);
},
error: function() { alert("Ajax request failed."); }
}
});
You will grab the value in your ajax page using $_POST['selectVal']. Test that value there, and create an HTML textbox which gets sent back to the success function.
Without submitting the form, this can be done using an AJAX call (see libraries like Prototype and MooTools for easy methods) all off the onchange HTML attribute of your select tag.
yes, as suggested a javascript/ajax implementation would be a good fit here.
I use jQuery but I'm assuming it can be achieved in other libraries.
Anyway .change() in jQuery would work for this. When a user changes the selected index of the drop down it triggers the the .change() function and you would insert more javascript conde inside of this function to make the needed changes.
If you wanted you could find out the selected index or get the value of the selected index and put in logic based around that to load your textbox (also using javascript).
Something like
$('target').change(function() {
var value = $('target').val(); // gets the selected value
if(value == "what you want it to be")
{
// load data into a div from your php file.
$('#loading_div').load('ajax/test.html');
}
});
That should definitely get you started.

Categories