How to populate the div with the response data from Ajax? - javascript

I have an Ajax post request which on success returns an array which I would like to load into a div. Now, doing this with single values is quite easy but with an array, I can't seem to find the right way to do it.
<fieldset id="div1" ondrop="remove_from_customer(event)" ondragover="allowDrop(event)">
<legend>Vacant parking spots</legend>
<?php $counter = 0;
echo count(get_free_parking_spots());
foreach (get_free_parking_spots() as $row) { ?>
<div id="count_id<?php echo $counter; ?>" data-parking_gate="<?php echo $row['parking_gate_id']; ?>" data-location_id="<?php echo $row['location_id']; ?>" data-spot_no="<?php echo $row['spot_no']; ?>" draggable="true" ondragstart="drag(event)">
<label><?php echo '' . $row['name'] . '' ?></label>
<label><?php echo '<p>Gate: ' . $row['parking_gate_id'] . '<p>Spot: ' . $row['spot_no'] . '' ?></label>
</div>
<?php $counter++;
} ?>
</fieldset>
<fieldset id="div2" ondrop="drop_to_customer(event)" ondragover="allowDrop(event)">
<legend>Current parking spots of the customer</legend>
<?php $count = 0;
echo count(get_customer_parking_spots($selected_user_id));
foreach (get_customer_parking_spots($selected_user_id) as $user) { ?>
<div id="count_idd<?php echo $count; ?>" data-customerid="<?php echo $user['customer_id']; ?>" data-gate_id="<?php echo $user['gate_id']; ?>" data-spot_id="<?php echo $user['spot_id']; ?>" data-location_id="<?php echo $user['location_id']; ?>" draggable="true" ondragstart="drag(event)">
<label><?php echo '' . $user['location_name'] . '' ?></label>
<label><?php echo '<p>Gate: ' . $user['gate_id'] . '<p>Spot: ' . $user['spot_id'] ?></label>
</div>
<?php $count++;
} ?>
</fieldset>
Ajax:
function drop_to_customer(ev) {
if (<?php echo count(get_customer_parking_spots($selected_user_id)); ?> < 3) {
const el = document.querySelector("[id=" + "\'" + ev.dataTransfer.getData("text") + "\'" + "]");
var add_location = "add location";
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
$.ajax({
type: 'post',
url: 'external_submit.php',
data: {
add_spot: add_location
},
success: function(html) {
$('#div1').html($('#div1', html).html()); //my failed attempt to reload data into the div here
}
});
}
}
As you can see when drop_to_customer() is called I am doing a post request and returning an array which I would like to load into the other div with id div1. The array is json_Encoded and it is returned successfully.
EDIT:
This is how I echo the array in PHP:
echo json_encode(array("array" => get_data($_POST['id']), "html" => $html))

Related

Javascript not allowing actually image to be linked out

I am trying to get my website to link the slider image. Nothing in my wordpress has the options, so I opened up the slider php from the file manager, and I am trying to figure out exactly what I need to do to enable the image to link out without having to put on the "caption". Here is the website
<div id="home-slide-wrapper">
<div id="home-slide" class="<?php echo $img_slide_effect_direction; ?>">
<ul class="slides">
<?php
foreach( $slides as $slide ) :
$image_id = get_post_meta($slide->ID, 'info_image', true);
// $resized_image_src = wp_get_attachment_image_src($image_id, 'full');
// $resized_image_src = $resized_image_src[0];
$resized_image_src = theme_get_image( $image_id, 5000, $img_slide_height, true );
// Caption
$caption_pos = get_post_meta($slide->ID, 'info_caption_pos', true);
$caption_title = __(get_post_meta($slide->ID, 'info_caption_title', true));
$caption_text = __(get_post_meta($slide->ID, 'info_caption', true));
$link = __(get_post_meta($slide->ID, 'info_link', true));
// Pre-Process
$caption_title = ( $link != '' && $caption_title != '' ) ? '' . $caption_title . '' : $caption_title;
$caption_title_bg_tone = 'slide-caption-bg-' . getDarkLightYIQ( $sitewide_caption_title_bg_color );
$caption_style[] = ( $sitewide_caption_title_text_color != '' ) ? 'color:' . $sitewide_caption_title_text_color . ';' : '';
$caption_style[] = 'background-color:' . $sitewide_caption_title_bg_color . ';';
$caption_title_style = 'style="' . implode( ' ', $caption_style ) . '"';
?>
<li>
<img src="<?php echo $resized_image_src; ?>" alt="<?php echo $slide->post_title; ?>" />
<?php if( $caption_title || $caption_text ): ?>
<div class="slide-caption <?php echo $caption_pos; ?>">
<div class="container">
<?php if( $caption_title != '' ) : ?>
<div class="slide-caption-headline <?php echo $caption_title_bg_tone; ?>"><?php echo $caption_title; ?></div>
<?php endif; ?>
<?php if( $caption_text ) : ?>
<div class="slide-caption-text"><?php echo $caption_text; ?></div>
<?php endif; ?>
</div>
</div>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
</div><!-- #home-slide-wrapper -->
Replace
<img src="<?php echo $resized_image_src; ?>" alt="<?php echo $slide->post_title; ?>" />
with
<a href="<?php echo $link; ?>">
<img src="<?php echo $resized_image_src; ?>" alt="<?php echo $slide->post_title; ?>" />
</a>

