ajax not able to pass variable to php - javascript

I have a slider which uses javascript. I am trying to update the display of my web page based on the slider values. I tried to use ajax function to send the data to another PHP page to update the display. But I am not getting anything in my page. Here is my code 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" onclick="loadXMLDoc()">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));
});
</script>
<script>
function loadXMLDoc()
{
alert "Am I coming here";
$.ajax({
type: "POST",
url: 'update.php',
data: { value : data.value },
success: function(data)
{
alert("success!");
}
});
}
</script>
I read in another post that javascript variables are available across functions and so I am trying to use the variable data.value inside my another javascript function loadXMLDoc(). But I do not see the value getting displayed in my update.php page. My update.php file is as below.
<?php
if(isset($_POST['value']))
{
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
}
?>
Can someone please help me on this?

In the loadXMLDoc function I don't see data defined anywhere. I think that could be one of the problems. Also, when you're doing jquery ajax requests be sure to have a fail callback. The fail callback will tell you if the request fails which can be very informative.
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
To make the data variable accessible in the XMLLoadDoc function you could try putting it in the global scope (kind of a 'no-no', but its OK for a use case like this). So, at the top, declare var masterData, then when you have data in the .bind callback set masterData = data; and then in loadXMLDoc refer to masterData

Related

ajax request, query database, json_encode, return on success, show results

