I trying to make like button for each recipe
but if i click like button browser said
xhr.send( ( options.hasContent && options.data ) || null );
return this errors
I don't know why this error occurred
this is my code in rails
application.js
function like(id){
$.ajax({
url:"/like/" + id,
type:"POST",
dataType:"json",
success: function(data){
if(data.result){
$("#countlike").html("likes " + data.count);
// $("#count").removeAttr('onclick');
// $("#count").attr('disabled', 'disabled');
}
}
});
}
route.rb
post '/like/:id'=>'recipes#like'
views/recipes/show.html.erb
<p>
<a id = "countlike" onclick="like(<%=#recipe.id%>)">Like it</a>
</p>
recipes_controller.rb
def like
likes = Recipe.find(params[:id]).likes
result = likes.create
render json:{result: result, count: likes.count}
end
It was work correctly in other project same code
Looks like you are missing your data attribute in you post ajax request that might be throwing the error.
function like(id){
$.ajax({
url:"/like/" + id,
type:"POST",
dataType:"json",
data: my_data, // <--- HERE
success: function(data){
if(data.result){
$("#countlike").html("likes " + data.count);
// $("#count").removeAttr('onclick');
// $("#count").attr('disabled', 'disabled');
}
}
});
}
Hope it helps. Cheers!
Related
when i want enter a city here, nothing happens, no error in my console, i don't know why
this is my code :
ajax.js
$(document).ready(function(){
$('#submitLocation').click(function(){
//get value from input field
var city = $("#city").val();
$.post('PHP/controller.php', {variable: city});
//check not empty
if (city != ''){
$.ajax({
url: "PHP/router.php",
// url :"http://api.openweathermap.org/data/2.5/weather?q=" + city +"&lang=fr"+"&units=metric" + "&APPID=697edce53ba912538458a39d776ca24e",
type: "GET",
dataType: "jsonp",
success: function(data){
console.log(data);
console.log(data.weather[0].description);
console.log(data.main);
console.log(data.main.temp);
var information = show(data);
$("#show").html(information);
}
});
}else{
$('#error').html('Field cannot be empty');
}
});
})
function show(data){
return "<h3>Témpérature: "+ data.main.temp +"°C"+"</h3>" + "<h3>"+ data.weather[0].description +"</h3>";
}
this is my router.php, my js call the router
<?php
require('../PHP/controller.php');
if (isset($_GET['city'])) {
return getWeatherCity($_GET['city']);
}
else {
echo'Error';
}
?>
i know that i can do this only with js or only with php but i want use both of them.
Do you have any request happening in the "Requests" tab of your DevTool?
You should see a request towards PHP/router.php and the associated status code. Given that you might collect clues to debug what's going on.
I load replies to comments asynchronously in php like in youtube comments.
The ajax handler for forms (ie reply forms) loaded like this is not working. e.preventDefault() is not working. The forms are submitted to the action page itself and page is redirected to action url. If i edit a reply. It works but page is redirected to the action url. This happens only for the ajax loaded replies. The same handler is used for regular comments and it works fine.
A comment :
A comment with loaded replies :
When a reply is edited it just goes to /path/to/submit.php and shows the value of json output like this
result on submitting a reply form
Ajax to show or hide replies:
//load or hide replies
function loadmore(id) {
var val = $('#' + id).data("value");
var count = $('#' + id).data("count");
$.ajax({
type: 'post',
url: '/path/to/submit.php',
data: {
replyof: val
},
success: function(response) {
var content = document.getElementById("show" + val);
content.innerHTML = response;
var clicknum = $('#' + id).data("clicknum");
$('#' + id).data("clicknum", 2);
if (!$("#show" + val).is(":hidden") && clicknum != 1) {
document.getElementById(id).innerHTML =
' View all ' + count + ' replies <i class="fas fa-angle-down"></i>';
$("#show" + val).hide();
} else {
document.getElementById(id).innerHTML =
'Hide all replies <i class="fas fa-angle-up"></i>';
$('#show' + val).show();
}
}
});
}
I use the same class for comments as well as replies and ajax submit the form to the same page /path/to/submit.php using
eg
<form class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
The form handler
$(".replyform").submit(function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
The .replyform render by ajax so use on instead of traditional way
$(document).on("submit", ".replyform",function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
I think your calling your form wrong. You need an id attribute. I don't think you can call it by it's class name like that.
<form id="myForm" class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
$("#myForm").submit(function(e) {
...rest of script.
I am trying to write a .ajax request through a form to log in. When I submit my form, nothing happens with either the success or error functions. I notice that if I put an alert box after the .ajax call it does not work either. I would expect, that if I am just incorrectly putting the data, I would at least expect the error alert box to show up? Here is my code:
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(e){
$.ajax({
type: "POST",
url: "myurl",
data: $(this).serialize() + "&client_type=" + clienttype,
success: function(data) {
alert("sent" + data);
},
error: function(){
alert("Did not work");
}
});
e.preventDefault();
});
});
I noticed you're already using JQuery. So perhaps use the built in post function. Example below:
Also side note: You've got a slight type in your variable: data: $(this).serialize() + "&client_type=" + clienttype, clienttype was declared with a capital T: clientType
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(e){
e.preventDefault();
$.post("myurl",{data:$(this).serialize(),client_type:clientType},function(data){
console.log("Date returned from request:",data);
// Returns JSON Data. So data.clientType.
},'json');
});
});
If you add in a trigger to cancel the page from being submitted, it should work (return false;), take a look below.
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(){
$.ajax({
type: "POST",
url: "myurl",
data: $(this).serialize() + "&client_type=" + clienttype,
success: function(data) {
alert("sent" + data);
},
error: function(){
alert("Did not work");
}
});
return false;
});
});
I have a website where I rely on a lot of custom API call. My API return always an XML.
Currently, at the start of each and every $.get or $.post I call, I have this snippet :
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
However, I feel this code to be much redundant on one of my page, it's used 15 times.
I tried to use the $(document).ajaxSuccess() but the event.stopPropagation don't seem to work here
Is there a way to "intercept" each and every ajax call responses, do some stuff and possibly prevent the call to other defined success functions ?
I assume that you have something like this in many places in your code
$.ajax({
method: "GET",
url: "someurl.html",
dataType: "xml",
success : function() {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
// ...
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
});
you could create a generic custom ajax function tha you can re-use
function baseAjaxCall(option, sCb) {
var ajaxOptions = {
method: option.method || "GET",
url: option.url,
dataType: option.dataType || "xml",
success : function(data) {
var root = $($.parseXML(data)).find("Response");
if (root.children("Type").text() == "Error") {
toastr.error(root.children("Content").text(), "Error " + root.children("ReturnCode").text());
return;
}
else {
sCb(root);
}
},
error : function(qXHR, textStatus, errorThrown){
toastr.error(errorThrown, "Error " + qXHR.status);
}
};
//you can check for optional settings
if(option.contentType !== undefined){
ajaxOptions.contentType = option.contentType;
}
$.ajax(ajaxOptions);
}
everywhere in your code you can re-use the baseAjaxCall function
baseAjaxCall({ url: "someurl.html" }, function(root){
// no need to chek for errors here!
});
Hope it's helps!
I'm trying to 'ajaxify' commenting in WordPress using this tutorial Ajaxify WordPress Comments
Here is my PHP handler:
function ajaxify_comments( $comment_ID, $comment_status ){
if( ! empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' ) {
//If AJAX Request Then
switch( $comment_status ) {
case '0':
//notify moderator of unapproved comment
wp_notify_moderator( $comment_ID );
case '1': //Approved comment
echo "success";
$commentdata = &get_comment( $comment_ID, ARRAY_A );
$post = &get_post( $commentdata['comment_post_ID'] );
wp_notify_postauthor( $comment_ID, $commentdata['comment_type'] );
break;
default:
echo "error";
}
exit;
}
}
add_action( 'comment_post', 'ajaxify_comments', 20, 2 );
And here is my script:
jQuery('document').ready(function($){
var commentform=$('#commentform'); // find the comment form
commentform.prepend('<div id="comment-status" ></div>'); // add info panel before the form to provide feedback or errors
var statusdiv=$('#comment-status'); // define the infopanel
commentform.submit(function(){
//serialize and store form data in a variable
var formdata=commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl=commentform.attr('action');
//Post Form with data
$.ajax({
type: 'post',
url: formurl,
data: formdata,
error: function(XMLHttpRequest, textStatus, errorThrown){
statusdiv.html('<p class="ajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
},
success: function(data, textStatus){
if(data=="success")
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
else
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
commentform.find('textarea[name=comment]').val('');
}
});
return false;
});
});
Every time I post a comment, I get: "Please wait a while before posting your next comment". Hoping somebody can tell me what I'm doing wrong?
Try this:
jQuery('document').ready(function($){
var commentform=$('#commentform'); // find the comment form
commentform.prepend('<div id="comment-status" ></div>'); // add info panel before the form to provide feedback or errors
var statusdiv=$('#comment-status'); // define the infopanel
commentform.submit(function(){
//serialize and store form data in a variable
var formdata=commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl=commentform.attr('action');
//Post Form with data
$.ajax({
type: 'post',
url: formurl,
data: formdata,
error: function(XMLHttpRequest, textStatus, errorThrown)
{
statusdiv.html('<p class="ajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
},
success: function(data, textStatus){
if(data == "success" || textStatus == "success"){
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
}else{
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
commentform.find('textarea[name=comment]').val('');
}
}
});
return false;
});
});