I am following a series of tutorials on youtube by howcode. It is about making a social network. When it comes to like/comment, he uses an api. However, this is not working for me, I want to use a normal ajax. I want to submit a like request from:
<form>
if (!DB::query('SELECT post_id FROM post_likes WHERE post_id=:postid AND user_id=:userid', array(':postid'=>$post['id'], ':userid'=>$userid))) {
echo "<input type='submit' name='like' value='Like' data-id=".$post['id'].">";
} else {
echo "<input type='submit' name='unlike' value='Unlike' data-id=".$post['id'].">";
}
echo "<span>".$post['likes']." likes</span>
</form>
reaching this ajax:
$('[data-id]').click(function() {
var buttonid = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "index.php?postid=" + $(this).attr('data-id'),
processData: false,
//ScontentType: "application/json",
data: '',
success: function(r) {
console.log("hhhhhhhhhhhhhhhh")
},
error: function(r) {
console.log(r)
}
});
});
then going here:
if (isset($_GET['postid'])) {
Post::likePost($_GET['postid'], $userid);
}
You need to add a selector i.e class or an id. to the element you want to use the jquery selector on & then bind the event on that selector. Please check the below updates to your code. Also you need to add the preventDefault method to prevent the original event of that selector.
<form>
if (!DB::query('SELECT post_id FROM post_likes WHERE post_id=:postid AND user_id=:userid', array(':postid'=>$post['id'], ':userid'=>$userid))) {
echo "<input class = "submit-class" type='submit' name='like' value='Like' data-id=".$post['id'].">";
} else {
echo "<input class = "submit-class" type='submit' name='unlike' value='Unlike' data-id=".$post['id'].">";
}
echo "<span>".$post['likes']." likes</span>
</form>
AJAX
$('.submit-class').click(function(e) {
e.preventDefault();
var buttonid = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "index.php?postid=" + $(this).attr('data-id'),
processData: false,
//ScontentType: "application/json",
data: '',
success: function(r) {
console.log("hhhhhhhhhhhhhhhh")
},
error: function(r) {
console.log(r)
}
});
});
Related
I have an ajax request where I register a user (wordpress). I want the user id to be sent back to the success response, but it just shows undefined, or blank in the case below:
$(document).on('submit', '.register_user_form', function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
dataType: 'html',
data: {
action: 'register_user_form',
currentUserName: $("#First_Name").val() + " " + $("#Last_Name").val(),
currentUserEmail: $("#email").val(),
currentUserPassword: $("#password").val(),
},
success: function(res) {
console.log(res);
}
});
});
PHP function (wordpress):
function register_user_form() {
$user_login = $_POST['currentUserName'];
$user_email = $_POST['currentUserEmail'];
$user_pass = $_POST['currentUserPassword'];
$userdata = compact( 'user_login', 'user_email', 'user_pass' );
$user_id = wp_insert_user($userdata);
echo 'this doesnt get returned';
wp_die();
}
add_action('wp_ajax_register_user_form', 'register_user_form');
add_action('wp_ajax_nopriv_register_user_form', 'register_user_form');
I have tried echo json_encode(''); but that doesn't work either. fyi - the user does get registered
So I'm building a social network as a personal hobby but, recently, when I try to Like a post the console log returns that error above. The code was working just fine in the last days but out of no where this error popped up.
Restapi code for liking a post:
if ($_GET['url'] == "likes")
{
$postId = $_GET['id'];
$token = $_COOKIE['SNID'];
$likerId = $db->query('SELECT user_id FROM tokens WHERE token=:token', array(':token'=>sha1($token)))[0]['user_id'];
if (!$db->query('SELECT user_id FROM post_likes WHERE post_id=:postid AND user_id=:userid', array(':postid'=>$postId, ':userid'=>$likerId))) {
$db->query('UPDATE posts SET likes=likes+1 WHERE id=:postid', array(':postid'=>$postId));
$db->query('INSERT INTO post_likes VALUES (\'\', :postid, :userid)', array(':postid'=>$postId, ':userid'=>$likerId));
//Notify::createNotify("", $postId);
} else {
$db->query('UPDATE posts SET likes=likes-1 WHERE id=:postid', array(':postid'=>$postId));
$db->query('DELETE FROM post_likes WHERE post_id=:postid AND user_id=:userid', array(':postid'=>$postId, ':userid'=>$likerId));
}
echo "{";
echo '"Likes":';
echo $db->query('SELECT likes FROM posts WHERE id=:postid', array(':postid'=>$postId));
echo "}";
}
script desing:
$.ajax({
type: "GET",
url: "restapi/posts",
processData: false,
contentType: "application/json",
data: '',
success: function(r) {
var posts = JSON.parse(r)
$.each(posts, function(index) {
$('.timelineposts').html(
$('.timelineposts').html() + ' <li class="list-group-item" id="'+posts[index].postId+'" style="border-color: #cbcbcb;"><blockquote class="blockquote"><p class="mb-0" style="color: rgb(0,0,0);">'+posts[index].PostBody+'</p><footer class="blockquote-footer">Posted by '+posts[index].PostedBy+' on '+posts[index].PostDate+'</footer></blockquote><button data-id="'+posts[index].postId+'" class="btn btn-primary" type="button" style="background-color: rgba(0,0,0,0);color: rgb(0,0,0);width: 142px;font-family: Alegreya, serif;" > <i class="icon-fire" data-bs-hover-animate="rubberBand" style="color: rgb(36,0,255);" ></i> '+posts[index].Likes+' likes</button><button class="btn btn-primary" type="button" style="background-color: rgba(0,0,0,0);color: rgb(0,0,0);width: 142px;font-family: Alegreya, serif;" onclick="showCommentsModal()" data-postid="'+posts[index].postid+'" > <i class="typcn typcn-pencil" data-bs-hover-animate="rubberBand" style="color: rgb(255,0,0);"></i> Comentários</button> </li> </ul> '
)
$('[data-postid]').click(function() {
var buttonid = $(this).attr('data-postid');
$.ajax({
type: "GET",
url: "restapi/comments?postid=" + $(this).attr('data-postid'),
processData: false,
contentType: "application/json",
data: '',
success: function(r) {
var res = JSON.parse(r)
showCommentsModal(res);
},
error: function(r) {
console.log(r)
}
});
});
$('[data-id]').click(function() {
var buttonid = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "restapi/likes?id=" + $(this).attr('data-id'),
processData: false,
contentType: "application/json",
data: '',
success: function(r) {
var ress = JSON.parse(r)
$("[data-id='"+buttonid+"']").html(' <i class="icon-fire" data-bs-hover-animate="rubberBand" style="color: rgb(36,0,255);"></i> '+ress.likes+' likes</span>')
},
error: function(r) {
console.log(r)
}
});
})
})
},
error: function(r) {
console.log(r)
}
});
});
Already verify all queries and they work fine in the sql.
EDIT::
Try
echo"<pre>";print_r($_GET); exit();
and see if you get any data in the backend
when you send data form the backend, do so in the following format
function listOfComments(){
$response=[
"success"=>0,
"message"=>"",
"data"=>[]
];
//database queries
if($databaseResponse){
$response=[
"success"=>1,
"message"=>"",
"data"=>$databaseResponse
];
}else{
$response["message"]=>"No Data"
}
return json.encode($response);
}
On the front end in javascript you could do
var ress = JSON.parse(r);
if(ress.success){
// render UI
}else{
alert(ress.message);
}
I'd be willing to help you out if you could share the link to your git hub repo.
Use https://json2html.com/ to render data on the front end.
Use onClick event on a class and not a custom attribute.
With this code I want to insert and move a file into a folder but when I choose a file and upload it shows me an error in my console:
Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.
How can I solve this problem? Please help me. Thank You
<input type="file" id="multiFiles" name="files" />
<button id="upload_file_multiple" class="btn btn-success add-btn update-btn">Upload</button>
$("#upload_file_multiple").click(function(event) {
event.preventDefault();
var form_data = new FormData($("#multiFiles"));
var id = "<?php echo $this->uri->segment(3) ?>";
jQuery.ajax({
type: "POST",
url: "<?php echo base_url() ?>syllabus/UploadFile/" + id,
data: form_data,
processData: false,
contentType: false,
success: function(response) {
$('#afx_khjk').html(response);
},
error: function(response) {
$('#afx_khjk').html(response);
}
});
});
public function UploadFile($id)
{
if (isset($_FILES['files']) && !empty($_FILES['files']))
{
$rename = 'file_no-'.time().$_FILES["files"]["name"];
move_uploaded_file($_FILES["files"]["tmp_name"], 'uploads/syllabus/' . $rename);
$data = array(
'pdf'=>$rename,
'subjectID'=>$id,
'unique_id'=>time()
);
$this->db->insert('sylabus_pdf',$data);
$insert_id = $this->db->insert_id();
echo 'File successfully uploaded : uploads/syllabus/' . $rename . ' ';
$this->commondata($id);
}
else
{
echo 'Please choose at least one file';
}
}
The error is because the FormData constructor expects an FormElement object, not a jQuery object containing an input.
To fix this create the FormData object with the empty constructor and use append() to add your file:
var input = document.querySelector('#multiFiles');
var form_data = new FormData();
for (var i = 0; i < input.files.length; i++) {
form_data.append('files[]', input.files[i]);
}
Alternatively you can make this more simple by providing the form to the constructor. That way the data in all form controls will be included for you automatically.
var form_data = new FormData($('#yourForm')[0]);
HTML
<form id="frm_upload_file">
<input type="file" id="multiFiles" name="files" />
<button type="submit" id="upload_file_multiple" class="btn btn-success add-btn update-btn">Upload</button>
</form>
Ajax
$("#frm_upload_file").submit(function (event) {
event.preventDefault();
var id = "<?php echo $this->uri->segment(3) ?>";
var form_data = new FormData(this);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url() ?>syllabus/UploadFile/" + id,
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function (response) {
$('#afx_khjk').html(response);
},
error: function (response) {
$('#afx_khjk').html(response);
}
});
});
I'm attempting to dynamically update a notice after the cart is updated via ajax. I can't seem to figure out how to re-update all variables so the calculation loop could run again. I tried wrapping the if statement into a function and calling that again inside of updated_wc_div but that didn't work.
Any suggestions?
( function($) {
var membership_price = membership.price;
//grab cart total from html
var total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
compared_price = parseInt(membership_price) - total;
//everything runs fine on load.
if ( total < membership_price ) {
message = 'For <strong>$'+ compared_price +'</strong> more, gain access to unlimited downloads. Become a member!';
notice = '<div class="woocommerce-info">' + message + '</div>';
$('.woocommerce-notices-wrapper').html(notice);
}
//running this to know when ajax is called
$(document.body).on('updated_wc_div',function( event ){
$('.woocommerce-notices-wrapper').empty();
total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
//I believe problem is here, it doesn't update variable so it could loop again.
});
} )(jQuery);
this is how I dynamically update an object after ajax call is being called:
function getCart(user_id) {
$.ajax({
type: "POST",
url: "get_total_cart.php",
data: {
'user_id': <?php echo $user_id; ?>
},
beforeSend: function() {},
success: function(response) {
var user = JSON.parse(response);
var total_cart = parseInt(user.total_cart);
$("#total_cart").html(total_cart);
}
});
}
function addCart(product_id, user_id) {
$.ajax({
type: "POST",
url: "add_cart.php",
data: {
'product_id': product_id,
'user_id': user_id
},
beforeSend: function() {},
success: function(response) {
getCart(user_id);
}
});
}
$(document).ready(function() {
$(".se-pre-con").fadeOut("slow");
getCart(<?php echo $user_id; ?>);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="total_cart">Total Cart</div>
<input type="button" name="add_cart" id="add_cart" value="Add to Cart" onclick="addCart('<?php echo $product[id]; ?>', '<?php echo $user_id; ?>')" class="btn btn-info">
I hope this helps.
Cheers.
Simply you have to put your function inside the ajax function or make the ajax function "async:false"
$.ajax({
type: "POST",
url: "",
async:false, // <======== remove asynchronous property
data: {},
success: function(result) {
}
});
////////////////////////////////////////////////
$.ajax({
type: "POST",
url: "",
data: {},
success: function(result) {
// Or put your function here
}
});
I am working on Yii2 and having a problem with returning the content of the javascript method to be sent when using the Html::a -hyperlink
The javascipt is in order to obtain the selected value of the checkboxes and it is outputting correctly.
<script>
function getNewPermissions() {
var permissions = '';
var rows = $(document).find('.permission');
$.each(rows, function (key, value) {
if($(value).find('input').prop('checked') == true)
permissions += value.id+'$&/';
})
permissions = permissions.substring(0, permissions.lastIndexOf("$&/"));
return permissions;
}
</script>
echo Html::a(Yii::t('app', 'Edit'), ['permissions/edit' ,'id'=> $name], [
'class' => 'btn btn-primary',
'onclick' =>'js:getNewPermissions()',
'data-method' => 'post',
'data' => [
'params' => ['newPerms'=>'js:getNewPermissions()','_csrf' => Yii::$app->request->csrfToken],
],
])
In the yii1 the value was read correctly from the params.
Just cant find any source to help get js in the params directly and the onclick does work.
in my project use another way
<a style="float:left;" class="btn btn-success" onclick="myFunction(this)"
type="<?php echo $value->id; ?>">
</a>
and use js function in end of layout
<script>
function updateSession(e)
{
var csrfToken = $('meta[name="csrf-token"]').attr("content");
var pid = e.getAttribute('type');
var key = e.getAttribute('title');
var pqty = $("#id_" + key).val()
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/updatecard') ?>',
type: 'Post',
data: {
productid: pid,
key: key,
pqty: pqty,
_csrf: csrfToken
},
success: function (data) {
alert(data);
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/getcard') ?>',
type: 'GET',
data: {
_csrf: csrfToken
},
success: function (data) {
$("#collapseCart").empty();
$("#collapseCart").append(data);
}
});
$.ajax({
url: '<?php echo Yii::$app->urlManager->createAbsoluteUrl('/site/getcardpage') ?>',
type: 'GET',
data: {
_csrf: csrfToken
},
success: function (data) {
$("#get_card2").empty();
$("#get_card2").append(data);
}
});
}
});
}
</script>