Jquery ajax retrieving text (numbers) from php mysql - php

I've just started learning Jquery and I'm trying to post and retrieve some data with Ajax. The data that i wanna extrapolate is some simple text (no json), more specifically numbers. So I wrote this:
$.ajax({
url : 'finproj.php',
type : 'POST',
data : 'p=' + devidproj,
success : function(resultaat) {
var lengtebalxkx = Math.floor(100*resultaat/<?php echo $number; ?>);
$(".ongelezendonatiesproj").animate({opacity:1}, 300).show();
if(lengtebalxkx > 120)
{
$(".ongelezendonatiesproj").width(120);
}
else
{
if(lengtebalxkx < 1)
{
$(".ongelezendonatiesproj").width(2);
}
else {
$(".ongelezendonatiesproj").width(lengtebalxkx - 10);
}
}
},
});
devidproj is a number, as is $number. I tried adding dataType : 'text',
But that didn't work.
The php-file which I'm trying to retrieve the data from, is:
<?php include('config.php');
$pid = $_REQUEST['p'];
$nieuwgeld = mysql_query('SELECT bedrag, aantal, projectid FROM donaties WHERE projectid="'.$pid.'"');
while($nieuwebed = mysql_fetch_assoc($nieuwgeld)) {
$plusbedrag = $nieuwebed['bedrag'] * $nieuwebed['aantal'];
$nieuwebedragen = $nieuwebedragen + $plusbedrag;
}
if($nieuwebedragen<>0) {echo $nieuwebedragen;} ?>
The php-file works fine.
I think I missed a comma or something in the Jquery-script but I can't seem to see what's wrong with it :s I've tried debugging it with alert() but that didn't work.

use
data : {p:devidproj},
insted of
data : 'p=' + devidproj,

Use the following data on your ajax request:
data : {p: devidproj}
Note that there should be no quotes on p.
You should also parse the result on your Ajax request as integer thru parseInt() function since that's suppose to be a number. JS will parse it as string by default if not added.
var lengtebalxkx = Math.floor(100*parseInt(resultaat)/<?php echo $number; ?>);

Related

How to send PHP variables and retrieve them with Jquery (without echo)?

I'm building a search function to retrieve XML data for a google map.
In addition to that, I want to display how many results were actually found.
I thought about doing an echo inside the actual document, however that might mess with my marker data. How would I take a PHP variable and retrieve it in Jquery after a success call?
If my PHP looked like this:
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
And Jquery like this:
$.ajax({
type: "POST",
url: "MapSearchxml.php",
data: {
dataFromDate: FromDate,
//lalala
dataHasPatio: HasPatio
},
beforeSend: function (html) { // this happens before actual call
$("#results").html('Please Wait');
$("#searchresults").show();
$(".phpFromDate").html(FromDate);
},
success: function (data, status, jqXHR) {
//Success?
},
dataType: 'xml'
});
Might find it easier to create array in php and send JSON. At client is easy to loop over response object/array
$output=array('status'=>'', 'results'=>array());
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
if( $num_rows){
$output['status']='ok';
/* push row data to $output['results'][]; in while loop*/
}else{
$output['status']= 'No results';
}
echo json_encode( $output);
Then in jQuery:
success:function( data){
if (data.status != 'No results' ){
/* count array length*/
var count= data.results.length;
/* loop over data.results array*/
}
}
/* change dataType to "json"*/
I forgot about count and added it in jQuery...can also add a count property to the $output php array and use $num_rows to populate
Just trying out a JSON example for you, this has echo but you can do complex things with it?
Not sure if that is what your after? I get that you don't want to do echo on each variable, and you wont if using JSON.
<?php
$simple = 'simple string';
$complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
var simple = '<?php echo $simple; ?>';
var complex = <?php echo json_encode($complex); ?>;
</script>
You see, what AJAX gets on success is an html code. If you AJAX a complete html page you will get it back, starting with <html> and ending with </html>. You can just make a special markap on your return html data, like [sepcial_info : 'INFO'] or somthing and then just to filter it.
Okay, I needed a bit to decipher your question, probably I'm still wrong, let's try:
What you try to do is not technically possible with what you have in mind. In short: If you do one Ajax request, you return one response. The moment the success function is called, your PHP script is already gone. So you can only pass one return value.
However what you can do is, that you make that return value a nested one, e.g. containing two parts:
The XML document you already returned
The count
That is probably your solution. If you ask how, I would add the count as a namespaced value to the XML and then process it with javascript.
As you have not shown any code here, I can not give a quick example (and I leave that as a pointer for your future questions) for your case. Add a namespace element, like an attribute is pretty simple with DOMDocument in PHP.

