trying to add ajax request html to page source - javascript

I'm working on a project using ajax and PHP, my problem is when I add HTML markup with ajax it's not showing in page source and that preventing my from making another request to delete this markup and the only way that makes my delete it redirect to the same page.
this is my markup code:
<div class="card">
<div class="card-content">
<form>
<div class="input-field">
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">Type something here</label>
</div>
</form>
</div>
<div class="card-action">
<button id="submit" class="btn waves-effect waves-light" type="submit" disabled>Submit</button>
</div>
</div>
<div id="cards--wrapper">
<?php
$query = "SELECT * FROM messages ORDER BY id DESC";
$retrieve_posts_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($retrieve_posts_query)){
$content_id = $row['id'];
$post_content = $row['posts'];
$post_date = $row['date'];
$post_date = strtotime($post_date);
$post_date = date('j F, Y', $post_date);
?>
<div class="card" data-id = "<?php echo $content_id; ?>">
<a class="btn-large waves-effect waves-light red right delete">+</a>
<div class="card-content">
<?php echo $post_content; ?>
<span> <?php echo $post_date; ?> </span>
</div>
</div>
<?php } ?>
</div>
and this is my ajax code :
window.onload = function(){
$('#textarea1').keyup(function(){
var messageInput = $(this).val();
if( messageInput !== '' ){
$('#submit').attr('disabled', false);
}else {
$('#submit').attr('disabled', true);
}
});
$('#submit').on('click', function(){
retrieveData();
return false;
});
function retrieveData(){
var messageInput = $('#textarea1').val();
$.ajax({
url: 'server.php',
type: 'POST',
data: {
message : messageInput
},
success: function(data) {
$('#cards--wrapper').prepend(data);
$('#textarea1').val('');
$('#submit').attr('disabled', true);
window.location.href = 'index.php';
}
});
}
$('.delete').on('click', function(e){
e.preventDefault();
var that = $(this);
var cardID = that.parent().data('id');
var el = that.parent();
$.ajax({
url: 'delete.php?delete='+ cardID +'',
type: 'GET',
success: function(){
el.remove();
}
});
});
}

Related

show and hide element in jquery with ajax

