How to use MySQL DB data inside JavaScript function? - php

I need to populate the chart created by the JavaScript function. The chart should be populated with MySQL DB data. I have SQL query defined in myquery.php. This php code returns an array that should be used to create the chart. The question is how to execute myquery.php and get the output array that I can further use inside the JavaScript function createChartControl?
<script type="text/javascript" language="JavaScript">
function createChartControl(htmlDiv1)
{
// Draw chart
}
(function(){
createChartControl('schedule');
})();
</script>

jQuery will make your life so much easier when it comes to AJAX. If you are really against using a library, you can look at examples for xmlhttprequest, which can be used in plain javascript.
jQuery would look something like:
function ajaxCall(){
$.ajax({
url: 'myquery.php',
type: 'POST',
data: {any_var: var_value},
success: function(data) {
var returned_array = $.parseJSON(data)
createChartControl(htmlDiv1, returned_array)
}
})
}
Basically you send any data you want to myquery.php in the any_var, retrieve that value in myquery.php with the $_POST['any_var'], run your query, then json_encode the array you want to be passed back to your javascript, and finally parse your returned data in the success function to be a usable javascript object. Now you can do what you want with it, but in my example you can see I send that returned_array to your createChartControl() function (which needs to have an added parameter for your array.
Tada, ajax magic.

I strongly suggest to you to use jQuery library on JS side. ( http://jquery.com/ )
1 - Without Ajax:(If your data will be available when the page is loaded):
<script type="text/javascript" language="JavaScript">
var myData = <?php echo json_encode($myArray); ?>;
function createChartControl(htmlDiv1)
{
// your code to draw chart
// read myData a fill the chart
}
(function(){
createChartControl('schedule');
})();
</script>
2 - With ajax (using jQuery):
function loadMyData(){
$.getJSON('ajax/myquery.php', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push(val);
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
}
Useful sites:
http://php.net/manual/pt_BR/function.json-encode.php
http://api.jquery.com/jQuery.getJSON/
Parse JSON in JavaScript?

Related

Using a value from an Input, do a Select using that value, then return a json to an autocomplete

I'm new to Json, Ajax and Jquery, so this is turning out very frustrating.
I'm doing a code to autocomplete on a form using Jquery. My form consists in 4 elements:
1) Client
2) Requestor
3) Address
4) Email
So far, I can autocomplete the Client with this code:
<script type="text/javascript">
$(document).ready(function(){
$("#Client").autocomplete({
source:'getClient.php',
minLength:1
});
});
</script>
However, I need to get the next data (Requestors, Address...) using the Client's values instead of showing all the requestors and all the addresses from the database.
I've been trying for 3 hours and I just don't seem to get any data.
As an example, I've just set my Requestor input with an onclick.
<input type="text" name="Req" size="60" id="Reqt" onclick="getreq()"><br>
This was the last code attempt I've done so far:
<script type="text/javascript">
$(document).ready(function()
{
function getreq(){
//get the username
var Client = $('#Client').val();
//use ajax to run the check
$.ajax({
data: Client,
url: 'getReq.php',
type: 'post',
success: function (response) {
$("#Reqt").autocomplete({
source:'getReq.php',
minLength:1
});
}
});
}
});
</script>
And my PHP looks like this
<?php
mysql_connect("localhost","user","pass");
mysql_select_db("test");
$client = mysql_real_escape_string($_POST['Client']);
$query=mysql_query('SELECT * FROM client WHERE Clients ="'.$client.'"');
$json=array();
while($Reqt=mysql_fetch_array($query)){
$json[]=array(
'value'=> $Reqt["Requestor"],
'label'=>$Reqt["Requestor"]
);
}
echo json_encode($json);
?>
Like I said, I've been trying this for hours and I'm pretty new to Json, Ajax and Jquery, but I need to use those technologies, I would really appreciate any and all insight. Thanks in advance!

I want to use AJAX to dynamically generate layout based on the ID of a link clicked

