PHP code called via JQuery stopped working - php

Initially, I used a .js file that contains AJAX functions to call a .php file. The .php file contains code to dynamically populate a DropDown based on certain parameters passed via QueryString.
Everything works fine with the above method. But now I want to populate the DropDowns on page load and so want to use JQuery instead of my old method. I tried following code, but it is not filling the DropDown.
$.get("../Lib/filldropdown.php",
{ param1: "divMemberOf", param2: "inMemberOf", param3: "categorymaster" });
Below is the code of the .php file:
<?php
require("dbconnection.php");
require("dbaccess.php");
$dropdownControlName = $_GET['DropDownControlName'];
$query = ".....";
dbconnection::OpenConnection();
$result = dbaccess::GetRows($query);
?>
<select id="<?php echo $dropdownControlName; ?>" name="<?php echo $dropdownControlName; ?>">
<option>Select from the list</option>
<?php while($row=mysql_fetch_array($result))
{ ?>
<option value="<?php echo $row[0]; ?>"><?php echo $row[1]; ?></option>
<?php } ?>
</select>
Please note that the above JQuery code passes three parameters, but I have used only one in the PHP code above. I am going to use two parameters later. The above PHP code is perfectly working with my old AJAX method.

You are making an AJAX request using GET, but you are not adding a callback function to actually handle the returned HTML. It vanishes in thin air.
Check out the JQuery AJAX documentation on GET for a complete example.
Your call would have to look something like this:
$.get("../Lib/filldropdown.php",
{ param1: "divMemberOf", param2: "inMemberOf", param3: "categorymaster" },
function(data) { $('#myDivID').html(data); }
);

You either need to add a callback function, or the .load method might be more appropriate since you just want to inject the results from that PHP call into the page:
$("#someContainer").load("../Lib/filldropdown.php",
{ param1: "divMemberOf",
param2: "inMemberOf",
param3: "categorymaster" });
You just need some DIV or something to be a placeholder to inject the select box into.

You are not specifying the key correctly for your php to work as-is. In your javascript you are creating a request like this:
param1=divMemberOf&param2=inMemberOf&param3=categorymaster
I would think you need one of those parameters to be named DropDownControlName since you are using it as the id for your newly created select input. You might also check param2 and param3 since you are likely using those in your query.

Related

Outputting variable value into innerHTML with JQuery and then storing it in PHP variable

Essentially, I'm attempting to capture the value of a HTML drop down menu and call a php function (i.e., print_wp_cart_button_for_product) with the user selected row. I have created a JQuery function which is called onchange, but have encountered several problems. By using alerts, I'm sure that the function is called and that the value is stored in currentrow. Additionally, by using the firefox web console, I know that order.php is called with the appropriate parameters. Originally I was using ajax success method, but the function was not being called, so I switched it to the complete method, which at least solved the fist problem. The second issue I'm dealing with involves storing the variable currentrow in the innerHTML of test. When I changed $('#test').html(currentrow) to $('#test').html("Complete") the string was outputted to the screen, as I would expect, but I've been unable to do so dynamically with the value of the currentrow. The last problem I've found involves saving the value of the test div tag into a php variable. I've attempted to use $_GET to capture the value and subsequently call my php function, but have had no luck.
<div id="test">
</div>
<script type = "text/javascript">
function productchange()
{
var currentrow = $('#productcategory1').val();
//alert(currentrow);
$.ajax({
type: "GET",
url: "http://www.example.com/wp-content/themes/themeX/order.php",
data: {'rownum': currentrow},
complete: function(currentrow){
//alert('COMPLETE');
$('#test').html(currentrow);
//$('#test').html("Complete");
}});
return false;
}
</script>
<?php $rownum = $_GET['test']; ?>
<?php echo print_wp_cart_button_for_product($products[$rownum]["Product"], $products[$rownum]["Price"]); ?>
Order.php
<?php
$rownum= $_GET['rownum'];
echo "Row number = $rownum";
?>
It seems like your <div id="test"></div> should really be <input type="hidden" id="test" name="test"/> within a <form>
Using a form element of some kind is the only way you can natively pass a value back to the server on submit.
In any case, the inline PHP code after your HTML will only work after submit of a form.
Here is a snippet of code that will submit a hidden form field to the PHP page allowing you to store the value in a PHP variable. First, do something like this on the main page which has your javascript.
<form method="post" action="storevar.php">
<input type="hidden" name="jsvar" id="jsvar" value="" />
</form>
Then, after you have calculated the value that variable should be in javascript, update the value of this hidden form field with Javascript/JQuery, like this:
function productchange() {
var currentrow = $('#productcategory1').val();
$("#jsvar").val(currentrow);
$.post('storevar.php', {jsvar: currentrow}, function(data) {
// do any additional coding with the result if need be
}
});
return false;
}
Then you could do something like this in storevar.php. Notice I'm storing it in a session so that it can be retrieved in other pages as well if you need to.
session_start();
$currentrow = $_POST['jsvar'];
$_SESSION['currentrow'] = $currentrow;
I hope that helps you. If you need any additional help, or if I've misunderstood something, please let me know and I'd be happy to help.