I create survey poll in wordpress plugin to display questions i use ajax to display it
this is my html code
<div id="my_poll">
<button class="start" id="start"><b><?php _e('Start poll questions'); ?></b></button>
<div id="poll" class="container mt-sm-5 my-1">
<form>
<?php
if ($ques->have_posts()) {
while ($ques->have_posts()) {
$ques->the_post();
global $post;
$ID = $post->ID;
$option = get_post_meta($ID, "op1", true);
$nonce = wp_create_nonce("my_user_vote_nonce");
$link = admin_url('admin-ajax.php?action=my_user_vote&post_id=' . $ID . '&nonce=' . $nonce);
$ques_id = 'Q-' . $ID;
?>
<div id="<?php echo $ques_id ?>" class="questions">
<div class="question ml-sm-5 pl-sm-5 pt-2">
<h3><b><?php _e('Poll Survey'); ?></b></h3>
<div class="py-2 h5"><b class="msg"><?php the_title() ?></b></div>
<div class="ml-md-3 ml-sm-3 pl-md-5 pt-sm-0 pt-3" id="options">
<label class="options"><?php _e($option['op1']['op1']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op1']['op1']) ?>"> <span class="checkmark"></span> </label>
<label class="options"><?php _e($option['op2']['op2']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op2']['op2']) ?>"> <span class="checkmark"></span> </label>
<label class="options"><?php _e($option['op3']['op3']); ?> <input type="radio" name="framework" value="<?php esc_attr_e($option['op3']['op3']) ?>"> <span class="checkmark"></span> </label>
</div>
<div class="d-flex align-items-center pt-3">
<div class="ml-auto mr-sm-5">
<button class="btn btn-success">
<?php
echo '<a class="user_vote" data-nonce="' . $nonce . '" data-post_id="' . $ID . '" href="' . $link . '">submit</a>';
?>
</button>
</div>
</div>
</div>
</div>
<?php
}
}
?>
</form>
</div>
</div>
and this is my ajax to show and hide elements
jQuery(document).ready(function() {
jQuery("#poll").hide();
var count = 0;
jQuery(".start").click(function(e) {
jQuery("#poll").show();
jQuery(".start").hide();
});
jQuery(".user_vote").click(function(e) {
e.preventDefault();
option = jQuery('input[name="framework"]:checked').val();
post_id = jQuery(this).attr("data-post_id");
nonce = jQuery(this).attr("data-nonce");
var idArr = [];
jQuery(".questions").each(function() {
idArr.push(jQuery(this).attr("id"));
});
jQuery.ajax({
type: "post",
dataType: "json",
url: myAjax.ajaxurl,
data: {
action: "my_user_vote",
post_id: post_id,
nonce: nonce,
option: option,
},
success: function(response) {
if (response.type == "success") {
count++;
if (count < idArr.length) {
jQuery(".questions").hide();
jQuery("#" + idArr[count]).show();
} else {
jQuery("#my_poll").hide();
alert('Thank you for your time.')
}
} else {
alert("Your vote could not be added");
}
},
});
});
});
in this jquery ajax whene i click start button i display all questoins divs.
but i want display the first question div.
Does anyone have any solutions?
Change the on click event function like below;
jQuery(".start").click(function(e) {
jQuery(".start").hide();
jQuery("#poll:first").show(); // id selector!
});
Better way, wirte "poll" word into the class attribute, dont use same id more than one time. If you change the id and class of the elements, your code must be like this;
jQuery(".start").click(function(e) {
jQuery(".start").hide();
jQuery(".poll:first").show(); // class selector
});
Also, you can use $ character instead of Jquery;
jQuery("div") EQUAL $("div")
Another way to find first element;
$(".start").click(function(e) {
$(".start").hide();
$(".poll").eq(0).show(); // class selector
});

How to submit a form using AJAX?

I am trying to submit a form using ajax. However, it is not showing the message that the code is wrong. I push errors the same way on the entire website so that part works.
This is my code:
<script type="text/javascript" src="jquery.js"></script>
<div id="showerrors"></div>
<script type="text/javascript">
$(document).ready(function() {
setInterval(function () {
$('#showerrors').load('errors2.php')
}, 1000);
});
</script>
<form id="formoid" method="post" action="data/newpass.php">
<div class="row2">
<input type="email" class="form-control2" placeholder="email adres" aria-describedby="basic-addon1" name="email" required>
</div>
<div class="row2">
<input type="text" class="form-control2 pull-left" placeholder="Enter code" aria-describedby="basic-addon1" name="captcha" style="width: 70%;" required>
<div class="capbg1">
<input type="text" class="disable1b pull-right" value="<?php echo $capcode3;?>" name="captcha" style="width: 29%;" disabled>
</div>
</div>
<div class="row2"></div>
<div class="row2">
<button type="submit" class="w3-black pull-left" name="req_new_pw">Request new password</button>
</div>
</form>
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : { email: $('#email').val(), captcha: $('#captcha').val() },
});
});
</script>
// newpass.php - action in the form
<?php
error_reporting(E_ALL);
session_start();
ob_start();
$db = mysqli_connect(***);
if (isset($_POST['req_new_pw']))
{
$captcha = mysqli_real_escape_string($db, $_POST['captcha']);
$email = mysqli_real_escape_string($db, $_POST['email']);
if(isset($_SESSION['capcode3']))
{
if($_SESSION['capcode3'] != $captcha)
{
array_push($errors, "- Code is incorrect.");
}
}
}
?>
//errors.php
<?php if (count($errors) > 0) : ?>
<div class="isa_error">
<i class="fa fa-times-circle"></i>
<b>Oops..</b><br>
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
//errors2.php - display errors above form
<?php
include('errors.php');
if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</div>
</h3>
</div>
<?php endif ?>
When i submit the form, nothing happens.
What am i doing wrong?
You don't send $_POST['req_new_pw'] and you are asking if it's set.
You can use serialize() to send all form element by post:
<script type='text/javascript'>
$("#formoid").submit(function(event) {
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
$.ajax({
type: "POST",
url: "data/newpass.php",
data : $('#formoid').serialize(),
});
});
</script>
Make sure you are setting $_SESSION['capcode3'] either.
This works like a charm:
$("#formoid").submit(function(event) {
event.preventDefault();
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
type: "POST",
url : "data/newpass.php/",
data : form_data
});
});