Populate Select list Menu though Ajax Jquery

Before anybody says this is a duplicate of this and that question, let me assure you I have tried the solutions there and I have failed. I am using a solution offered in this website to come up with my solution and I believe I am 90% done except for one error. I want to display a list of all codes that have a certain common ID associated with them.
Here is my PHP code that I am using to get a list of codes
<?php
$budgetcode=$_POST['budgetcode'];
//$budgetcode=2102;
$selectcodes="SELECT * FROM tblbudget_codes WHERE T1 = $budgetcode";
$query=$connection->query($selectcodes);
$count=$query->num_rows;
if($count < 1)
{
die('0');
}
else{
while($row=$query->fetch_array()){
$T1=($row['T1']);
$T2=($row['T2']);
$T3=($row['T3']);
$T4=($row['T4']);
$optionValue = $T1."-".$T2."-".$T3."-".$T4;
echo json_encode("<option>$optionValue</option");
// echo json_encode('1');
}
}
?>
Here is the ajax call i am using to fetch the codes
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(data!='0')
{
$("#budgetcode").html(data).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
//alert(budgetid);
})
The problem here is that jquery does not understand the data it is receiving if it is not numeric. E.g if I comment out the json_encode('1') and put random html code instead of data in my success part, I get results displayed in my browser. Can anybody tell me why jquery is only recognizing numeric values that are being echoed from PHP and not varchar values. Using jquery 1.4.2. Any help appreciated.
EDIT
I have managed upto some point and now i am stuck. I have used John's Answer and here is my jquery code. i just need to split the array and append each element to a variable one at a time like here
here is the code. Somebody please tell how I split (data). i can alert it but it is comma seperated. Just need to get the individual items append them to variable html and then display it.
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(!$.isEmptyObject(data))
{
//alert (data);
// alert(split (data))
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) {
html += '<option>' +data+ '</option>';
}
$("#budgetcode").html(html).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
I would skip JSON altogether:
PHP
echo "<option>$optionValue</option>";
Everything else should work.
Finally figured it out. Here is the php code
$selectcodes="SELECT * FROM tblbudget_codes WHERE T1 = $budgetcode";
$query=$connection->query($selectcodes);
$count=$query->num_rows;
if($count < 1)
{
die('0');
}
else{
while($row=$query->fetch_array()){
$data[] = $row;
}
echo json_encode($data);
}
?>
Here is the jquery code
$.post("Functions/getbudgetcodes.php",{budgetcode:budgetid},function(data){
if(!$.isEmptyObject(data))
{
//alert (data);
var html = '';
var joiner='';
var len = data.length;
for (var i = 0; i< len; i++) {
joiner=([data[i].T1,data[i].T2,data[i].T3, data[i].T4].join('-'));
//alert(joiner);
html += '<option>'+joiner+'</option>';
}
$("#budgetcode").html(html).show();
$("#result").html('');
}
else{
$("#result").html('<em>No codes found. Contact Administrator</em>');
}
},'json')
Had to use join to join the multiple codes using a dash. Hope this helps. The PHP part and part of the jquery was inspired by this question
FWIW, for populating select lists I usually use the following jQuery code:
// populates select list from array of items given as objects: {
name: 'text', value: 'value' }
function populateSelectList(parent, items) {
parent.options.length = 0;
if (parent.options.length === 0) {
parent.options[0] = new Option("Please select something...", "");
}
$.each(items, function (i) {
if (typeof (this) == 'undefined') { return; }
parent.options[el.options.length] = new Option(this.name, this.value);
});
}
and to call the above function i pass the results of an ajax call using the map method where #select is the selector for the parent select element. I am setting the Text property to the name and Value to the value but that should change according to the objects returned by the ajax call (e.g. assuming the returned objects have a Value and Text properties).
populateSelectList($('#select').get(0), $.map(results, function
(result) { return { name: result.Text, value: result.Value} }));

Passing array with ajax - can't print