How to update MYSQL field without refreshing page in PHP?

I wish to update MYSQL data using text instead of using submit button.
Admin will choose option from combobox and then click at save to update the MYSQL records.
How to do this using AJAX or jquery?
My coding:
<?php
include('config.php');
$per_page = 9;
if($_GET)
{
$page=$_GET['page'];
}
//get table contents
$start = ($page-1)*$per_page;
$sql = "SELECT bookingID,eventinfo.eventTitle,boothAlias,testbook.bstatus,date, testbook.username, customer.companyName, customer.contactName from eventinfo, testbook, customer where testbook.username=customer.username AND testbook.eventID=eventinfo.eventID order by date desc limit $start,$per_page";
$rsd = mysql_query($sql);
?>
<form method="post" name="form">
<table width="800px">
<?php
//Print the contents
while($row = mysql_fetch_array($rsd))
{
$id=$row['companyName'];
$contactName=$row['contactName'];
$eventTitle=$row['eventTitle'];
//$phone=$row['phone'];
$date=$row['date'];
$status=$row['bstatus'];
$booth=$row['boothAlias']
?>
<tr><td style="color:#B2b2b2; padding-left:4px"><?php echo $id; ?></td><td><?php echo $contactName; ?></td>
<td><?php echo $eventTitle; ?></td><td><?php echo $booth; ?></td><td><?php echo $date; ?></td><td><select name='status' id='status'>
<option value='-1'>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select></td><td><a href=#>save</a></td>
</tr>
<?php
} //while
?>
</table>
</form>
image
This is actually really simple using jQuery. First, you have to create another PHP script that will actually run the UPDATE code. I'm not sure how much you know about AJAX requests, but you can essentially think of them as your browser opening a new tab in the background, sending the request and returning/parsing the response with JavaScript.
So, I'd write a PHP script that you can request (maybe "update_field.php" or "update_field_ajax.php") which does the actual updating. Write this script as you would if a form were being submitted from another page (ie it'll have POST and GET variables, validations, etc). There will be two main differences. First, you'll pass in the POST params with jQuery and second you won't return HTML (you can return HTML if you want - but if you're doing a simple update you really only need some sort of success or fail/error message response). I'd consider JSON for the response type. So, the PHP script is up to you to write, you'll write it just as you normally.
Next, you'll use jQuery to grab the data (GET/POST params) from the page and make a request to the PHP script you created. This isn't all that bad either. I'm not sure what you mean by "using text instead of a submit button" other than you don't want to use a submit button so I'll explain this in a somewhat abstract way. In order to get the AJAX call to run you must have something trigger it. This will be an event on the page, and that event will call a function that fires the AJAX request. Google around for information on jQuery events, but essentially when an event is fired it calls a function that you define. When that function is called we can use jQuery's post() method to create an AJAX post request. This method call will look something like:
jQuery.post('url of your script', {postVarOne: jQuery('some elt').val()}, function () {success function}, 'json');
The details of jQuery.post can be found at http://api.jquery.com/jQuery.post/
So basically write a PHP script as you normally would that returns something other than HTML signifying success/fail or a response message(unless you need to inject HTML right into the page) and then use jQuery.post (or jQuery more generic jQuery.ajax method) to have your browser request that script with the GET/POST vars you define and parse the response.
Finally, check out these tutorials for more information/code examples.
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/

how to pass a php values to javascript?

here is the code??
posting code:
$.post('get.php',{selected:"aaaa"},function(return){alert(return);});
when i check the values of "selected" value using
<?php
$r=$_POST['selected'];
echo $r;
?>
is displays the value "aaaa" correctly..
this code works fine...
<?php
$r=$_POST['selected'];
?>
var answer="<?php echo "welcome" ?>";
when we echo the value"welcome" it is stored in the variable answer.and i could print that...
but when i put like this....
<?php
$r=$_POST['selected'];
?>
var answer="<?php echo $r ?>";
an empty value is stored in answer... and nothing gets displayed....
whether specifying $r inside " " is not right... how to specify that......
Assuming that the php code you are showing, is located in get.php, there is no use of using javascript in that same file. If you want to get the returned value in a javascript variable in your page, you need to use the first php snippet and use the return value in your .post function:
javascript in original page:
$.post('get.php',{selected:"aaaa"},function(data){
var answer = data;
});
get.php
<?php
$r=$_POST['selected'];
echo $r;
?>
$_POST['selected'] is probably empty to start with. Make sure you're sending a nonempty value for selected, and that you're using POST. (The easiest way is to look in your browser's developer tools for the initial request).
Note that directly outputting user input into the page introduces a Cross-Site Scripting Vulnerability: The input "; alert("evil"); can show that. Assuming you're using UTF-8 all around, you can write:
var answer = <?php echo json_encode($_POST['selected']); ?>
Also, there are often better ways to transfer data from php to JavaScript, including XHR requests/JSON or data-* attributes.

How to transfer select value to php?

I want to display the photos according to the album selected. But, I don't want to post the page, I want to just change the div.
This is my script:
<script type="text/javascript">
function replaceContent(divName, contentS) {
document.getElementById(divName).innerHTML = <?php echo get_pictures_from_album($fb, $albums, contentS); ?>;
}
</script>
And this is the select tag that invokes it:
<select name="album" size= "1" style="width:210;" onchange="replaceContent('photos', this.options[this.selectedIndex].value);">
<?php get_albums_select_list($albums); ?>
</select>
<div id = "photos">
<?php echo get_profile_pictures($fb, $albums); ?>
</div>
I understand from a reading that I have done that the problem might be connected to javascript Vs php variable types.
Please advise.
Looks like you are looking for an AJax call to an PHP script that retrives the data for the appropriate album selected and THEN update the div with the callback function.
Ajax + PHP basics
You are mixing Clientside and Serverside Code here. The function replaceContent is called after the page (and the php code) was loaded. You would need an Ajax Call for that if you need more information about that:
Ajax Tutorials on Google
What you are doing is not possible because PHP code runs before (on the server because PHP is server-side language) javascript code.
You will have to resort ot AJAX for that.

Need help with jQuery to clone form dropdown (dynamic dropdown)

I am using PHP to generate dynamic dropdown, the dropdown list items are fetched from database.
Here's the php code for that and it works.
<select name="title[]" id="title">
<?php $categories = Category::find_by_cid(5); foreach($categories as $category): ?>
<option value="<?php echo $category->name; ?>"><?php echo $category->name; ?></option>
<?php endforeach; ?>
</select>
What i want to do is, Using jQuery whenever a link with id AddNew is clicked, a new dropdown should appear below that, containing same values.
Also, is there any way to execute php code inside javascript??
ex :
<script>
var name = "<?php echo $user->name; ?>";
</script
To clone elements, you can use jQuery's .clone() method (obviously):
$('#addNew').click(function() {
$('select.title').after($('select.title').clone());
});
Note that ID's should be unique on the page, if you are going to clone the select element, give it a class instead of ID.
And yes, you can "use" PHP in JavaScript, provided that the file is processed with PHP. Just note that you are not actually accessing PHP with JavaScript, but rather creating JavaScript files dynamically.
Use jQuery .clone() method.
Also, is there any way to execute php code inside javascript??
Not really, no. PHP is executed server-side, so in the example you provided:
<script>
var name = "<?php echo $user->name; ?>";
</scrip>
That will turn out to be:
<script>
var name = "Josh";
</script>
at run-time, when the javascript has access to it. The php code is executed, then rendered to html where the javascript finally sees it. What you are doing is dynamically creating javascript rather than executing php code.

Categories