JQuery doesn't work after adding ajax (Node.js, PUG) - javascript

I have been trying to add like functionality to my blog posts website.
When i click on the numbers of like link it should run ajax call.
In my server.js file i have a function that receives post request updates number of likes for the given post in mongodb database.
I have set name attribute of the link to equal post_id so that i can modified that post in databse.
html
head
style
include ../styles/home.css
link(rel='stylesheet', href='https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css')
script(src='https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js')
script(src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js')
script.
$(document).ready(function(){
$('.number_of_likes').click(function(e){
e.preventDefault();
alert('This part wont run');
$.ajax(
type: 'POST',
url: '/like',
data: {'post_id' : $(this).attr('name')},
success: function(result){
alert('it works');
},
dataType: 'json'
);
});
});
h2 Welcome to the main page
br
br
br
br
br
mixin postCard(postData)
.post_container
.row
.col.s12.m6
.card.blue-grey.darken-1
.card-content.white-text
span.card-title #{postData.title}
p= postData.content
.card-action
a(href='#') #{postData.username}
a(href='/delete_post/'+postData._id) Delete
a(href='' name=postData_id class='number_of_likes') #{postData.likes}
each post in result
+postCard(post)
But click event doesn't get fired.

The issue is probably because this is invalid syntax causing the entire application to come to a halt:
$.ajax(
type: 'POST',
url: '/like',
data: {'post_id' : $(this).attr('name')},
success: function(result){
alert('it works');
},
dataType: 'json'
);
You need to pass it as an object with the data between { and } like this:
$.ajax({
type: 'POST',
url: '/like',
data: {'post_id' : $(this).attr('name')},
success: function(result){
alert('it works');
},
dataType: 'json'
});

Related

Updating Github Issue Body with Ajax

I've been successfully able to pull an issue, but not update it. My goal is to update the body of the issue with a new string. Per the documentation here I understand I need to do a "PATCH". This is what I have so far:
var patchedIssue = $.ajax({
dataType: "json",
type: 'PATCH',
body: newBodyText,
url: issueURL,
success: function(data){
console.log("success");
}
});
But when I do that in the network tab I see a Status code of 422: Unprocessable Entity. Response message from the API is "Invalid request.For 'links/1/schema', nil is not an object."
If I remove the "body" line I get the same error
Any thoughts? To get the body text I literally did the same as above but with "GET" instead of patch, and then the body text was "patchedIssue.responseJSON.body"
Figured it out, needed a "data" key.
This successfully replaced the body text:
patchedIssue = $.ajax({
dataType: "json",
type: 'PATCH',
url: issueURL,
data: '{"body":"test"}',
success: function(data){
console.log("success?");
}
});

Ajax query not working when file is in a sub directory

I am trying to use the following for a simple database query
$.ajax({
url: "trackingcodedata.php",
type: "GET",
dataType: 'json',
data:{option:1},
success: function(data) {
$('#js-tracking-code').val(data.tracking_code[0].js_tracking_code);
},
error: function(){
console.log("failed");
}
});
the url works fine in this form. What I really want to do is have the file in a sub directory. And call it the same way.
$.ajax({
url: "db/trackingcodedata.php",
type: "GET",
dataType: 'json',
data:{option:1},
success: function(data) {
$('#js-tracking-code').val(data.tracking_code[0].js_tracking_code);
},
error: function(){
console.log("failed");
}
});
The second version with the file in the db sub directory gives me a 500 error. The first one works fine. ????

How to pass data using jQuery/ Ajax to a URL

How to pass the fetched data using $.get() from a URL to a particular URL with query_string that can be retrieved using $_GET() in PHP. I'm using following but not working. I want to pass the fetched data into following parameter http://example.com/data?data=FETECHED_DATA
<?php
$ip_address=$_SERVER['REMOTE_ADDR'];
echo '<script>
$.get( "http://ipinfo.io/'.$ip_address.'/org", function( data ) {
$.ajax({
type: "GET",
url: "http://example.com/data",
data: data,
success: success,
dataType: dataType
});
});
</script>';?>
Well, don't recommended PHP to fetch and send data
I believe this will do what you want
<?php
$ip_address=$_SERVER['REMOTE_ADDR'];
echo '<script>
$.get("http://ipinfo.io/'.$ip_address.'/org", function(data) {
$.ajax({
type: "GET",
url: "http://example.com/data",
data: {data : data},
success: success,
dataType: dataType
});
});
</script>';?>
the only change is data: data changed to data: {data: data}
that's a lot of data :p
see this cut down mock up, http://jsfiddle.net/cm8o5dk8/ if you have a decent browser that can show you the network "usage" you'll see that the mockup fails trying to GET http://example.com/data?data=AS15169+Google+Inc.%0A - the %0A comes back from ipinfo.io
Thanks it worked
$.get("http://ipinfo.io/8.8.8.8/org", function(data) {
$.ajax({
type: "GET",
url: "http://example.com/data",
data: {data : data},
success: function() {},
dataType: 'json'
});
});

Using AJAX to collect a link from a php page and update image

I have a php page which spits out a profile picture URL from a instagram account that is supplied. For example if you went..
.com/ajax_check_instagram.php?username=tom
the page would return
http://instagram.com/profilepic.png
I then have an ajax call which im trying to manipulate so the sucess function updates an image source.
//Add a loading image in the span id="availability_status"
var link = '';
$.ajax2({ //Make the Ajax Request
type: "POST",
cache: false,
dataType: "json",
url: "/ajax_grab_instagram.php", //file name
data: "username="+ username, //data
success: function(server_response){
link = server_response;
$("#profilepic").attr("src","link");
}
});
}
How would I format the server_response line and jquery line?
In your PHP/AJAX file you need to return the URL of the picture. Then in your jQuery AJAX request...
It's pretty much there as is except you have link encapsulated within double quotes.
$.ajax({
type: "POST",
cache: false,
dataType: "json",
url: "/ajax_grab_instagram.php",
data: "username="+ username,
success: function(response) {
$("#profilepic").attr("src",response);
}
});
I have changed it to response in my example.
link is a variable, not a string.
$("#profilepic").attr("src", link); // link should not be in quotes

AJAX request not working properly

Hey guys and gals,
I have a form that I would like to use AJAX to submit. For the callback function basically what I want to happen is, the form elements disappear (.hide) and are replaced by a div element (which will ready success or something of that nature). I then want the function to pause for 5 seconds and then redirect to a different URL.
The AJAX request successfully submits (as I receive an e-mail to the specified address as I should) but the callback function is not carrying out properly. Any suggestions?
$(document).ready( function () {
var $form = $('form');
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
setTimeout(5000);
$(".button").addEventListener("click", function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
})
}
})
}
}
**
UPDATE #1
**
This is the only error code that I am getting when I initially load the website (I've heard these errors only pop up in the dev tools and do not affect the user?)
But then when I submit the form I get this error code
I've also updated my JavaScript to the below code, taking advice from a few people who posted, it's still not working 100% though
$(document).ready(function() {
var $form = $('form');
$form.submit(function(){
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
}
});
setTimeout(function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
}, 5000)
});
});
Joey
setTimeout usage is wrong.
See :
$(document).ready( function () {
var $form = $('form');
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
$("#mc-embedded-subscribe-form").hide("slow");
$("#form").html('<div class="some-class">Some text that shows up upon successful AJAX request</div>')
setTimeout(function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
}, 5000);
}
})
}
});
Further, the following should ideally be declared separately, if you want the user to click a link and go after ajax success.
$(".button").addEventListener("click", function(){
window.location.href='http://www.neuyear.net/collections/time-domination-products';
})

Categories

Resources