insert data in database dynamically

$query = "select * from comments t1 inner join users t2 on t1.user_id = t2.UserId where usercomplain_id='$id'";
$run =mysqli_query($mysqli,$query);
while($row=mysqli_fetch_array($run))
{
$commentid = $row['comment_id'];
$comment = $row['comment'];
$username = $row['UserName'];
$userid1 = $row['UserId'];
$date = $row['CDate'];
$ageDate = time_elapsed_string($date);
?>
<div class="jumbotron" style="border:3px solid #2FAB9B; background-color:#68C8C6;">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<?php echo $ageDate; ?>
</div>
</div>
<br>
<label>Comment by <?php echo $username; ?></span></label><br>
<a class="reply" data-role="<?php echo $commentid; ?>">Reply</a>
<br>
<br>
<div style="width:63%; display:none;" class="replyForm" data-role="<?php echo $commentid; ?>">
<form method="post">
<textarea cols="100" rows="4"></textarea><br>
<br>
<input type="submit" name="reply" class="btn btn-primary" style="float:right" value="reply">
</form>
</div>
</div>
<script>
$(document).ready(function(){
$(".reply").click(function(){
var current = $(this).attr("data-role");
$('.replyForm[data-role="'+$(this).attr("data-role")+'"]').fadeIn();
});
});
</script>
<?php
if(isset($_POST['reply']))
{
echo "<script>alert('$commentid')</script>";
}
?>
<?php } ?>
it is a simple comment system with each comment there is a reply link on click on reply link a textbox is shown . I want to enter comment reply to database table therefore I want to get the record of the specific comment. How to do that with PHP.
this code should do what you want, completely dinamically
<div class="jumbotron comment-container" data-pk="<?php echo $commentid; ?>">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<em class="text-muted"><?php echo $ageDate; ?></em>
</div>
<div class="col-md-12">
<label>Comment by <?php echo $username; ?></label><br/>
<button class="btn btn-primary reply">Reply</button>
</div>
</div>
</div>
And here is the JS part. In order to reduce the code printed in the while loop, the reply form is cloned each time and appended where needed.
var reply_form = $('<div class="row replyForm-container"><div class="col-md-12">'+
'<form method="post" class="reply-form">'+
'<textarea class="form-control" rows="4">Prefilled content</textarea><br>'+
'<br>'+
'<button type="submit" name="reply" class="btn btn-primary" style="float:right" >Reply</button>'+
'</form>'+
'</div></div>');
$(".reply").click(function(){
$(this).hide();
var $container = $(this).closest('.comment-container');
var pk = $container.data('pk');
var rf_clone = reply_form.clone();
rf_clone.find('form').attr('data-pk', pk).data('pk', pk);
$container.append( rf_clone.hide().fadeIn(1000) );
});
// working with dynamical elements, we need to use delegation here
$(document).on('submit', '.reply-form', function(e){
e.preventDefault();
var reply_container = $(this).closest('.replyForm-container');
var pk = $(this).data('pk');
var reply = $(this).find('textarea').val();
console.log('Insert reply "'+reply+'" for comment ID: '+pk);
$.ajax({
type: "POST",
url: 'my_php_handler.php',
async: false,
dataType: "json",
data: {action: 'add-reply', commend_id: pk, reply_text: reply},
success: function (response) {
if( response ) {
reply_container.fadeOut('slow', function(){
var btn = reply_container.closest('.comment-container').find('button.reply');
$(this).remove(); //will remove the element after fadeOut completes
btn.show();
})
}
}
});
});
Check working Fiddle (ajax disabled)