I hope this problem is very simple, I can't figure out the solution myself it seems. Been trying and googling for hours, driving me nuts :) Ok, so I have a drag'n'drop + sortable (using scriptaculous and prototype for your information) on my index.php. I use this code to send the items dropped in a div using this code:
<script type="text/javascript">
//<![CDATA[
document.observe('dom:loaded', function() {
var changeEffect;
Sortable.create("selectedSetupTop", {containment: ['listStr', 'selectedSetupTop'], tag:'img', overlap:'vertical', constraint:false, dropOnEmpty: true,
onChange: function(item) {
var list = Sortable.options(item).element;
$('changeNotification').update(Sortable.serialize(list).escapeHTML());
if(changeEffect) changeEffect.cancel();
changeEffect = new Effect.Highlight('changeNotification', {restoreColor:"transparent" });
},
onUpdate: function(list) {
new Ajax.Request("script.php", {
method: "post",
parameters: { data: Sortable.serialize(list), container: list.id }
onLoading: function(){$('activityIndicator').show(), $('activityIndicator2').hide()},
onLoaded: function(){$('activityIndicator').hide(), $('activityIndicator2').show()},
});
}
});
});
// ]]>
</script>
I've been using this code before so I "kind of know" it will send me data to my script.php page. selectedSetupTop is my div containing the elements. Don't mind about the notification and the activityIndicator thingy. My script.php page looks like this for the moment:
parse_str($_POST['data']);
for ($i = 0; $i < count($selectedSetupTop); $i++) {
$test .= $selectedSetupTop[$i];
}
echo "<script>alert('$test');</script>";
I can't seem to get any output in the alert message, it's just blank. The purpose of the script.php is to update a row in a database and it will look kind of like this:
$sql = mysql_query("UPDATE table SET row = '$arrayInStringFormat' WHERE id = '1'") or die(mysql_error());
where the $arrayInStringFormat is a conversion of the array $selectedSetupTop to the format (1, 2, 3, 4). I guess I'll solve that using implode or something, but the problem is parsing the array $selectedSetupTop. I'm not it passes between the pages at all, really appreciate help! Tell me if I need to explain further.
Thanks in advance!
''''''
EDIT 1
If it will help, I used this code before that I know will send me the data and use it. Notice I don't wanna do my task like the way I do below:
$querySetup = $_GET["s"];
parse_str($_POST['data']);
for ($i = 0; $i < count($selectedSetupTop); $i++) {
$sql = mysql_query("UPDATE " . $querySetup . " SET orderId = $i, hero_selected = 'n' WHERE imageId = $selectedSetupTop[$i]") or die(mysql_error());
}
''''''
EDIT 2
So it does parse, but I still have the problem I can't print it. I wanna implode the array somehow.
Not sure how AJAX works in Scriptalicious/Prototype, but you don't seem to be getting the data from the AJAX call. In jQuery it would be something like this where the data you receive from the script is returned as the argument of the function.
onLoaded: function(msg){
$('activityIndicator').hide(),
$('activityIndicator2').show(),
alert(msg)
}
Secondly, you can't echo a PHP array, you have to encode it to JSON:
echo json_encode($test);

Jquery .post() return array

