getting variable from javascript to php - php

I have a simple combo box whose value I can get in JavaScript.
I am doing that so I don't need to refresh the page.
Also I want to use the selected value to do some conditional branching after combo box so how do I get the value of combo box from JavaScript to my variable $change.
echo '<select id="combo_1">';
echo '<option value="2">Submative</option>';
echo '<option value="1">formative</option>';
echo '</select>';
Below is my JavaScript:
<script type="text/javascript">
$(document).ready(function() {
$('#combo_1').change(function(){
});
});
</script>
Here I want to do $change = $(this).val(), but obviously I cant do it like this.
Any suggestions?
i want to do it on the same page without refreshing or without submitting
my url kinda look like this
http://localhost/lms/grade/report/userdef/index.php
and i want it to be on click action
cuz depending on the choice of combobox 2 very different procedures will be called

You're gonna want to use AJAX and submit the form, then you can access the returned data without ever refreshing the page.
Basically:
HTML
<select name="combo" id="combo_1">
<option value="2">Submative</option>
<option value="1">formative</option>
</select>
JavaScript
$('#combo_1').change(function() {
$.post('calcScript.php', $(this).serialize(), function(data) {
alert(data);
});
});
in PHP, you can access your combo data via $_POST['combo'].

<script type="text/javascript">
$(document).ready(function() {
$('#combo_1').change(function(){
var combo_1 = $(this).val();
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {'combo_1':combo_1},
success: function(data){
alert(data)
}
});
});
});
</script>
ajax.php
if( isset($_GET['combo_1]) ) {
echo $change = $_GET['combo_1'];
}

JS:
$.ajax({
type: "POST",
url: './filename.php',
beforeSend: function(){
//If you want to do something
},
data: 'data='$('#combo_1').val(), //Optional '&data2='+value+'&datan='+value,
success: function(msg){
alert(msg);
}
});
PHP:
$val = $_POST['data'];
return 'received successfully';
This will alert 'received successfully'

Related

How can I use localStorage in php with AJAX to update my database?

I need to use a localStorage value in a PHP file to update values in my database. I know that I need ajax to achieve this, I can't get it to work.
My localStorage item is named option and it exists (checked in browser and stored the value in a div)
$(document).ready(function(){
$.ajax({
type: "POST",
url: "activity.php",
data: { storageValue: localStorage.getItem('option') },
success: function(data){
alert('success');
}
});
});
PHP Example:
$option = $_POST['storageValue'];
mysql_query("...SET x = '".$option."'...");
echo 'Update complete';
I dont see any post data nor do I get a response.
Thank you!
Your page:
<form>
<input type="hidden" value="thedatayouwanttopost" id="option"/>
</form>
<script src="Your_Js_File.js"></script>
Your JS file:
document.getElementById('option').submit(); // This submits the form
var storageValue = $('#option').val(); // This gets the value of the form once it has been posted to the .php file
$(document).ready(function(){
$.ajax({
type: "POST",
url: "activity.php",
data: { storageValue:storageValue },
success: function(data){
alert('success');
}
});
return false; // This stops the page from refreshing
});
Your PHP file to callback the data to AJAX and display the alert (activity.php):
...
$option = $_POST['storageValue']; // This is the post value of your hidden input on your page
mysql_query("...SET x = '".$option."'...");
?><input type="hidden" id="option" value="<?php echo $option; ?>"><?
// The input above posts the value of 'option' on your page back to your Ajax and spits out the request.
...

Jquery/ajax/php load data into textfield after clicking checkbox

How do i load data into textfields after clicking a checkbox & after doing it, i need to disable that textbox, but again as i uncheck it, need to remove that data & make the textbox enable to manually enter data. I tried this code,i'm new to jquery/ajax, can't figure out how to solve this problem.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('#chk').click(function(){
if($(this).is(":checked"))
$("#txtaddress").removeAttr("disabled");
else
$("#txtaddress").attr("disabled" , "disabled");
// here, i don't know how do i assign $row['address'] to txtaddress by
// using php mysql
});
});
</script>
<!-this is my html code-->
<form>
<input type="checkbox" id="chk" name="chk">Same as home address?
<input id="txtaddress" name="txtaddress" disabled type="text">
</form>
Try the following,
<script>
$(document).ready(function(){
$('#chk').click(function(){
if($(this).is(":checked"))
$("#txtaddress").val(""); //reset the textbox
$("#txtaddress").removeAttr("disabled");
else {
$.ajax({
type: 'GET',
url: destinationUrl, // your url
success: function (data) { // your data ie $row['address'] from your php script
$("#txtaddress").val(data); //set the value
$("#txtaddress").attr("disabled", "disabled");
}
});
}
});
});
</script>
From your php script you can echo $row['address'], so the data in success function can be put into textbox in ajax
javascript code:
$(document).ready(function(){
$('#chk').click(function(){
var txt = $("#txtaddress");
($(this).is(":checked")) ? txt.attr("disabled" , true) : txt.attr("disabled" , false);
});
});
I hope this is what u meant.. Hope this might help... :)
$('#chk').click(function(){
if(! $(this).is(":checked")){
$("#txtaddress").removeAttr("disabled");
$("#txtaddress").val('');
}
else{
$.ajax( {
url: "get_row_details",
type: "POST", //or may be "GET" as you wish
data: 'username='+name, // Incase u want to send any data
success: function(data) {
$("#txtaddress").val(data); //Here the data will be present in the input field that is obtained from the php file
}
});
$("#txtaddress").attr("disabled" , "disabled");
}
});
From the php file echo the desired $row['address'].This value will be obtained at the success of the ajax function