HTML not showing in a div when called from ajax

This is the script of ajax I am using
mypage.php
$(".sales_anchor").click(function(e)
{
e.preventDefault();
var store_username = $("#storeUsername").val();
var store_id = $("#storeID").val();
var sale_id = $(this).attr('id');
$.ajax(
{
url: 'scripts/sales_sales_products.php',
data: {"store_id": store_id, "sale_id": sale_id,"store_username": store_username},
method: 'POST',
success: function(data)
{
data = $(data).find("div#mainContentOfSale");
$("#contents").html(data);
console.log(data);
}
});
})
<div id="contents"></div>
And
sales_sales_products.php
include_once '../includes/custom_functions.php';
$stmtgetallsales = $mysqli->prepare("SELECT * FROM store_sales ss
INNER JOIN store s ON s.store_id=ss.store_id
WHERE s.store_id=?");
$stmtgetallsales->bind_param("i",$_POST['store_id']);
$stmtgetallsales->execute();
$getallsales = $stmtgetallsales->get_result();
$sales_rows = $getallsales->num_rows;
$stmtgetallsales->close();
?>
<script src="js/3.1.1/jquery.min.js"></script>
<script src="../js/jquery.countdown.min.js"></script>
<div class="container" id="mainContentOfSale">
<?php while($allsales = $getallsales->fetch_assoc())
{
$stmtgetsaleproducts = $mysqli->prepare("SELECT * FROM store_products sp
INNER JOIN store_sale_products ssp ON sp.product_id = ssp.product_id
WHERE ssp.sale_id=? AND sp.store_id=?");
$stmtgetsaleproducts->bind_param("ii",$allsales['sale_id'],$_POST['store_id']);
$stmtgetsaleproducts->execute();
$getsaleproducts = $stmtgetsaleproducts->get_result();
$sale_product_rows = $getsaleproducts->num_rows;
$stmtgetsaleproducts->close();
?>
<script>
$(document).ready(function() {
$('.products_title').hide();
$(".timer").each(function() {
var time = this.id;
var timeLeft = time.split('-').reverse().join('-');
$(this).countdown(timeLeft, function(event) {
$(this).text(event.strftime("%D days %H hours %M minutes %S seconds remaining"));
});
})
});
</script>
<div class="sale_title">
<h2 class="title" id="sale_products"><?php echo $allsales['sale_name']; ?></h2> <span class="badge"><?php echo $sale_product_rows; ?></span> <span class="timer" id="<?php echo $allsales['sale_till']; ?>"></span></div>
<div class="sale_title"><span class="discount">Discount: <span class="color-text"><?php echo $allsales['sale_discount']; ?></span>%</span></div>
<div class="product_area wrapper ">
<?php while($saleproducts = $getsaleproducts->fetch_assoc()){?>
<div class="product">
<a href="<?php echo " index.php?store=".$_POST['store_username']." &view=single&product=".$saleproducts['product_id']; ?>">
<div class="product-image">
<img src="<?php echo image_check($saleproducts['product_image1']); ?>" />
</div>
</a>
<div class="product-details">
<div class="product-name">
<a class="name" href="<?php echo " index.php?store=".$_POST['store_username']." &view=single&product=".$saleproducts['product_id']; ?>"><span><?php echo substr($saleproducts['product_name'], 0, 20); ?></span></a>
</div>
<div class="product-price">
<span class="price"># Rs. <?php echo sale_price($allsales['sale_discount'],$saleproducts['product_price']); ?>/</span>
</div>
</div>
</div>
<?php }?>
<?php } ?>
When I call the anchor tag with class sales_anchor it calls this script and in the inspect element and in network tab when I check the script it does populated the data and html and everything is fine. But it isn't getting called in the current page and in contents div. What am I doing wrong?
You are encountering an JSON.parse error in your screenshot. (Notice the red bar above your result window saying SyntaxError: JSON.parse: unexpected character at line 1 column 9 of the JSON data)
This is because $.ajax is trying to parse the response as a JSON string to an object (the default behaviour).
Please change your ajax function to this:
$(".sales_anchor").click(function(e)
{
e.preventDefault();
var store_username = $("#storeUsername").val();
var store_id = $("#storeID").val();
var sale_id = $(this).attr('id');
$.ajax(
{
url: 'scripts/sales_sales_products.php',
dataType: "text",
data: {"store_id": store_id, "sale_id": sale_id,"store_username": store_username},
method: 'POST',
success: function(data)
{
data = $(data).find("div#mainContentOfSale");
$("#contents").html(data);
console.log(data);
}
});
})
<div id="contents"></div>

Website login with Ajax

Here is a screenshot of the console.I am a beginner in working with json and Ajax and I am trying to write a login for my website, but I don't know why it is not working.
login-register.js
function loginAjax(){
$.post( "login.js", function( data ) {
if(data == 1){
window.location.replace("/sportime.html");
} else {
shakeModal();
}
});
}
login.js
$(document).ready(function()
{
$('#login').click(function()
{
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0)
{
$.ajax({
type: "POST",
url: "ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function(){ $("#login").val('Connecting...');}
});
}
return false;
});
});
ajaxLogin.php
<?php
include("conectare.php");
session_start();
if(isset($_POST['username']) && isset($_POST['password']))
{
// username and password sent from Form
$username=mysqli_real_escape_string($mysqli,$_POST['username']);
//Here converting passsword into MD5 encryption.
$password=md5(mysqli_real_escape_string($mysqli,$_POST['password']));
$result=mysqli_query($mysqli,"SELECT uid FROM users WHERE username='$username' and password='$password'");
$count=mysqli_num_rows($result);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
// If result matched $username and $password, table row must be 1 row
if($count==1)
{
$_SESSION['login_user']=$row['uid']; //Storing user session value.
echo $row['uid'];
}
}
?>
sportime.php
<?php
session_start();
if(!empty($_SESSION['login_user']))
{
header('Location: sportime-loggedin.php');
}
?>
and this is the modal for the login from sportime.php
<div class="modal fade login" id="loginModal">
<div class="modal-dialog login animated">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Login</h4>
<div class="content text-center"><h5>Use your University credentials</h5></div>
</div>
<div class="modal-body">
<div class="box">
<div class="content">
<div class="error"></div>
<div class="form loginBox">
<form method="post" action="" onsubmit="loginAjax(); return false;" accept-charset="UTF-8">
<input id="email" class="form-control" type="text" placeholder="University ID" name="id">
<input id="password" class="form-control" type="password" placeholder="Password" name="password">
<input class="btn btn-default btn-login" type="submit" value="Login">
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Why are you trying to post to a js file?
function loginAjax(){
$.post( "login.js", function( data ) {
if(data == 1){
window.location.replace("/sportime.php");
} else {
shakeModal();
}
});
}
Your loginAjax function should look like this
function loginAjax() {
var username = $("#email").val();
var password = $("#password").val();
var dataString = 'username=' + username + '&password=' + password;
if ($.trim(username).length > 0 && $.trim(password).length > 0) {
$.ajax({
type: "POST",
url: "ajaxLogin.php",
data: dataString,
cache: false,
beforeSend: function() {
$("#login").val('Connecting...');
}
}).success(function(data) {
if (parseInt(data) > 1) {
window.location.replace("/sportime.html");
} else {
shakeModal();
}
});
}
return false;
}
EDIT
You have misplaced the ids.
Replace
var username = $("#username").val();
with var username = $("#email").val();

Categories