I am attempting to use AJAX to generate PHP to be displayed inside of a div based on the ID of the link clicked. (I haven't dealt with HTML formatting yet, just want to figure this out first)
My Code:
<script type="text/javascript">
jQuery(document).ready(function()
{
$(".myClass h3").click(function(){
var clickID = $(this).attr('id'); //For sake of argument lets say id = 1.
$.ajax({
url: 'landingPage.php',
data: {ProductIDNumber: clickID},
success: function(html) {
$('#container').append(html);
}
});
});
});
</script>
I have dealt with getting the PHP to run when the url is landingPage.php?ProductIDNumber=1 and that all works properly, I just don't quite grasp how to return the resultant HTML.
Edits made and commented on.
You need to include success, which is run once the response is received, similar to;
<script type="text/javascript">
jQuery(document).ready(function()
{
$(".myClass h3").click(function(){
var clickID = $(this).attr('id'); //For sake of argument lets say id = 1.
$.ajax({
url: 'landingPage.php',
data: {
ProductIDNumber : clickID
},
success: function(html) {
// Do what you need to here with 'html'
$('#container').append(html);
}
});
});
</script>
As Alvaro said the structure of the data was also incorrect
Here's a link to the jQuery docs where you can find out more about the parameters and options you have (such as handling fails etc)
the data is wrong,
it is like this:
data: {varname: value, varname1: value},

How to check whether a div is updated?

I have got site with dynamic refreshing divs.
Source:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script>
var auto_refresh = setInterval(
function()
{
$('#loaddiv').fadeOut('slow').load('boo.php').fadeIn("slow");
$('#loaddiv2').fadeOut('slow').load('boo2.php').fadeIn("slow");
}, 1000);
</script>
But I want fadeout and fadein only if boo.php return different(updated) value than actuall div. How compare new and actuall value and do this?
P.s Sorry for bad English but I'm Polish
You'll need to write a callback function that inspects the returned data and compares it to what's stored within the div already. Additionally, the functions that show/reveal the div will probably need to be moved to the callback function as well.
Documentation is available here.
You'd have to write an Ajax function to boo.php and compare the result with the div's value
$.ajax(
{
url: "boo.php",
success: function(result)
{
if($("#loaddiv").html() != result)
{
$("#loaddiv").fadeOut("slow")
$("#loaddiv").html(result);
$("#loaddiv").fadeIn("slow");
}
}
});
You need to check the result you are getting from the ajax call and compare it with the current content. Assuming you have an element with ID MsgCount in your Ajax response and current Div Markup and you are using the value of that to compare, the below code will work
$(function() {
var auto_refresh = setInterval(function(){
var currentMsgCount= $('#MsgCount').text();
$.get("boo.php",function(data){
var resultData=$(data);
var newMsgCount= resultData.filter('#MsgCount').text();
if(newMsgCount!=currentMsgCount)
{
//content is different. Let's show it
$('#loaddiv').fadeOut('slow',function(){
$('#loaddiv').html(data).fadeIn("slow");
});
}
});
}, 1000);
});

Creating a 2-dimensional jQuery array from a 2-dimensional PHP array with AJAX

I am using jQuery, AJAX and PHP to update the contents of a drop down box on an event. My code currently triggers the event and uses AJAX to call a PHP function which goes to the database and gets the records associated with each member of the drop down.
I can currently return this 2-dimensional array (an array of records with an array of columns in each one) back to my jQuery function but I am at a loss as to how to convert the array into something which I can use.
jQuery code to call AJAX:
var element= $('select[name=elementName]');
var data = 'inData=' + element.val();
// Call AJAX to get the info we need to fill the drop downs by passing in the new ID
$.ajax(
{
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
success:
function(outData)
{
// WHAT DO I DO HERE TO CONVERT 'outData' INTO A 2-DIMENSIONAL jQUERY ARRAY??
},
error:
function()
{
}
});
PHP code:
$sqlResults= mysql_query("SELECT data FROM table WHERE id='".$_POST['inData']."'");
$outData = array();
// Fill the data array with the results
while ($outData[]= mysql_fetch_array($sqlResults));
// echo the data to return it for use in the jQuery file
echo $outData;
The code posted is working fine - I just don't know how to read 'outData' in jQuery.
Thanks in advance for any help!!
Have you looked at json_encode?
echo json_encode($outData);
This will convert it into a json object that can be read by jQuery.
your looking for json
//php
echo json_encode($outData);
//javascript
$.ajax({
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
dataType: "json",
success: function(outData) {
console.log(outData); //this will be an object just like
//your php associative array
},
error: function() {
}
});
JSON can do the trick, but why not look at it from another angle?
If you're pinging PHP to get updated info, just have PHP output the option values you want in your select box. Then use the HTML return of jQuery AJAX to .html() the result into your select element.
There's a couple of different ways to skin a cat, and I would submit that this much easier approach is going to gain you extra time to do more jQuery wizardry.
jQuery can not read the echo of a PHP array. Use json_encode before you output it:
echo json_encode($outData);
That's a format jQuery actually can parse as the response.

Submit Value With Javascript

I'm a stuck with the following function:
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
parent.removeChild($child);
}
}
</script>
x
This function deletes a child element, and its content, which works great client-side! But I am wanting to pass a value to the server, in the same instance, so the content of the element can be deleted from the mysql database too. I have no idea how to do this, so any suggestions will be very appreciated!
Notes: $child, and $parent are strings generated within the php file, that I use to give each element a unique ID.
To make your life easier, use jQuery or similar framework. Here's how you would do it in jQuery:
$(function() {
$('.delete').click(function() {
var link = $(this);
var id = link.attr('id').replace('element_', '');
$.ajax({
url: 'handler.php',
data: {
element: id
},
type: 'post',
success: function() {
link.remove();
// Or link.closest('tr').remove() if you want to remove a table row where this link is
}
});
return false;
});
});
The HTML:
Remove
And handler.php:
mysql_query("DELETE FROM `table` WHERE id = '".mysql_real_escape_string($_POST['element'])."'");
Always remember to escape database input!
If you're a total noob as you said, you probably won't understand all of this so I suggest you read something about jQuery's AJAX capabilities and about overall development using jQuery or similar JavaScript framework.
Lets say I want to delete an entity using a ID
JQUERY - $.post()
This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). Jquery post docs
On the server assuming you have an open database connection.
mysql_query("DELETE FROM TABLE WHERE ID = ".$_POST['ID']);
more on mysql_query found here
EDIT:
So the following will only remove the element when the ajax post is complete. Note the first arg is the url to the script that will take the action , second is the data to be sent, in this case the ID post value will be {child.id} and the third is a anon inline callback function that will take action to remove the element client side.
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
$.post('{URLTOSCRIPT}', 'ID=$child.id',function () { parent.removeChild($child); });
}}
</script>
When you call the function, you'd want to put your PHP variables in tags like so:
<?php echo $parent; ?>
and
<?php echo $child; ?>
In the function definition, you will want to get rid of the PHP style variables and use something like:
function removeElement(parentDiv, childDiv) {
//CODE
}

Categories