How to set Session variable on text box's on change event in php

I want to update my session variables on textbox's onchange event, without page reload
How to do that.?? thanks!
You must use ajax for it, on on change event of textbox like,
$('textbox').on('change',function(){
$.ajax({
url:'yoururl.php',
data:{data},
success:function(){
alert('success');
}
});
});
I would use on blur, that way it wont set the variable everytime the user types, only when he clicks somewhere else....
$('textbox').blur(function(){
var thevalue = $(this).val();
$.ajax({
url:'yoururl.php',
type: "post",
data:{"value":thevalue},
dataType:"html",
success:function(data){
console.log(data);
}
});
});
THen in your php...
<?php
$_SESSION['yoursessionkey'] = $_POST['value'];
echo "success";
?>
It can be done by combination of javascript and PHP.
Make a function() and insert PHP code in it.
Pass the current argument as in session variable in javascript function..
<script type="text/javascript" language="JavaScript">
$(document).ready(function(){
$("#field").change(function(){
$.ajax({
url: "http://yourserver.com/ajax.php",
data: { value: $("#field").val() }
});
});
});
</script>
...
<input type="text" id="field" />
And in ajax.php:
<?php
$_SESSION['var'] = $_GET['value'];
?>

Submitting form with jQuery

Apologies if this has been answered before (I couldn't find the answer when I searched the archives)
I've got a page protected by a password:
<?php
if($_POST['pw'] == 'pw')
{
//Page content
} else
{
//Display password form
}
?>
Within the page content, I've got another form, which I want to submit using jQuery, and have the following code:
<script type='text/javascript'>
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
</script>
<form name='form1' id='form1' action=''>
<fieldset>
<label for='input1' id='input1_label'>Input 1</label>
<input type='text' name='input1' id='input1' size='30' />
<input type='submit' value='Update / reset' id='submit' class='buttons' />
</fieldset>
</form>
<div id='#testResult'></div>;
However, clicking submit then sends the form to p1.php?input1=test (i.e., the data string is being sent to p1.php, not p2.php). If I edit the code and remove dataType:html and the 2 references of data2, then this doesn't happen (infact, nothing happens, so I assume that jQuery is submitting the data to the form). I've also changed the type to 'GET', incase the 2 POST requests on the same page were causing problems, but this didn't change the result.
What am I missing to get the information from p2.php (i.e. data2) and displaying it?!
EDIT
Thanks to a comment pointing out a typo, I've changed dataType: html to dataType: 'html' - this now doesn't cause the page to redirect to p1.php?input1=test, but once again, it doesn't do anything (when it should still be returning the value of data2)
EDIT 2
I've updated the code so dataString is now:
var dataString = $('input#input1').val();
dataString = 'var1='+dataString;
but this hasn't made any difference
For clarification, my p2.php just contains the following:
<?php
echo "<p>HELLO!</p>";
?>
EDIT 3
I made the changes to my code has suggested by Damien below; I get the alert of "works!" but still nothing seems to be returned from p2.php, and nothing is inserted into the #testResult div.
var dataString = $('input#input1').val();
$(function() {
$('#submit').click(function(evt)
{
evt.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: "someval="+dataString,
dataType: 'html',
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
$(function() {
$('#submit').click(function()
{
var dataString = $('#form1').serialize();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
success: function(data2) {
alert('works!'); // ADDED AFTER UPDATE
$('#testResult').html(data2);
},
/* ADDED AFTER UPDATE */
error:function(obj,status,error)
{
alert(error);
}
});
return false;
});
});
Edit:
In p2.php:
<?php
var_dump($_POST['pw']);
?>
In p2.php you then need to output ( using echo, for example) what you want to be returned as 'data2' in your ajax success call.
UPDATE:
Since you're Ajax request fires succesfully, that means either your post is not passed correctly, or you're not outputting anything. I've re-looked at your code and I saw this:
<input type='text' name='input1' id='input1' size='30' />
that means you're fetching the wrong $_POST variable!
Do this:
Since you're sending a name="input1", in your p2.php try with:
<?php
if(isset($_POST['input1'])
{
echo $_POST['input1'];
}
else
{
echo 'No post variable!';
}
And in your jquery success:
success: function(data2) {
alert(data2);
$('#testResult').html(data2);
},
That oughta work, if you follow it literally. In the remote possibility it won't work, forget AJAX, remove the javascript and do a normal post submitting with p2.php as an action of your form :)
I think you have to prevent the default action of the form.
Try this:
$('#submit').click(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: 'p2.php',
data: dataString,
dataType: html,
success: function(data2) {
$('#testResult').html(data2);
}
});
return false;
});
});
The data should be formatted like this:
variable1=value1&variable2=varlue2
I also think you can remove the dataType property.

