automatically getting data as it is posted without refreshing with ajax - javascript

I am trying to create a conversation system with php jQuery and ajax.
I am using the following jQuery to handle the ajax post together with php.
function replyToStatus(sid,user,ta,postuser){
var data = $('#'+ta).val();
if(data.trim() == ""){
alert("Please type a reply before you submit.");
return false;
}else{
var dataString = 'action=status_reply&sid='+sid+'&user='+user+'&postuser='+postuser+'&data='+data;
$.ajax({
type: "POST",
url: location.href,
data: dataString,
cache: false,
success: function(response){
$('#'+ta).val("");
$( "#conrep_"+sid ).append( '<li><div class="comment-user-image-container"><div class="user-image" style="background:url(\'imagesrc.jpg\');"></div></div><div class="comment-content"><h5>admin '+data+'</h5><img class="scaledImageFitWidth img" src="userimagesrc.jpg"></div></li>');
}
});
}
}
This code appends and displays the post immediately to the current user(user1) making the post.However to all the other users viewing the same page whom have not refreshed the page after this user(user1) has posted ,this post won't appear until they have refreshed.
My question is how do I make a system that will automatically show this post to all users or how do I deal with this problem otherwise.
Thanks for the reply in advance:)

Related

Can't get unique data based on unique form click sent to php with AJAX

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.

Sending large string Ajax to PHP

I have been struggling with sending a large string to a PHP page via AJAX post method.The AJAX part seems to be working fine and sending the string without any problem,my problem is as soon as i redirect to my destination page the PHP $_POST seems to be empty.
I have made some research and i found out that this is a recurring problem but none of the solutions worked for me.
Ajax page
PHP destination page
AJAX code
$("#save").click(function(event){
var data = $("#mycontent").html();
$.ajax({
type: "POST",
url: "concat.php",
cache:false,
dataType:"html",
data: {
mycontent: data,
},
success: function(msg){
alert( "Data Saved: " + msg );
top.location.href = 'concat.php';
}
});
});
PHP page
session_start();
if(isset($_POST['mycontent'])){
$content = $_POST['mycontent'];
}
var_dump($_POST);
var_dump($_REQUEST);
The $_POST vairable is not perserved between page redirection. You will need some other mechanism to perserve posted data ie. using $_GET, session or database etc.

submit form without refresh page and load output into html [duplicate]

This question already has answers here:
Submit form without page reloading
(19 answers)
Closed 7 years ago.
I want to submit a form information to another php script without leaving the page and show the output in that same page.
Here's my ajax function to load php output in html without leaving the page. It doesn't do that if my form has a submit button. It only works with a normal clickable button.
$('#btnLoad').click(function(){
$.ajax({
type: 'POST',
url: 'page1.php',
success: function(data){
if(data != null) $('#content').text(data);
}
});
});
The problem is that I need to send POST variables to my PHP script but when I do, it goes to my PHP script page. I just want the script to receive the POST variables, run the script and then show the output in my HTML page.
Here's the script that doesn't go to PHP script page. I don't know if the PHP script runs with this function.
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('page1.php', $(this).serialize(), function (data) {
}).error(function() {
});
e.preventDefault();
});
});
How can I combine these two scripts into one, to submit my variables via POST, run the script and show the output in my HTML page?
Combining both Ajax
$("#btnLoad").click(function (e) {
e.preventDefault()
$.ajax({
type: "POST",
url: "page1.php",
data: $('#myForm').serialize(),
success: function (msg) {
$("#thanks").html(msg);
},
error: function (msg) {
$("#error").html(msg);
}
});
});
HTML to show success message
<div id="thanks"></div>
HTML to show error message
<div id="error"></div>
PHP Server Side
<?php
if (isset($_POST['submit'])) { //assuming you have input with name="submit"
//Do what ever you like to do next
//If everything good
echo "<strong>Success!</strong> This Is Success Thanks Message. If everything go exactly as Planned.";
} else {
echo "<strong>Error!</strong> This Is Error Message. If anything goes south.</div>";
}
?>
Edited: OP asked to show messages in jQuery modal dialog
In Ajax after success call, try like this
success: function(msg) {
$("#thanks").html(msg);
$("#modalId").dialog({
autoOpen:true,
width:500,
title:"Your Error Message",
},
And same for error function
Note: I haven't test this so not sure it will work out of the box or need any debugging.
Why do you not replace the submit buttons with normal buttons then?
What you could do in jQuery is:
$(formSelector).on('submit',function (e) {
e.preventDefault()
//Place your ajax here.
})
you can do something like
$('#btnLoad').click(function(){
$.ajax(url,
{
data: { variable1: $("#variable1").val(), variable2: $("#variable2").val() },
type: "POST",
success: function(data) {
if(data != null) $('#content').text(data);
}
});
});
And normally I don't use a form if I need to send data via ajax, I use just JS.

How to refresh a page or div with jquery in order to reveal new data

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.

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>');
}
});
}

Categories