Value attribute of html element is undefined - javascript

Why is name undefined?
$('#langs li').click(function(){
var name = $(this).attr('value');
$.ajax({
type: "POST",
url:'test.php',
data: 'name='+name,
success:function(raspuns){
//$('#content1').html(raspuns);
var ras = raspuns;
$.ajax({
type: "POST",
url: "index.php",
data: 'ras='+ras;
)};
}
});
});

You can check a few things:
make sure you have data before sending. you have value attribute on li? or if you want to get li contents, use html() or txt(). But probably you want to get input field value inside li?. then use $(this).find("input").val() if you have just one input inside.
Then others to check:
1) Visit http://example.com/test.php to make sure it echoes the response correctly. You may have error in php or the link may not be accessible.
2) Your url is like this: http://example.com/test.php ? It is also fine if you have a virtual host in your local machine like http://example.local/test.php. But it will not work if you have something like
http://localhost/mysite/test.php
unless you correct your path in ajax call to a full link.
3) Make sure your javascript doesnt fail before sending. I mean, are you able to do alert(name) ? You can also use beforeSend() above success to check if you are ending data correctly.
4) Make sure you are not trying to make a cross domain ajax request as you can't do so with POST.
5) May try using "/test.php" instead of "test.php" although it wouldn't be the problem, I think.
You can also use console to see what is going on.

If what you mean is that raspuns seems to be undefined, maybe it's because you did not echo your response from test.php?
test.php
...
echo 'this is my response';
AJAX call
$.ajax({
...
success: function(raspuns) {
// raspuns == 'this is my response'
}
});
And also, if you're passing POST data, I think it would be better if you pass a JSON object, like so:
$.ajax({
url: 'test.php',
type: 'POST',
data: {name: name},
...
});

li elements don't support a value attribute. Perhaps you're looking for an input or the contents of li via .html().
See in this demo that name is undefined: http://jsbin.com/IzOXiJOZ/2/edit

Related

Sending an array/set via to PHP via $.ajax. PHP adding a number

Im trying to send an array to the PHP script:
usedAnswers = [1,2];
// funtion for displaying a question
displayQuestion = () => {
$.ajax({
url: "backend/retriveData.php",
data: {usedAnswers:usedAnswers} ,
type:"post",
success: function(response) {
console.log(response);
}
});
}
// inital display of question
displayQuestion();
Then when I want to access the array in the PHP script
<?php
echo print_r($_POST['usedAnswers']);
?>
I get the following problem on screen
Why is he adding an extra 1 ?
When I try to access the first element of the Array like this:
echo print_r($_POST['usedAnswers'][0]);
He console.logs me the number 11?
What am I doing wrong what is the correct way to send an Array via Ajax?
Is it also possible to send a set via Ajax?
so, based on your comments, it appears your question is really referring to how to send data through, rather than the odd output you're getting, which Jay has already answered for you.
as far as your code reads, what you're actually sending is this:
{[1, 2]:[1, 2]}
which is invalid JSON.
if you're trying to actually have a 'usedAnswers' key (which it looks like from your php), then you need to do this:
$.ajax({
url: "backend/retriveData.php",
data: {'usedAnswers':usedAnswers}, // <-- note the quotes around the key
type:"post",
success: function(response) {
console.log(response);
}
});
Because you are echoing the print_r() (which in and of itself is a type of echo) you're returning a value for the truthiness of the print_r(). Change the line to this
print_r($_POST['usedAnswers']);

Ajax loading image error

my question is very simple. I have drafted the code as follow for showing the loading image when the form is being posted. The loading image can be shown properly. However, it cannot hide automatically after the result is returned. May i know what is the error?
HTML
<div id="loading"></div>
Ajax
function email_subscribe(){
$('#loading').html('<img src="loading.gif"> loading...');
$.ajax({
type: 'post',
url: 'index.php?subscribe',
dataType: 'html',
data:$("#subscribe").serialize(),
success: function (html) {
$('#loading').html();
eval(html);
}});
}
You're just calling the .html() method without any parameters (which serves as a getter). To achieve what you're looking for here, you need to at least pass in like an empty string to set and overwrite existing content.
$('#loading').html('');
I also think you should not use eval....
...and yes call .html() with an argument like:
$('#loading').html(" ");
or
$('#loading').html(" ");

Update div after ajax database insert