post jquery array to php page when checking checkboxes

i have dynamic number of checkboxes and a button to post the checked elements to another page .. here is the code:
<div class="overSelect"></div>
<div id="checkboxes<?php echo $aa['id']; ?>">
<?php
$pid = select::property($aa['name']);
$arr2 = select::properties($pid);
$cc = 1;
foreach ($arr2 as $aa2) { ?>
<div style="padding-right: 20px" class="row"><label>
<input type="checkbox" value="<?php echo $aa2['name'] ?>" name="checks<?php echo $aa['id'] ?>[]"id="check<?php echo $aa['id']; ?>"><?php echo $aa2['name'] ?>
</label></div>
<?php } ?>
</div>
<a class="btn btn-primary btn-sm" name="update-all"onclick="update_all('prop_id<?php echo $aa['id']; ?><?php $counter; ?>','checks<?php echo $aa['id'] ?>')"id="btn-all<?php echo $aa['id']; ?><?php $counter; ?><?php echo $p['id']; ?>">save</a>
i tried this code but it is not working
<script type="text/javascript">
function update_all(a, b) {
var aa = document.getElementById(a).value;
var values = new Array();
$("input:checkbox[name=b]").each(function () {
if ($(this).is(":checked")){
values.push($(this).val());
}
});
alert(aa);
alert(values.length);
alert(values);
}
</script>
if the checkboxes checked .. it's value will be added to the array and posted to php page
any help please .. thanks in advance

JavaScript on change function working not well

