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>');
}
});
}
Related
I am making a weather app as a school project. I have an input through which the user is supposed to enter a name of a city to get the weather from an API. If the user misspells the name of the city I get an error in the console. I'd like to catch this when it happens and display some message to inform the user to correct the input. I searched other questions on StackOverflow and jQuery site as well, but didn't get my answer so that's why I'm here.
My code looks like this:
$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/find?q=' + valueFromInput + '&units=metric&type=like&mode=json&APPID=cdb7ecf86aa724f19f723f964e5f15ae',
dataType: 'json',
success: function (weatherData) {...//code}
I tried putting the ajax inside a try/catch block and added error: function().. beneath success, it still doesn't display an error message.
Why isn't this working? Is this easier to do in plain javascript?
Add an if statement to your success function to check if the list has elements in it. Otherwise you will get an error trying to get the name of an element that doesn't exist.
success: function (weatherData) {
if (weatherData.list.length > 0)
document.getElementById("cityNameCountry_").appendChild(document.createTextNode((weatherData.list[0].name)));
}
From your comment it seems that you go and use this:
weatherData.list[0].name
your response as you mentioned is like this
"message":"like","cod":"200","count":0,"list":[]
You should check your response in order to see if you have any server errors.
My guess from what you have provided seems like you don't take into consideration neither the response code nor the number of items. You should change your ajax success handler to something like the following.
$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/find?q=' + valueFromInput + '&units=metric&type=like&mode=json&APPID=cdb7ecf86aa724f19f723f964e5f15ae',
dataType: 'json',
success: function (result) {
// Error handling
if (result.code != '200'){
alert('some kind of error');
return false;
}
// Checking the number of list items
if (result.list.length > 0){
document.getElementById("cityNameCountry_").appendChild(document.createTextNode((result.list[0].name)));
}
}
});
I am trying to setup a page that displays observations, and if one of the observations is clicked then it will send the observation number of the observation clicked to php. Then when they are redirected to a details screen it will populate the details of the observation clicked. I have tried many different ways to get this done, so my code is kind of all over the place, but It seems that no matter how I do it either the Ajax doesn't send the data or it sends the same observation number every time. To me it seems like the AJAX data attribute can't deal with i. This is being built in Intel XDK, which is a html5 app builder. That is why this is tricky because I can't use browser developer tools to debug.
Javascript
<script>
$(document).ready(function(){
$.ajax({
url: "http://localhost/observationMain.php",
data: { action: "observationID" },
type: 'post',
dataType: 'json',
success: function(observationID){
for(i = 0; i <= observationID.length; i++)
{
$("#observationMainListView").append("<form id='form"+i+"'' method='post'><a id='observation"+i+"' class='list-group-item allow-badge widget uib_w_"+(i+4)+"' data-uib='twitter%20bootstrap/list_item' data-ver='1'><h4 id='observationNum"+i+"' class='list-group-item-heading'>"+observationID[i][0]+"</h4><p class='list-group-item-text'>"+observationID[i][1]+"</p></a><input name='observationNum' value='"+observationID[i][0]+"'></form>");
$("#observation"+i+"").click(function(){
$.ajax({
url: "http://localhost/observationDetail.php",
data: $("#form"+i+"").serialize(),
type: 'post',
success: function(observationNum){
document.location.href = 'observationDetail.html';
}
});
});
}
}
});
});
</script>
php
<?php
session_start();
if(isset($_POST['observationNum'])){
$_SESSION['observationNum'] = $_POST['observationNum'];
}
?>
This might be crazy but check this line.The form's id property has an extra ' may be that's causing the issue.
$("#observationMainListView").append("<form id='form" + i + "'' method='post'
I cant run the script but just give it shot.
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
I've got some jquery that submits a form for me. It works just fine. The only major problem is how simple it is.
The form submits the info to the database using my php script without refreshing the page, but the page isn't updated in any way to show the new data. What are some good ways to update the page or div so my new data is displayed after submitting the form. Below is my code
$(function() {
$('#form').submit(function(e) {
var data = $(this).serialize();
// Stop the form actually posting
e.preventDefault();
// Send the request
$.ajax({
type: "POST",
url: "submit.php",
data: data,
cache: false,
success: function(html){
$('textarea#joke').val('');
}
});
});
});
You are very close, just use html() method or text() depend on your needs, for your example I think text is better, since you want put text into textarea
success: function(html){
$('textarea#joke').text(html);
}
but if you want put some html into custom div do
success: function(html){
$('#custom-div').html(html);
}
Suppose from the submit.php, you are returning some value as status = true if form submitted suceessfully else status = false
then in your ajax code, you can use it as
success: function(html){
if(html.status == true)
$('textarea#joke').html('Form submitted succcessfully');
else
$('textarea#joke').html('ERROR!');
}
OR
success: function(html){
$('textarea#joke').val(html.status);
}
This would update the div content of $('textarea#joke')
Hope this would help you.
Thanks.
Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.