AJAX change a div value on click inside PHP loop - javascript

I'm looking to change the content of a div based on a link being clicked on a php page. The link is created through a loop and I need to pass several parameters through the URL. The div is also created through the loop so the id of the div will be variable. I'm having trouble with the AJAX to make this happen.
Below is my php:
<?php
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$tripDestination = $row3["tripDestination"];
$sessionID = $row3["$sessionID"];
$price = $row3["price"];
echo "" . $tripDestination . ' - ' . $price . "";
echo "<br />";
echo "<div id=\"trips\"></div>";
}
}
?>
I need to pass two variables in the URL: sessionID and tripDestination. I was able to load static content, but it needs to be dynamic. Here's my AJAX so far
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "sqlUpload.php?sessionID=35&tripDestination=SFO", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
Thanks in advance!

I might think about sending the information from a data attribute on the link:
PHP:
<?php
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
$tripDestination = $row3["tripDestination"];
$sessionID = $row3[$sessionID];
$price = $row3["price"];
// Store the organized data
$data = array(
'tripDestination'=>$tripDestination,
'sessionID'=>$sessionID,
'price'=>$price
);
?>
<!-- You can store the array into json on the data attribute -->
<a href="#" class="data-set" data-information='<?php echo json_encode($data) ?>'><?php echo $tripDestination.' - '.$price ?></a>
<br />
<div class="data-response"></div>
<?php
}
}
?>
JavaScript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// When user clicks the <a> that has the "data-set" class
$('.data-set').on('click',function(e){
// I like to prevent default here, just incase
e.preventDefault();
// Assign current obj
var getObj = $(this);
// Fetch the json from the attribute
var getData = getObj.data('information');
// Send
$.ajax({
// Just send to the page, no query string
url: "sqlUpload.php",
// I would send POST, personally
type: 'GET',
// This is the data being sent
data: getData,
success: function(response){
// Presumably you want to put the response into the
// accompanying div, then you can just do next()
getObj.next('.data-response').html(response);
}});
});
});
</script>

Related

How to pass php variable from a loop to a javascript variable