so i have some comments pulled from a database and echoed into a div.
Im am entering new comments via a form and they are inserted into the database with ajax.
I want the comments in the div to update and show the new ones as soon as they are posted.
How can i refresh the div to show new content, without the page loading again?
javascript is like so:
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$comment.after('<div class="success">Update Added!</div>');
else
$comment.after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});
Thanks for any help.
I think you would like to use
http://api.jquery.com/prepend/ for making new comments on the top,
OR,
http://api.jquery.com/append for making new comments on the bottom.
right after using
$comment.after('<div class="success">Update Added!</div>');
Just append or prepend the valid structure that forms your comment box is okay for it.
just like for example:
$("#comment-holder").append("<div class='commentbox'><p class='commenthead'>" + response.newCommentHeadline + "</p><p class='commentcontent'>" + response.newCommentContent + "</p></div>");
Also worth looking into your response.databaseSuccess, you might want to compare it more strictly like using "==", because boolean not always work as you expect, since i am not sure if your responding document are in the correct format that it correctly interprets as a boolean.
you should extract your required data from response json and generate a Html for appending to your div with id of "comment" then as you apply your css it will get styled.
my suggestion is if you don't want to add extra info from your server to the comment, you only need a flag as success or fail and instead of sending data to server and retrieving it you can use your local data when successfully inserted to your database
if (check == true) {
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
$("#comment").after('<div><div class="from">'+response.from+'</div><div class="message">'+response.message+'</div></div>');
}
fail:function(){
$("#comment").after('<div class="error">Something went wrong!</div>');
}
});
}

JQuery Ajax POST throwing an empty error without making the request

I have a function that makes an Ajax request for any anchor. The request method can be GET or POST. In this case, I want to make a POST without using a form but the Ajax request throws an error before even sending the request. The error has the value "error" and all error/failure description variables are "".
function loadPage(url,elem_id,method,data) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: data,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
When the function is called the params are these (copied from the js console):
data: "partial=yes"
elem_id: "page"
method: "post"
url: "/projects/2/follow"
As asked, here is the code that calls the loadPage function.
$("body").on("click","a.ajax",function(event) {
var _elem = getDataElem($(this));
var _method = getRequestMethod($(this));
var _partial = getRequestPartial($(this));
handlers.do_request(event,$(this).attr("href"),_elem, _method, _partial);
});
var handlers = (function() {
var obj = {};
obj.do_request = function(event,url,elem_id,method,data) {
event.preventDefault();
loadPage(url,elem_id,method,data);
history.pushState({selector:elem_id,method:method,data:data},null,url);
};
}());
After the failure of the Ajax request, the request is made by default and it responds sucesss. In all I have read, this seems to be a valid way to make a POST request (that doesn't need a form).
Am I doing something wrong in the function? Why is the error information empty?
Thanks
EDIT:
I have been thinking, for a POST from a "form" that function works, when the variable "data" is made with the serialize function (e.g. "var data = $(this).serialize();"). Could it be that the format of the "data" when I make a POST without a "form" is wrong in someway? Maybe the JQuery Ajax function doesn't accept a simple string like "partial=yes" as data when a POST is made. Any thoughts on this?
I just experienced this problem and after an hour or two, thought to try setting cache to false. That fixed it for me.
$.ajax({
url: url,
cache: false,
type: method
});
Unfortunately, when I removed cache again, my request was working as if it had never had a problem. It seems as if setting cache:false made something 'click'.
Oh well.
Just a guess, but in the docs the type parameter is in all caps, i.e. 'POST' and not 'post'.
Try:
function loadPage(url,elem_id,method,dat) {
ajaxLoading(elem_id);
$.ajax({
type: method,
url: url,
data: dat,
success:function(data){
$("#"+elem_id).html(data);;
},
error:function(request,textStatus,error){
alert(error);
}
});
}
I'm wondering if you are running into a problem using a variable named after a keyword. If this doesn't work, try calling loadPage with no arguments and hard coding all of your ajax parameters, just to see if that works.
Could not solve the problem, neither could find the reason why it was happening. Although, I found a way around, by using a hidden empty form instead of an anchor with the method 'POST'. For a form, the function worked nicely.
Thanks for the answers

Trying to set variable as part of URL in jquery ajax post

So I am trying to do a post using jQuery.ajax instead of an html form. Here is my code:
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/$org_ID',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Here is my problem:
When this was in an html form, the $org_ID that was part of the URL would actually pull the variable and send it as part of the URL. Now that this is in jquery, its just sending $org_ID as text. How can I get this to figure out what the variable, $org_ID is? I tried declaring it in the javascript but I am brand new to jquery/javascript and don't really know what i'm doing.
Thanks!
Are you rendering this in PHP? In that case you need to do:
url: '/groups/dissolve/<?php print $org_ID; ?>'
Otherwise, you need to do something like
var org_id = 'foo';
// or
var org_id = '<?php print $org_id ?>';
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/'+org_ID,
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Unlike PHP, you can't interpolate variables in javascript, you have to concatenate them with the string.
If you're trying to POST a variable (org_id) then you should put it in data:
data['org_id'] = org_id;
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
While you can concatenate params onto your url to send them in an HTTP request, putting them in a data object not only lets jQuery do more work for you & escape HTML entities etc (and keep your code cleaner), but also allows you to easily debug and play around with ajax() settings.
It's not clear in the question where your data comes from, but you can use something like:
url: '/groups/dissolve/'+orgId,
or:
url: '/groups/dissolve/?orgId='+orgId,
Short answer, concatinate
url: '/groups/dissolve/' + $org_ID

Categories