I'm working on a new piece of code and I'm new to ajax so I cant get it to work. I've got a textbox that has a javascript onKeyUp assigned to it. The first function is a delay function. It sets a delay timer, and as long as no other request is made via that delay timer, it runs a second function with the ajax after a certain time period. Inside the ajax, it runs a database query located in the second file based on the text that was entered in the textbox. It sets up an array of the results, json_encodes them, and returns them back to the original page. Then, I need to populate the page with the results (with php).
The Textbox
<input type="text" onKeyUp="delay_method('search_customer',search_customer(this.value),'2000')" />
The delay function
<script type="text/javascript">
function delay_method(label,callback,time){
if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}
delayed_methods[label]=Date.now();
var t=delayed_methods[label];
setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{ callback();}}, time||500);
}
</script>
The ajax function
<script type="text/javascript">
function search_customer(value){
console.log(value);
$.ajax({
type: "POST",
url: "secondpage.php",
data: query,
dataType: 'json',
success: function(data){
console.log(data.name); // customer name
console.log(data.company); // customer company name
}
});
}
</script>
second page
set up an array for testing. Bypassing the query for now. Just need to get results back into main page. I can set up the array from the php once its working. My query will use LIKE %search text%
$arr = array(
'name'=>'overflow',
'company'=>'value'
);
echo json_encode($arr);
I have NO clue how to retrieve the data from the ajax function and populate the results. I would love to get the results back into a php array, and then loop through the array to echo out the results. I can loop through the array in php...my biggest concern is getting the results back into a php array.
Any assistance would be great. I cant seem to get the code to work. I am new to ajax so I'm learning this as I go.
UPDATE
Everything is working the way it should except the delay. Its not putting a delay on anything. I need it to wait for 2 seconds from each keyup before it activates the ajax function. If it receives another keyup, it waits an additional 2 seconds. IT continues until there is 2 seconds with no keyups. That way its not querying the database on every single keyup if the person is still typing. Right now its processing everything with each keyup.
textbox
<input type="text" onKeyUp="delay_method('search_customer',search_customer(this.value),'2000')" />
delay
function delay_method(label,callback,time){
if(typeof window.delayed_methods=="undefined"){window.delayed_methods={};}
delayed_methods[label]=Date.now();
var t=delayed_methods[label];
setTimeout(function(){ if(delayed_methods[label]!=t){return;}else{ callback();}}, time||500);
}
ajax function
function search_customer(value){
console.log(value);
$.ajax({
type: "POST",
url: "secondpage.php",
data: { "value": value },
dataType: 'html',
success: function(data){
$('#resultDiv').html(data);
}
});
}
second page:
$value = $_POST['value'];
if ((isset($value)) && ($value != "")) {
$arr = array();
$search_query = $db1q->query("SELECT first_name, company FROM Users WHERE first_name LIKE '%$value%' OR last_name LIKE '%$value%' OR company LIKE '%$value%'");
if ($search_query->num_rows > 0) {
while ($search_result = $search_query->fetch_assoc()) {
$arr[$search_result['first_name']] = $search_result['company'];
}
}
$html = '';
$html .= '<div>';
foreach ($arr as $key => $value) {
$html .= '<div class="sub-div"><h2>'.$key.'</h2> : ' . '<h4>' . $value . '</h4></div>';
}
$html .= '</div>';
echo $html;
}
You can't get the results back into a php array in js. So, what you have to do is to pass processed html in js and just print on page.
For example,
In second page
$arr = array(
'name'=>'overflow',
'company'=>'value'
);
using above array $arr make html over here and store it in variable. pass that variable into js.
For Ex :
$html = '';
$html .= '<div>';
foreach ($arr as $key => $value) {
$html .= '<div class="sub-div"><h2>'.$key.'</h2> : ' . '<h4>' . $value . '</h4></div>';
}
$html .= '</div>';
echo $html;
Now you will get html in your ajax success. just show on div like
$('resultDiv').html(data);
Your problem with my snippet of code (The delay function) is that on the keyup event when you are calling the delay function and passing the function/callback argument you are calling it and executing it immediately which is not the purpose of it. You should pass it as an anonymous function that calls your functions ( in a closure way). Also because you are using the html element to provide the values, you need to send them to the function scope / closure. Otherwise the closure will lost the parent context of (this) in this case the input.. so to solve it, you should use the bind javascript method, to preserve the "this" parent and its values. This is the key.
The correct input onkeyup event becomes this one:
<input type="text" onKeyUp="delay_method('search_customer',function(){search_customer(this.value);}.bind(this),'2000')" />
There are multiple commas after URL tag in ajax request remove it like following:
url: "secondpage.php",
Generally, the ajax request format should be the following using jQuery:
var index=0;
var menuId = $( "ul.nav" ).first().attr( "id" );
var request = $.ajax({
url: "script.php",
method: "POST",
data: { id : menuId },
dataType: "html"
});
request.done(function( msg ) {
index++;
//Append the result to the js array and then try storing the array value to PHP using HTML;
//Call your next event;
$( "#log" ).html( msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
Now for your logic rather go with delayed call you should be using done or success event. Inside the success event, you should be calling next requirement. Because Ajax is asynchronous.

javascript variable pass into php

I get category id by js and want to use it to get category description.
when i am passing this id using ajax into php variable its print correct output but when i try to put this id in get_description code ajax give 500 error and not return output why this happen please help me.
Below is my code.
<script type="text/javascript">
$(".-filter").click(function() {
var js_var = this.id;
$.ajax ({
type: "POST",
url: "<?php echo plugin_dir_url( __FILE__ ); ?>category.php",
data: { val : js_var },
success: function( result ) {
$("#update").html(result);
}
});
});
</script>
<div id="update">
<?php
$cat_id = $_POST['val'];
echo $cat_id;
//echo term_description($cat_id,'category');
?>`enter code here
</div>
Thanks,

Undefined index in php when getting value passed from AJAX

I'm trying to get the value that I passed in AJAX to PHP. It shows an alert that says, "Success!" however it when I try to display the value in PHP, it says undefined index. Also I am passing it in the same page.
Whenever I click a button, it opens a modal and I also passing values from that button to the modal. This is evident in my JS code.
<script>
$(document).ready(function(){
$('#editModal').on('show.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id'); //im trying to pass this value to php, e.g. 5
var time = $(e.relatedTarget).data('time');
var name = $(e.relatedTarget).data('name');
var stat = $(e.relatedTarget).data('stat');
var desc = $(e.relatedTarget).data('desc');
alert(id);
$("#task_id_edit").val(id);
$("#new-taskID").val(id);
$("#allotted_time_edit").val(time);
$("#task_name_edit").val(name);
$("#task_status_edit").val(stat);
$("#task_desc_edit").val(desc);
$("#task_id_ref2").val(id);
//AJAX CODE HERE
$(function() {
$.ajax({
type: "POST",
url: 'tasks.php?id='<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>,
data: { "userID" : id },
success: function(data)
{
alert("success!"); //this display
}
});
});
}); // line 1131
});
</script>
PHP CODE:
<?php
$uid = $_POST['userID'];
echo $uid." is the value";
?>
It keeps getting an error that says, undefined index: userID. I am confused. Please help me how to fix this. Your help will be much appreciated! Thank you!
Echo the number in the javascript string.
Currently you will get:
url:'tasks.php?id='1,
The 1 should be concatenated or inside the quote. Try:
url: 'tasks.php?id=<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>',
or take that parameter out since it doesn't appear to be being used.
Just put the $_POST['userID'] in a if statement
Undefined index: UserID is not a error it is a warning
<?php
if(isset($_POST['userID'])
{
$uid = $_POST['userID'];
echo $uid." is the value";
}
else
{
echo "Sorry Value cant be printed";
}
?>

How do i make my php variable accessible?

I am trying to implement a timer. I learned this idea from a SO post.
<?php
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
}
?>
This is my php code. My php,html and JS codes are in the same page. I have a button in my html. When a user clicks on the html page, It will call a Ajax function
//url:"onlinetest.php",
//dataType: 'json',
beforeSend: function()
{
$(".startMyTest").off('click');
setCountDown();
}
It will call setCountDown() method, which contains a line at the very beginning
var days = <?php echo $remainingDay; ?>;
When i run the page, it says[even before clicking the button] "expected expression, got '<'" in the above line. My doubt is
Why this php variable get replaced before i am triggering the button. Please let me know hoe to solve this or how to change my idea.
The problem is, since initial load, $_POST values aren't populated (empty on first load),
That variable you set is undefined, just make sure you initialize that variable fist.
<?php
// initialize
$remainingDay = 1;
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
echo json_encode(array('remaining_day' => $remainingDay);
exit;
}
?>
<script>
var days = <?php echo $remainingDay; ?>;
$('.your_button').on('click', function(){
$.ajax({
url: 'something.php',
dataType: 'JSON',
type: 'POST',
beforeSend: function() {
// whatever processes you need
},
success: function(response) {
alert(response.remaining_day);
}
});
});
</script>
That is just the basic idea, I just added other codes for that particular example, just add/change the rest of your logic thats needed on your side.
You can pass a php variable into JS code like
var jsvariable ="<?php echo $phpvariable ?>";
NOTE:
If you ever wanted to pass a php's json_encoded value to JS, you can do
var jsonVariable = <?php echo $json_encoded_value ?>; //Note that there is no need for quotes here
Try this,
var days = "<?php echo $remainingDay; ?>";

AJAX PHP function onchange select box

I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)
Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....
Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>
In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;
set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!
just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});

Categories