I have this function which gets a value from a slider and I need to send it to the server. I call the function which gets the parameter and works fine but the post function is not working inside.
How is it possible to call a jQuery function inside another function? Is there a better way to do this?
function process_decision(slider_value) {
var selectedData = {};
selectedData['pick_pack_point'] = slider_value;
selectedData['gameID'] = <?php echo $booxuser->game->id?>;
selectedData['teamID'] = <?php echo $booxuser->team->id ?>;
selectedData['roundID'] = <?php echo $booxuser->game->getRoundToBePlotted() ?>;
$.post('index.php',
{
'option': 'com_maximulation',
'task': 'max_decision_pickpack.pickpack',
'data': selectedData,
'<?php echo JSession::getFormToken(); ?>': '1'
},
function (response) {
var response_data = JSON.parse(response);
document.getElementById("loanResultDiv").innerHTML = response_data['data']['first'];
},
'text'
);
}
Try using jQuery instead of $, if there is another library imported, the $ could be conflicted.
Related
I'm creating one Graph chart using Google APIs I used Java Script source from Google. In PHP I'm using while loop where I fetch some array row using query, this mysql query works fine, and values of fetched array are also correct (When I echoed that in PHP) but problem is that how do I pass this values to JavaScripts function?
My PHP code is as follows :
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
echo $graphCount; // This works
echo $graphMonth;
}
This gives me in result of two rows, each contains two values listed below:
Now I want to pass this above values to Java script function so that it draws Graph chart for me, my javascript code is as follows:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount] // Here I have to place PHP values !
]);
}
So how to pass this values to JS ???
Try the below code,
In PHP
$i = 0;
while ($graph_result = mysqli_fetch_row($graph))
{
$graph_values[$i]["count"] = $graph_result[0];
$graph_values[$i]["month"] = $graph_result[1];
$i++;
}
In script,
<script>
<?php foreach($graph_values as $key){ ?>
drawChart('<?php echo $key["count"]; ?>', '<?php echo $key["month"]; ?>');
<?php } ?>
function drawChart(graphCount, graphMonth) {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[graphMonth, graphCount]
]);
}
</script>
<?php while ($graph_result = mysqli_fetch_row($graph))
{
?>
<script>
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'users'],
[<?php echo $graph_result[0]; ?>, <?php echo $graph_result[1]; ?>]
]);
}
</script>
<?php
}
?>
I don't know if it is best practice or not..
You can use json to do that.
In your while loop, build an associative array and encode it in json:
$jsonArray = array();
while ($graph_result = mysqli_fetch_row($graph))
{
$graphCount = $graph_result[0];
$graphMonth = $graph_result[1];
$jsonArray[] = array($graphCount, $graphMonth);
}
echo '<div id="json">' . json_encode($jsonArray) . '</div>';
And then recover it in your javascript:
var json_data = JSON.parse(document.getElementById('json').innerHTML);
function drawChart(json_data) {
var data = google.visualization.DataTable();
data.addColumn('number','Months');
data.addColumn('number','users');
data.addRows(json_data);
}
I have a PHP array of values. I loop through it, make ajax calls to the server by iterating through a for loop (I totally understand that making ajax cals in a for loop is not a great idea. Any suggestions/pointers to doing this a bette way would be awesome no doubt. I'd like to seek an answer to this question however please.). The data from the server takes different times based on what is to be processed & returned.
The problem I have is the showCustomerUsageChart function call doesn't get invoked at all at any stage. I tried debugging this by setting a breakpoint on this function's entry & see that there is no call made to it at all. However, I can see that the JSON data is being returned by the server at different points in time upon the respective data being available. I understand I've implemented this incorrectly, no doubt.
AJAX world is not all too familiar to me. I have looked up quite a few questions in this forum, but, kind of struggling to put the pieces together.
Could I request help to achieve what I'm after please. I'd be highly grateful to any help.
<script>
var ajaxurl = 'myDbHandler.php';
<?php for ($k = 0; $k < count($propertyCustomer); $k++) { ?>
data = {
'param1': paramFromUser1,
'param2': paramFromUser2,
'param3': paramFromUser3,
'lookUpParamId': "<?php echo $k ?>"
};
$.post(ajaxurl, data,function (response) {
var resp = $.parseJSON(response);
showCustomerUsageChart(
"<?php echo $propertyCustomer[$k][0] ?>",
"<?php echo $propertyCustomer[$k][1] ?>",
"<?php echo $propertyCustomer[$k][2] ?>",
"<?php echo $propertyCustomer[$k][3] ?>",
resp,
);
});
<?php } ?>
</script>
So here's one way to go about it instead, I avoided using php in javascript so the code and markup are cleaner.
To simulate the lag coming from your queries I did this:
myDbHandler.php:
$number = rand(2, 11);
sleep($number);
echo 'success after ' . $number . ' seconds';
The original .php file now looks like this (test.php):
<?php
// Array filled with testdata:
$propertyCustomer = array(
array('value1', 'value2', 'value3', 'value4'),
array('value1', 'value2', 'value3', 'value4'),
array('value1', 'value2', 'value3', 'value4')
);
// Make a string that html can handle and also encode the array above to a jsonString:
$json = htmlentities(json_encode($propertyCustomer));
?>
<!-- Echo the string as data-attribute -->
<div id="holdingElement" data-array="<?php echo $json ?>"></div>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="test.js"></script>
I seperated js from markup, because I can't stand ugly code (test.js):
$(document).ready(function () {
// Get the array from the element:
var phpArray = $('#holdingElement').data('array');
// Console.log for testing:
console.log(phpArray);
// Loop through the array with the jQuery each function:
$.each(phpArray, function(k, phpArrayValue){
// The makeCall function returns a ajaxObject so the object gets put in var promise
var promise = makeCall(k);
// Now fill the success function in this ajaxObject (could also use .error() or .done() )
promise.success(function(response){
// When success, call the function and use the values out of the array above
showCustomerUsageChart(
phpArrayValue[0],
phpArrayValue[1],
phpArrayValue[2],
phpArrayValue[3],
response
);
});
});
});
function makeCall(paramId) {
// Just testdata:
var paramFromUser1 = 'val1';
var paramFromUser2 = 'val2';
var paramFromUser3 = 'val3';
// Use ajax instead of $.post to use the success function, and return this ajaxObject
return $.ajax({
url: 'myDbHandler.php',
type: 'post',
data: {
'param1': paramFromUser1,
'param2': paramFromUser2,
'param3': paramFromUser3,
'lookUpParamId': paramId
}
});
}
// Function to log the results from the ajax call:
function showCustomerUsageChart(val1, val2, val3, val4, response) {
console.log(val1, val2, val3, val4, response);
}
I hope this makes any sence, and that it works for you!
Your code is faulty there:
showCustomerUsageChart(
<?php echo $propertyCustomer[$k][0] ?>
You have to put a "," after the PHP closing tag.
I don't know how to make a script for sending multiple variables from external php to javascript (jQuery)
For exemple:
<?php
$test = "tets"; -->this, I want something this, no echo
$dock = "dock"; --
echo $test; -->no, I don't want echo in PHP script
echo $dock; -->no, I don't want echo in PHP script
?>
and JS
<script>
function(){
$.post("url", {Some_Thing: "Some_Thing"}, function (data) {
alert(data); --> no, I don't want echo in PHP script
alert($test); --> this, I want something this, no echo
alert($dock);
}
}
</script>
Use a data structure, e.g:
<?php
$data = array('test', 'dock');
echo json_encode($data);
Then in your JS
$.post('url', {...}, function (data) {
alert(data[0]);
}, 'json');
^^^^^^^^--- tell jquery you're expecting back some json
you can just output your data in JSON format and then load the data to JavaScript using ajax like so:
<?
$arrayWithData = array('data1' => 123, 'data2' => 555);
echo json_encode($arrayWithData);
then call load the data using ajax:
$.ajax({
'url' : 'php-data-script.php',
'method' : 'get',
'dataType' : 'json'
}).done(function(data) {
// do whatever you want with the data
console.log(data);
});
I have a php code (no functions, just direct code) which queries a data base stores values
in an array and returns the array
<?php
//Query the database and fetch some results
$array["min_date"] = $arr['min(date)'];
$array["max_date"] = $arr['max(date)'];
$array['query'] = $query;
echo $arr['min(date)'].'</br>';
echo $arr['max(date)'];
return $array;
?>
this is my jquery ajax call
function date(){
$temp = $('select[name=people_name]').val();
$name = $temp;
$table = 'myTablename';
$url = "/myurl/php/get_date.php?name="+$name+"&table="+$table;
$.ajax({
type: "POST",
url: $url,
success: function(data) {
document.getElementById("from_date").value = data['min_date'];
document.getElementById("to_date").value = data['max_date'];
}
});
}
when I echo the php variables I do get the data which I want. but logging the jquery variables the give me result as undefined.
maybe the php return data is not fetches by ajax success(data)? or do I need to have a function in my php code? how do I fetch returned array in my jquery?
Thanks!
Try encoding the array in php side with json_encode().
In your PHP
//Query the database and fetch some results
$array["min_date"] = $arr['min(date)'];
$array["max_date"] = $arr['max(date)'];
$array['query'] = $query;
echo json_encode($array); //add this
In ajax call
function date(){
$temp = $('select[name=people_name]').val();
$name = $temp;
$table = 'myTablename';
$url = "/myurl/php/get_date.php?name="+$name+"&table="+$table;
$.ajax({
type: "POST",
dataType:'json', //add dataType
url: $url,
success: function(data) {
document.getElementById("from_date").value = data.min_date;
document.getElementById("to_date").value = data.max_date;
}
});
}
I am trying to send an array from javascript to PHP script using ajax. This is the code I have so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" >Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
$(".output")
.each(function() {
var parms = [];
parms.push($(this).text());
});
</script>
<script>
function loadXMLDoc()
{
$.ajax({
type: "POST",
url: "update.php",
data: { value : $(parms).serializeArray() },
success: function(data)
{
console.log (data);
}
});
}
$("button").on('click',function(){ loadXMLDoc(); });
</script>
In my $.output function, I am using the parms [] array to store all the UI slider values which I am trying to pass on to the next PHP script page on a button click event as defined in loadXMLDoc() function. In my PHP page, I am accessing them as below.
<?php
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
// Do whatever you want with the $uid
?>
However, I am not able to view the data in my update.php script. Can someone please let me know what am doing wrong?
This is the link to my work so far.
serializeArray returns the json object ,maybe you could try json_decode in your php script,simply like:
$uid_arr = json_decode($uid,true);
print_r($uid_arr);
Just Use
data: $(parms).serializeArray()