I have a JavaScript code which works with HTML select tag.
$(function() {
$('#to_name').on('change',function() {
if( $(this).val()=="<?php echo $ceo_chunks[0];?> <?php echo $ceo_chunks[1];?> <?php echo $ceo_chunks[2]?>") {
$('#to_designation').val('<?php echo $ceo_chunks[3];?>');
$('#dear_sir').val('<?php echo $ceo_chunks[0]?> <?php echo $ceo_last_name;?>') ;
if( $(this).val()=="<?php echo $liaison_one_chunks[0];?> <?php echo $liaison_one_chunks[1];?> <?php echo $liaison_one_chunks[2]?>") {
$('#to_designation').val('<?php echo $liaison_one_chunks[3]?>')
$('#dear_sir').val('<?php echo $liaison_one_chunks[0]?> <?php echo $liaison_one_last_name;?>')
$("#liaison_one").show()
$("#dear_liaison_one").show()
} else {
$("#ceo").hide()
$("#liaison_two").hide()
$("#dear_ceo").hide()
$("#dear_liaison_two").hide()
}
if( $(this).val()=="<?php echo $liaison_two_chunks[0];?> <?php echo $liaison_two_chunks[1];?> <?php echo $liaison_two_chunks[2]?>") {
$('#to_designation').val('<?php echo $liaison_two_chunks[3]?>')
$('#dear_sir').val('<?php echo $liaison_two_chunks[0]?> <?php echo $liaison_two_last_name;?>')
$("#liaison_two").show()
$("#dear_liaison_two").show()
} else {
$("#ceo").hide()
$("#liaison_one").hide()
$("#dear_ceo").hide()
$("#dear_liaison_one").hide()
}
};
});
});
and here is html code
<select name="to_name" id="to_name">
<option value="<?php echo $ceo_chunks[0];?> <?php echo $ceo_chunks[1];?> <?php echo $ceo_chunks[2]?>"><?php echo $ceo_chunks[0];?> <?php echo $ceo_chunks[1];?> <?php echo $ceo_chunks[2]?></option>
<option value="<?php echo $liaison_one_chunks[0];?> <?php echo $liaison_one_chunks[1];?> <?php echo $liaison_one_chunks[2]?>"><?php echo $liaison_one_chunks[0];?> <?php echo $liaison_one_chunks[1];?> <?php echo $liaison_one_chunks[2]?></option>
<option value="<?php echo $liaison_two_chunks[0];?> <?php echo $liaison_two_chunks[1];?> <?php echo $liaison_two_chunks[2]?>"><?php echo $liaison_two_chunks[0];?> <?php echo $liaison_two_chunks[1];?> <?php echo $liaison_two_chunks[2]?></option>
</select>
<br>
<select name="to_designation" id="to_designation">
<option value="<?php echo $ceo_chunks[3]?>" id="ceo"><?php echo $ceo_chunks[3]?></option>
<option value="<?php echo $liaison_one_chunks[3]?>" id="liaison_one"><?php echo $liaison_one_chunks[3]?></option>
<option value="<?php echo $liaison_two_chunks[3]?>"id="liaison_two"><?php echo $liaison_two_chunks[3]?></option>
</select>
<div id="dear_ceo" style="margin-top:10px; width:auto">
<input type="text" name="dear_sir" id="dear_ceo" value="Dear <?php echo $ceo_chunks[0]?> <?php echo $ceo_last_name;
?>"/>
</div>
<div id="dear_liaison_one" style="margin-top:10px; width:auto; display:none">
<input type="text" name="dear_sir" id="dear_liaison_one" value="Dear <?php echo $liaison_one_chunks[0]?> <?php echo $liaison_one_last_name;?>"/>
</div>
<div id="dear_liaison_two" style="margin-top:10px; width:auto; display:none">
<input type="text" name="dear_sir" id="dear_liaison_two" value="Dear <?php echo $liaison_two_chunks[0]?> <?php echo $liaison_two_last_name;?>"/>
</div>
My function works very well for select tag but it's not working with input type text.
How can I fix that?
There is a closing bracket clearly missing for your first if statement.
Please close the bracket. There is no logical error in your code.
$(function() {
$('#to_name').on('change',function(){
if( $(this).val()=="<?php echo $ceo_chunks[0];?> <?php echo $ceo_chunks[1];?> <?php echo $ceo_chunks[2]?>"){
$('#to_designation').val('<?php echo $ceo_chunks[3];?>')
$('#dear_sir').val('<?php echo $ceo_chunks[0]?> <?php echo $ceo_last_name;?>')
/*$("#ceo").show()
$("#dear_ceo").show()*/
//} ---uncomment this ---
also include a terminating semi-colon everytime you are calling a function. For example
if( $(this).val()=="<?php echo $ceo_chunks[0];?> <?php echo $ceo_chunks[1];?> <?php echo $ceo_chunks[2]?>"){
$('#to_designation').val('<?php echo $ceo_chunks[3];?>');
$('#dear_sir').val('<?php echo $ceo_chunks[0]?> <?php echo $ceo_last_name;?>');
}
I suggest you use semicolons at the end of line (when appropriate). I know they are not mandatory but consider them as a good practice.
You also have a semicolon at the end of if-clause at the end. It's probably not braking anything but just in case...
Try replacing spaces with underscores (_).
For example:
<?php echo $ceo_chunks[0];?> <?php echo $ceo_chunks[1];?> <?php echo $ceo_chunks[2]?>
would become
<?php echo $ceo_chunks[0];?>_<?php echo $ceo_chunks[1];?>_<?php echo $ceo_chunks[2]?>
And check if you can alert the value of the changed input correctly.

Using ajax to refresh a div in a for each loop, wrong result

So I've been struggling with this for a while, i have a div and a form in a for each loop and on submitting one of the forms in the loop, the content of its div is updated in the database and refreshed ("div only"). This is done using JavaScript and Ajax. My update query works fine, JavaScript handles the form and Ajax refreshes only the div in the page. My problem is, upon refreshing all the contents in the loop are put into one div but instead i want one content to one div as many times the loop is run, to better understand my problem please refer to the image below:
Before:
After first like button is clicked:
This is the result i expect to see:
info.php
<html>
<head>
.......
<script type="text/javascript">
$(document).ready(function(){
$('.ajaxform').submit(function(e) {
e.preventDefault(); // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType:'html',
url: "test.php", // the file to call
cache: false,
success: function(response) { // on success..
$('.ld').html(response);
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...........
foreach($stmt as $obj){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id = $obj['id'];
$userimage = $obj['user_image'];
$row ++;
$likes = $obj['like1'];
$dislikes = $obj['dislike'];
echo '<div class="txt">';
echo '<div class="comment-container">';
echo '<div class="comment-item">';
echo '<div class="comment-avatar">';
echo '<img src="user/user_images/'.$userimage.'" alt="avatar">';
echo '</div>';
echo '<div class="comment-post">';
echo '<span style="font-weight:bold;">'.$username.'&nbsp&nbspsaid....
</span>';
echo '<p style="margin-left:-11px;">'.$comment.'</p>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<form action="" method="post" class="ajaxform"
enctype="multipart/form-data">';//form to submit
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="pid" value="'.$type_id.'">';
echo '<input type="hidden" name="stk" value="'.$likes.'">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;margin-
right:290px;"/><div class="ld">'.$likes.'</div>';//div to refresh
echo '</form>';
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkd_id" value="'.$id.'">';
echo '<input type="hidden" name="dislike" value="">';
echo ' <input type= "image" id="submit" src="images/dislike.png"
width="15" height="15" style="float:right;position:relative;
margin-top:-14px;margin-right:230px;"/>
<div class="ldks">'.$dislikes.'</div>';
echo '</form>';
echo '<span class="SendCopy">Reply</span> ';
echo '<div class="users">';
echo '<form action="" method="post" enctype="multipart/form-
data">';
echo '<textarea rows="4" name="replycomment" style="float:right;
resize: none;margin-top:5px;" cols="50" >';
echo '</textarea>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<input type="submit" name="reply" id="submit" class="post-
button" value="Send" />';
echo '</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
?>
</body>
</html>
test.php
<?php
$mysqli = new mysqli("localhost", "root", "", "Anonmy");
if( isset( $_POST['lkcv'] ) && is_array( $_POST['lkcv'] ) )
{
$idArray = array();
foreach( $_POST['lkcv'] as $value )
{
$idArray[] = intval( $value );
}
$mysqli->query( "UPDATE comment SET like1 = like1 + 1 WHERE id IN (".implode(
',', $idArray ).")" );
}
?>
<?php
$host = 'localhost';
$dbname = 'dbname';
$username = "root";
$password = "";
$conn = new PDO('mysql:host=localhost;dbname=Anonmy', $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_id = $_POST['pid'];
$like = $_POST['stk'];
$target_no = 3;
echo '<div class="wrap">';
// retrive comments with post id
$stmt = $conn->prepare(
"SELECT *
FROM comment
WHERE post_id = :pid
");
$stmt->bindParam(":pid", $type_id, PDO::PARAM_INT);
$stmt->execute();
foreach($stmt as $obj){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id = $obj['id'];
$userimage = $obj['user_image'];
$likes = $obj['like1'];
$dislikes = $obj['dislike'];
echo '<div class="">'.$likes.'</div>';
}
?>
</body>
</html>
How can i modify my code to achieve the result in image 3.
test.php[updated]
$host = 'localhost';
$dbname = 'dbname';
$username = "root";
$password = "";
$conn = new PDO('mysql:host=localhost;dbname=Anonmy', $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_id = $_POST['pid'];
$like = $_POST['stk'];
$target_no = 3;
echo '<div class="wrap">';
// retrive comments with post id
$stmt = $conn->prepare(
"SELECT *
FROM comment
WHERE post_id = :pid
");
$stmt->bindParam(":pid", $type_id, PDO::PARAM_INT);
$stmt->execute();
//updated
$result = array();
foreach ($stmt as $row) {
$result[] = array('id' => $row['id'], 'likes' => $row['like1'], 'dislikes' =>
$row['dislike']);
}
echo json_encode($result);
?>
info.php[updated]
<html>
<head>
.......
<script type="text/javascript">
$(document).ready(function(){
$('.ajaxform').submit(function(e) {
e.preventDefault(); // catch the form's submit event
//updated
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType:'json',
url: "test.php", // the file to call
cache: false, // Not needed for POST
success: function(response) { // on success..
$.each(response, function(i, el) {
var comment_post = $("#comment-post-" + el.id);
comment_post.find(".ld").text(el.likes);
comment_post.find(".ldks").text(el.dislikes);
});
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
</head>
<body>
<?php
...........
foreach($stmt as $obj){
$username = $obj['user_name'];
$comment = $obj['comment'];
$id = $obj['id'];
$userimage = $obj['user_image'];
$row ++;
$likes = $obj['like1'];
$dislikes = $obj['dislike'];
echo '<div class="txt">';
echo '<div class="comment-container">';
echo '<div class="comment-item">';
echo '<div class="comment-avatar">';
echo '<img src="user/user_images/'.$userimage.'" alt="avatar">';
echo '</div>';
echo '<div class="comment-post" id="comment-post-' . $id .'">';//updated
echo '<span style="font-weight:bold;">'.$username.'&nbsp&nbspsaid....
</span>';
echo '<p style="margin-left:-11px;">'.$comment.'</p>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<form action="" method="post" class="ajaxform"
enctype="multipart/form-data">';//form to submit
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="pid" value="'.$type_id.'">';
echo '<input type="hidden" name="stk" value="'.$likes.'">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;margin-
right:290px;"/><div class="ld">'.$likes.'</div>';//div to refresh
echo '</form>';
echo '<form action="" method="post" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkd_id" value="'.$id.'">';
echo '<input type="hidden" name="dislike" value="">';
echo ' <input type= "image" id="submit" src="images/dislike.png"
width="15" height="15" style="float:right;position:relative;
margin-top:-14px;margin-right:230px;"/>
<div class="ldks">'.$dislikes.'</div>';
echo '</form>';
echo '<span class="SendCopy">Reply</span> ';
echo '<div class="users">';
echo '<form action="" method="post" enctype="multipart/form-
data">';
echo '<textarea rows="4" name="replycomment" style="float:right;
resize: none;margin-top:5px;" cols="50" >';
echo '</textarea>';
echo '<input type="hidden" name="comment_id" value="'.$id.'">';
echo '<input type="submit" name="reply" id="submit" class="post-
button" value="Send" />';
echo '</form>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
echo '</div>';
?>
</body>
</html>
test.php[ajax response]
<html>
<head>
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2
/jquery.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1
/jquery.min.js"> </script>
<script language="JavaScript">
$(document).ready(function(){
$(".users").hide();
$(".SendCopy").click(function(){
$(this).next(".users").slideToggle("slow");
});
});
</script>
</head>
<body>
[{"id":"2","likes":"196","dislikes":"0"},
{"id":"5","likes":"80","dislikes":"0"},
{"id":"6","likes":"45","dislikes":"0"},
{"id":"7","likes":"31","dislikes":"0"}]
</body>
</html>
Change the HTML so that the post ID is included in the the ID of the DIV containing the like/dislike data.
echo '<div class="comment-post" id="comment-post-' . $id .'">';
Change test.php so it returns JSON instead of HTML:
$result = array();
foreach ($stmt as $row) {
$result[] = array('id' => $row['id'], 'likes' => $row['like1'], 'dislikes' => $row['dislike']);
}
echo json_encode($result);
Remove all other code in test.php that produces output, like this line:
echo '<div class="wrap">';
The only output should be the JSON.
Then in the AJAX call, extract the JSON data and update each corresponding element with its likes and dislikes.
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType:'json',
url: "test.php", // the file to call
cache: false, // Not needed for POST
success: function(response) { // on success..
$.each(response, function(i, el) {
var comment_post = $("#comment-post-" + el.id);
comment_post.find(".ld").text(el.likes);
comment_post.find(".ldks").text(el.dislikes);
});
}
});

JQuery checkbox when value is assigned

I've been trying to get JQuery to check a radio for me when I assign a value 'Z' to it.
My current code:
<?php if ($option['type'] == 'radio') { ?>
<div class="form-group<?php echo ($option['required'] ? ' required' : ''); ?>">
<label class="control-label"><?php echo $option['name']; ?></label>
<div id="input-option<?php echo $option['product_option_id']; ?>">
<?php if (isset($option_values)) foreach ($option_values as $option_value) { ?>
<div class="radio">
<label>
<input type="radio" name="option[<?php echo $option['product_option_id']; ?>]" value="<?php echo $option_value['product_option_value_id']; ?>" />
<?php echo $option_value['name']; ?>
<?php if ($option_value['price']) { ?>
<?php if ($option_value['price_prefix'] == 'z') {?>
<script>
$(".radio").prop("checked", true)
</script>
<?php echo 'Im Active!!'; ?><?php }
else { ?> <?php echo ' ';?> (<?php echo $option_value['price_prefix'];?>
<?php echo $option_value['price']; ?>) <?PHP }?>
<?php } ?>
</label>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
<?php } ?>
As for now, my option 'Z' only shows 'I'm Active!!' in the list. The radio is still unchecked though.
What am I doing wrong?
I'm planning on releasing a free OpenCart module where people can activate an option by standard by assigning the value Z in product properties.
Thanks!

Categories