I have a while loop which loads the posts of the user and when the like button is clicked to get the post id send it to another php page which will process it and update in the database the likes number but I can't get the good id..
My while loop :
while($posts = mysqli_fetch_array($query)){
<div <?php echo "id=".$posts['id'] ?>
<div class="post">
.
.
</div>
</div> }
And the Ajax Request:
var id = "<?php echo $posts['id'] ?>";
$.ajax({
type: 'POST',
url: 'likes.php',
data: {id:id},
success: function(msg){
alert('Success!');
}
});
But it output only the last value of the while loop and I want for every post to get the id when the like button is pressed.Thanks for help!
What you're doing would never work. Since you have multiple IDs, you have to retrieve the ID from the <div> that was clicked on, and pass that to your ajax call, e.g.
<div data-id="42" class="clickme">
<script>
$('div.clickme').click(function (e) {
id = $(this).attr('data-id');
$.ajax( .... use "id" here ... );
}
alternatively, even something like this would help:
<? while(... fetch from db ... ){ ?>
<div onclick="doAjax(<?php echo json_encode($row['id']); ?>)">
<script>
function doAjax(id) {
$.ajax(... use "id" here ...);
}
</script>

How to get id and type in php foreach loop and send to server via ajax?

So i have 2 files index.php and changeLikeDislike.php. I think the issue is where javascript is trying to get the type and id but I do not know how I would go about that. My javascript function is being called in the foreach->li->divs. It was working before like this: data: dataString, but I added schoolId into data of ajax as well so it's like this now data: {dataString:dataString, schoolId:schoolId},
index.php
<?php
$last_id = 0;
foreach ($list as $rs) {
$last_id = $rs['id']; // keep the last id for the paging
?>
<li>
<div style="width:100%; color:#000;">
<?php echo '<div class="product_like thumb-div"><img src="like.png" class="rating-image " onclick=changeLikeDislike("like","'.$rs['id'].'")> <br><span id="product_like_'.$rs['id'].'">'.$rs['pLike'].'</span></div>';?>
<?php echo '<div class="product_dislike"><img src="dislike.png" class="rating-image" onclick=changeLikeDislike("dislike","'.$rs['id'].'")><br> <span id="product_dislike_'.$rs['id'].'">'.$rs['pDislike'].'</span></div>';?>
</div>
</li>
<?php
}
?>
<script type="text/javascript">
//begin like and dislike
function changeLikeDislike(type,id){
var dataString = 'id='+ id + '&type=' + type;
$.ajax({
type: "POST",
url: "changeLikeDislike.php",
data: {dataString:dataString, schoolId:schoolId},
cache: false,
success: function(result){
if(result){
console.log('working');
}
}
});//end ajax
}
schoolId works in data but not dataString in ajax How would i go about grabbing those. My php file for reference:
//checks if school page id was brought and stores into variable
if (isset($_POST['schoolId'])) {
$schoolIdFinal = $_POST['schoolId'];
}else {
echo "nope";
}
if (isset($_POST['type'])) {
$type = $_POST['type'];
}else {
echo "nope type";
}
if (isset($_POST['id'])) {
$id = $_POST['id'];
}else {
echo "nope id";
}
my page is echoing out "nope type nope id"
Please change
data: {dataString:dataString, schoolId:schoolId},
to
data: {type:type, id:id, schoolId:schoolId},
to match the params to your PHP script.
data can either be a query string (like your dataString) OR a json struct (like {type:type, id:id, schoolId:schoolId}).
See the documentation of jQuery.ajax():
"The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}."
see http://api.jquery.com/jquery.ajax/
The issue is in the data bracket. change
data: {dataString:dataString, schoolId:schoolId}
to
data: {dataString:'dataString', schoolId:'schoolId'}
next time do a print_r of $_REQUEST or $_POST to see what fields are being recognized and in this case it looks like its not detecting anything.

Passing JavaScript variable to PHP on dropdown change

I am trying to change text in a div depending on value change on a dropdown box. The dropdown box values are populated from MySQL using PHP. I am loading the dropdown box on page load.
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response)
{ alert("The winner was passed!")},
}
);
<?php
require_once 'config.php';
$iid=$_GET['winner_id'];
$sql="SELECT * FROM Products where prod_id = ".$iid;
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$prodCredit="Credit :".$row["prod_price"];
$time="estmated time is :".$row["prod_time"];
?>
$('#esdTime').text(' <?php echo $prodCredit ?> ' );
$('#credit').text(' <?php echo $time ?> ' );
});
});
</script>
I am not getting results.
Let me know how can I assign JavaScript value idval to PHP variable $iid value.
//you would want a the php script to be in a separate file that you could call Have the php file return an array or json object. Have the callback success function append the new options to the html select. The following is a ruffexample
<script>
$(document).ready(function() {
$('#products').change(function(){
var idval=$('#products').val();
$.ajax
( {
type: "post",
url: "my.php",
data: {winner_id:idval},
success: function(response){
for (var i = 0; i < response.length; i++) {
$("#idofyourselect").append("<option val='" +response[i]+"'>" + response[i] + "</option>");
}
},
}
);
</script>

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; ?>";

Single Div refresh with jquery Ajax and PHP

Okay So I have a div on my page that has some code for display option groups in a select input. And then on the other side displaying the options in that group after the selection is made. My html/php code for this is below:
<div class="row">
<div class="col-lg-6">
<label class="control-label" for="productOptions">Select your
product options</label> <select class="form-control" id=
"productOptions">
<option>
Select an Option Group
</option><?php foreach($DefaultOptions as $option): ?>
<option value="<?php echo $option['GroupID']; ?>">
<?php echo $option['GroupName']; ?>
</option><?php endforeach; ?>
</select>
</div>
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
</div>
By default on the original page load, $GroupOptions does not exist in the form, because it is set after the user selects the Group they wish to choose from. I call the php script by using ajax to avoid page reload
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function() {
$("#groupOptions").html(dataString);
}
});
return false;
});
Then the ajax goes to a php call that gets the options that match the groups id in the database.
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
}
Now I want to refresh the div #GroupOptions to display the results from the query above, and make <?php if($GroupOptions): ?> set to true.
I managed to refresh the div with $("#groupOptions").html(dataString); in the success function of the ajax call. But that only returns well the dataString. (obviously). Is there a way to truly refresh just the div. Or a way to pass the info from the php call into the success function?
UPDATE:
You have 4 problems in your current code:
Problem #1 and Problem #2 - In your separate PHP script you are not echoing anything back to the Ajax. Anything you echo will go back as a variable to the success function. Simply the add echo statement(s) according to the format you want. Your 2nd problem is that you are trying to echo it in the HTML part, where $GroupOptions does not even exist (the Ajax simply returns an output from the PHP script, it's not an include statement so your variables are not in the same scope).
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
//this is where you want to iterate through the result and echo it (will be sent as it to the success function as a variable)
if($GroupOptions):
foreach ($GroupOptions as $optionValue):
echo $optionValue['optionName'];
endforeach;
endif;
}
In your Ajax, add a variable named data to the success function, which will receive the output from the PHP script. Also notice that your url is incorrect, you need to post to an actual external file such as my_custom_script.php.:
$.ajax({
type: "POST",
url: "your_external_script.php",
data: dataString,
success: function(data) {
if (data && data !== '') {
//data will equal anything that you echo in the PHP script
//we're adding the label to the html so you don't override it with the new output
var output = '<label class="control-label">Group Options</label>';
output += data;
$("#groupOptions").html(output);
} else {//nothing came back from the PHP script
alert('no data received!');
}
}
});
Problem #4 - And on your HTML, no need to run any PHP. Simply change:
<div class="col-lg-6" id="groupOptions">
<label class="control-label">Group Options</label>
<?php if($GroupOptions): ?>
<?php foreach ($GroupOptions as $optionValue): ?>
<?php echo $optionValue['optionName']; ?> <?php endforeach; ?>
<?php endif; ?>
</div>
to
<div class="col-lg-6" id="groupOptions">
</div>
Hope this helps
You have to take the response in yout success callback function and actually give a response in your oho function
$("#productOptions").change(function(){
var GroupID = $(this).val();
var dataString = 'GroupID=' + GroupID;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(dataString) { //take the response here
// convert dataString to html...
$("#groupOptions").html(newHtml);
}
});
return false;
});
PHP:
if(isset($_POST['GroupID']))
{
$GroupID = $_POST['GroupID'];
$sql = "SELECT * from `KC_Options` WHERE GroupID=$GroupID";
$GroupOptions = $db->query($sql);
echo json_encode($GroupOptions ); //give a response here using json
}

Categories