Sorry for the bad title, but I don't know how to name this. My problem is that whenever I pass a value from a select box I trigger this jquery event in order to check on the check boxes. Bassically I echo $res[]; at selecctedgr.php. Do I need to use json? and how can I do this?
Mainpage:
$("#group_name").change(function(){
var groupname = $("#group_name").val();
var selectedGroup = 'gr_name='+ groupname;
$.post("selectedgr.php", {data: selectedGroup}, function(data){
$.each(data, function(){
$("#" + this).attr("checked","checked");
});
},"json");
});
PHP (selectedgr.php):
<?php
include_once '../include/lib.php';
$gr_name=mysql_real_escape_string($_POST['gr_name']);
$sqlgr = "SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=".$gr_name;
$resultgr = sql($sqlgr);
while($rowgr = mysql_fetch_array($resultgr)){
$res[] = $rowgr['ACT_ID'];
}
echo $res[];
?>
Change the last line in your PHP sample (echo $res[];) to:
echo json_encode($res);
json_encode() manual page will tell you more.
Also as #Unicron says you need to validate the $gr_name variable before passing it to your SQL statement.
You could use:
if(isset($_POST['gr_name'])) {
$gr_name = mysql_real_escape_string($_POST['gr_name']);
}
See: http://php.net/manual/en/function.mysql-real-escape-string.php for more information in the PHP manual.
You can use json_encode function to convert arbitrary data into JSON. Assuming that you want to return an array of strings, here is how you will use json_encode:
<?php
include_once '../include/lib.php';
$res = array(); // initialize variables
$sqlgr = sprintf("
SELECT ACT_ID
FROM PRIVILLAGE
WHERE MAINGR_ID=%d
",
$_POST['gr_name']
); // only select those columns that you need
// and do not trust user input
$resultgr = sql($sqlgr);
while($rowgr = mysql_fetch_array($resultgr)){
$res[] = $rowgr['ACT_ID'];
}
echo json_encode($res); // use json_encode to convert the PHP array into a JSON object
// this will output something like ['foo', 'bar', 'blah', 'baz'] as a string
?>
On the client side you can use jQuery.post method, like this:
<script type="text/javascript">
$("#group_name").change(function () {
$.post("selectedgr.php", {
gr_name: $(this).val()
}, function (data) {
// console.log(data);
// jQuery will convert the string "['foo', 'bar', 'blah', 'baz']" into a JavaScript object
// (an array in this case) and pass as the first parameter
for(var i = 0; i < data.length; i++) {
$("#" + data[i]).attr("checked", "checked");
}
}, "json");
});
</script>
If you want to use JSON then just use echo json_encode($res);
But I don't really understand what you'll gain if your code is working now, since you'll still have to do some processing in the Javascript to handle the result.
I found my major problem as below
instead of (before):
$.post("selectedgr.php", {data: selectedGroup}, function(data){
do this (after):
$.post("selectedgr.php", selectedGroup, function(data){
Forgive my bad. Ahh ya guys, regarding the escaping on mysql actually #group_name is not any input field but a select box. Appreciate for every comment, suggestion and guide.
Eric.

How do I use php to feed data to jQuery autocomplete?

I'm trying to build a form where certain text fields and text areas have autocomplete.
I've used the formidable plugin for wordpress to build my form. I'm using the jQuery autocomplete plugin for the autocomplete part.
The code looks like this:
<script>
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing Manipulation CSS Events Effects Ajax Utilities".split(" ");
$("#example").autocomplete(data);
});
</script>
So basically I need to use php to pull data from the mysql database and feed it to that data var. I'm a php newbie, so I'm not sure how to do this. A coder who works on the formidable plugin suggested the following code for the var data part:
<?php
global $frm_entry_meta;
$entries = $frm_entry_meta->get_entry_metas_for_field($field_id, $order='');
?> //db_frm_entry_metas is the name of the mysql db that stores the values for every field from the form. I suspect get_entry_metas_for_field is a function added by the formidable plugin. $field_id is the id for a given field on the form.
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>;
<?php } ?>
I tried to run this code with an id number in the place of $field_id, but it didn't work. I'm stuck here.
I can understand most of the code, except for this part:
var data = new Array();
<?php foreach($entries as $value){ ?>
data[] = <?php echo $value ?>
I don't get what the data[] is doing there... should the php be feeding the data to the var data= line?
I have around 15 form text/textarea fields, each of which needs to pull data associated with its given field_id. Unless there's an easier way to do this, this means I'll have to write 15 scripts, each with a particular $field_id and jQuery object with field's css selector.
Any help getting this to work would be much appreciated!
The coder is wrong, this:
data[] = something;
will cause a syntax-error in JS, it's a PHP-shorthand for pushing members to an array and doesn't work in JS.
Try this:
data.push(unescape('<?php echo rawurlencode($value); ?>');
According to the autocomplete docs, you can pass a url as the data parameter. That being said, do something such as the following:
<?php
// --- PLACE AT VERY TOP OF THE SAME FILE ---
$search = isset($_GET['q']) && !empty($_GET['q']) ? $_GET['q'] : null;
if (!is_null($search))
{
$matches = Array();
// some search that populates $matches based on what the value of $search is
echo implode("\r\n",$matches);
exit;
}
?>
then, in your jQuery code replace the .autocomplete(data) with .autocomplete('<?php echo $_SERVER['PHP_SELF']; ?>');
your jquery will be something like this
$("#example").change(function(){
$.ajax(
{
type: "POST",
url: "php_page.php",
data: "data=" + $("#example").val(),
beforeSend: function() {
// any message or alert you want to show before triggering php_page.php
},
success: function(response) {
eval(response);
// print your results
}
});
});
in your php page after getting all info echo the results like this.
echo "var result=" . json_encode($results);
then eval(response) jquery function will give you javascript variable result with your results in it.
Hope this helps...

Categories