jQuery variable to php variable then use it on query

i have a problem when it comes to retrieving value from jQuery to php.i was able to get the value of my select and pass it to my php but i can't pass it back to php. here is the code...
<script>
$(document).ready(function()
{
$("select#months").change(function(event)
{
var m=$(this).val();
$.ajax({
type: 'POST',
url: "monthly_CRD.php",
data: {m: m},
success: function(){alert("updated")}
});
});
});
</script>
<div>
<select id="months">
<option value='00'>Month...</option>
<option value='01'>Jan</option>
<option value='02'>Feb</option>
<option value='03'>Mar</option>
<option value='04'>Apr</option>
</select>
<select id="years">
<?php
for($yr=10; $yr<=$year; $yr++)
{
echo "<option value='".$yr."'>".$years[$yr]."</option>";
}
?>
</select>
</div>
<?php
if (isset($_POST['m']))
{
$m = $_POST['m'];
echo $m;
} else {echo "fail";}
?>
it keeps on returning fail which means that isset is not working.
Change data: {m: m} to data: {"m":m}
Since you are looking at $_POST['m'] you need to define that key in your JSON. Currently you'd need to look inside $_POST['03'] if you selected Mar
If you mean that on page load, it returns fail, that is because on page load your $_POST array is probably empty.
If you want to know what was returned from your AJAX post, you need your success function to accept a parameter (like data) that jQuery will fill with the response to your post.
Then in the function body, you can write it to the DOM or your error console.
If you have an id to an element then just id is enough to select. Try this
$(document).ready(function()
{
$("#months").change(function(event)
{
$.ajax({
type: 'post',
url: "monthly_CRD.php",
data: { m: $(this).val()},
success: function(){
alert("updated")
}
});
});
});
$(document).ready(function()
{
$("#months").change(function(event)
{
$.ajax({
type: 'post',
url: "monthly_CRD.php",
data: '{ "m": "' + $(this).val() + '"}',
success: function(msg){
alert(msg)
},
error: function(msg) {
alert("An error happened: " +msg);
}
});
});
});
User fiddler of chrome tools to break on either success or error and check the value of the meesage property.

Categories