I thought the easiest way would be to explain it with an image of what I have.
Summary -
I have a form to submit posts (pretty much like what you would find in twitter). Within each post there is an <ol> where comments to that post will reside.
Problem -
When I submit the first comment (button submit 2 in the picture), it doesn't call the ajax and just goes to a page where it presents me the php output of the comment. It seems it is not reloading or aplying DOM events to that portion of code. If I go back, the comment is presented (because it refreshs the page) and when adding the 2nd comment, everything goes normal, as expected. The problem is just the first comment.
Flow -
1) insert new post
2) click the textarea, put some text and press submit
3) Jumps to a page where php output for comment is presented
3a) no ajax call is done. It never enters the code
Could you please help me out understand what is going on? Thanks in advance.
In case you need more of the code just tell me.
JS (post_comment.js - associated with submit 2 in picture. I use ajaxForm - jquery form plugin - though I also tried with the standard .ajax call and the result is the same)
$(function () {
var options = {
success: function (html) {
var arrHTML = html.split(',');
var postId = $.trim(arrHTML[0]);
var html_code = arrHTML[1];
$('ol#post_comment_list' + postId).load(html_code);
//$('ol#post_comment_list'+postId 'li:first').slideDown('slow');
$('.footer-post').hide();
$('.comments-feed').delay(2000).slideUp({
duration: 1000,
queue: true
});
$('.small-textarea-main-feed').removeClass('set-large');
resetForm($('.footer-comment'));
},
error: function () {
alert('ERROR: unable to upload files');
},
complete: function () {
},
};
$(".footer-comment").ajaxForm(options);
function ShowRequest(formData, jqForm, options) {
var queryString = $.param(formData);
alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
return true;
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
});
Related
So currently I'm searching for 10 new posts and the Ajax searches in the same page from the page and I use $_GET['limits'] in my PHP query to scan the server for all requested data.
So what I'd like to do is if there is no new data to show the 'No More Posts' Div. I tried using t.length===0 with no luck, now I don't know if its because t isn't an array or whether I put it in the wrong place in my success.
var streams_stream_count=10;
function streams_stream_load(targetID){
$('#loadmorestreamoneajaxloadertarget').show();
$.ajax({
method: 'get',
url : 'stream2.php?limits='+streams_stream_count+'&targetID='+targetID,
dataType : 'text',
success: function (t) {
$('#streams_stream_container').fadeIn('slow').html(t);
$(document).scroll(function(){
if ($(window).scrollTop() + $(window).height() >= $(document).height()) {
streams_stream_count+=10;streams_stream_load(targetID);
}
});
},
complete: function(){
$('#loadmorestreamoneajaxloadertarget').hide();
}
});
}
And my hidden div to show if no new data.
<div id='nomoreposts' style='display:none;'>No more Posts</div>
UPDATE
I use $sqlLimit=mysqli_real_escape_string($mysqli,$_GET['limit'])
$call="SELECT * FROM streamdata ORDER BY streamitem_timestamp DESC LIMIT $sqlLimit";
You can also do like this :- Write code in backend (PHP function) and return html if no data found "No more Posts", also send one parameter true/false. On the bases of the parameter show html in your fronted.
(simplified) Scenario: a remote MySql DB and an HTML page with 2 buttons: SHOW and SELECT. The SHOW loads a single record and displays the fields in a form.
Everything is ok on this side.
The SELECT was made with a new approach for me:
I pass a parameter to a PHP function to query the DB and create an html file with the resuls.
This file is a series of <UL><LI><a id="1"...data..</LI></UL> to be inserted within a DIV.
One of the <LI> contains a link that, when clicked, calls the SHOW function. The record identification is made by mean of the ID associated to the anchor.
This procedure works fine; I get the new HTML segment (that I can check on the remote web server).
It is inserted (???) inside my DIV and the content is correctly displayed on screen, but... it does not exist.
Clicking on the links does not activate the SHOW procedure (actually, an Alert with the calling ID is never shown).
Looking to the html page source from Mozilla it still shows the previous content, without the new added (or replaced) code.
This is the reason for this post's title: I see something that really is not there.
Possibly, I should have AJAX to 'refresh' its visibility of the DOM, but and do not understand how.
This is the piece of JQuery script that I use to get the new content:
$("#select").click(function() {
$.ajax({
url: "new_record_list.php",
cache: false,
success:
function(recNumber)
{
$("#selected").val(recNumber); //ok
$("#recordList").load("list.txt"); //'list.txt is created by new_record_list.php
alert($("#recordList").html()); //this is OK
}
});
});
Everything is ok, but where is the meat?
Most likely the listener you created did not attach to the new dom nodes.
You can fix this by attaching a listener to a parent element that exists at page creation or even the document like so:
$(document).on('click', '.show', function() {
//click event
});
Replace ".show" with the jquery selector for the links
Since I'm unable to comment on your new post due to rep:
Remove the click event handler inside the loadRecord function.
The click event was already bound at the top of your script. What happens is that you click, activate the load record function which binds a new click handler, triggering the action on all the clicks following it.
The load record should look like this instead:
function loadRecord(){
ind = $(this).attr("id");
$("#thisRecord").val(ind); //shows the clicked record
$.get("show_record.php",{id:ind}, function(gotString)
{
ptr=0; //used to fetch fields
pos=0;
lun = gotString.length;
if (lun==0) {
alert ("Empty string!");
return false;
};
// fetch received keys and values then fills the fields
while (ptr < lun) {
..... //not interesting here
}; //while
});
return false; //required!
};
Also, you should replace
$(document).on('click', '.compLink', function() {
loadRecord();
});
with
$(document).on('click', '.compLink', loadRecord);
And loadRecord will be passed the mouse event as an argument. $(this) will also refer to the link you clicked inside the loadrecord function.
Otherwise you need to pass the element clicked into that function.
One issue I can see straight away is the AJAX call, it should be along the lines of:
$( "#select" ).on( "click", function ()
{
$.ajax( {
url: "new_record_list.php?record=MY_RECORD_VALUE",
type: "GET",
success: function ( response )
{
$( "#selected" ).val( response );
$( "#recordList" ).html( function ()
{
$.ajax( {
url: "list.txt",
typ: "GET",
success: function ( response2 )
{
$( "#recordList" ).html( response2 );
}
} );
} );
alert( $( "#recordList" ).val() );
},
beforeSend: function()
{
$( "#recordlist" ).html( "Loading..." );
$( "#selected" ).val( "Loading..." );
}
} );
} );
This will give a better result from the $.ajax call that you have made.
The .load() method can be quite unreliable at times, hence why it is (IMO) better to make an ajax within an ajax, because that's what your doing with less control effectively.
Where you have done the function(recNumber) is kinda wrong I'm afraid, whats brought back from the AJAX call is the response, everything that would be shown should you be using it as an actual page, e.g. if you had:
<table>
<tr>
<td>Row 1</td>
</tr>
<tr>
<td>Row 2</td>
</tr>
</table>
<input id="id_valued" value="2" />
Then this whole thing would be returned, not just the id_valued input field.
I followed the hints from Erin plus some other suggestion found on this forum and now the program ALMOST works.
Actually it does, but when a new set of records is loaded, to update the display (that is to call the loadRecord function) it is necessary to click twice on a link, the very first time only. All next clicks reacts immediately.
I try to post the entire script, for you experts to see what I hardly did:
<script type="text/javascript">
$(document).ready(function()
{
$(document).foundation();
var $scrollbar = $("#scrollbar1"); //other stuff
$scrollbar.tinyscrollbar();
//Erin suggestion + my understanding
$(document).on('click', '.compLink', function() {
loadRecord();
});
/* =========== ADD Rows ============================== */
/* action called by hitting the "selectRow" button.
/* query the DB and get a list of rows (5 fields each)
/* that are then inserted into the '#recordList' DIV.
/* Each rows has format:
/* <UL><LI><A id="xxx" class="compLink" ...>item xxx</A></LI><LI>....</LI></UL>
*/
$("#selectRow").on( "click",function()
{
$.ajax(
{
url: "new_record_list.php",
type: "GET",
success: function(recNumber) //if ok, we get the number of records
{
$("#selectedRecords").val(recNumber); //show how many records we got
$("#recordList").load("newRecords.txt"); //loads the remote text file into the DIV
}
});
});
/* ====================================================== */
/* =========== LOAD Record ============================== */
/* loads and displays an entire record from DB,
/* based on the ID of clicked link with class="compLink"
/* in '#recordList' DIV.
/* Example: <a id="1" class="compLink" ...>
*/
function loadRecord(){
$(".compLink").click(function(event)
{
ind = $(this).attr("id");
$("#thisRecord").val(ind); //shows the clicked record
$.get("show_record.php",{id:ind}, function(gotString)
{
ptr=0; //used to fetch fields
pos=0;
lun = gotString.length;
if (lun==0) {
alert ("Empty string!");
return false;
};
// fetch received keys and values then fills the fields
while (ptr < lun) {
..... //not interesting here
}; //while
});
return false; //required!
});
};
/* ====================================================== */
return false;
});
</script>
I hope this is clear enough. Thanks
I am newbie to AngularJs. I am using AngularJS as front end and Laravel As backend.
I have a situation where I want page to be refreshed on ajax success (when user post data).
I have template index.blade.php like this :
#extends(layout)
#section
header page
post page
main page
footer page
#endsection
Now thing is that User is posting update from post page and
on that success i want data to be refreshed which is on main page
function addpost ($scope, $http){
$scope.loadData = function(){
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http.post( baseurl+"alldata").success(function(data)
{
$scope.posts = data;
});
}
$scope.addComment = function(post){
if("undefined" != post.hoot){
// Angular AJAX call
$http({
method : "POST",
url :baseurl+ "url",
data : "post="+post
}).success(function(data){
$scope.posts = data;//json response
// here i want page to be refreshed or div refresh of sub-main page
});`
$scope.post = ' ';`
}
}
$scope.loadData();
}`
Now thing is that if i am posting data from other sub page and then showing it on other sub page. Iam calling addcomment to add posted data in model and then loaddata() to get all data from model for ng-repeat in a view.
if i am going to fire watch event . it will keep on refreshing model thus view data. Suppose i am working on comment section where we can like , dislike and comment on post. and i want to use ng-click event inside ng-repeat(which is refreshing view).
Test.controller('Testing',['$scope', '$http', function($scope,$http){
$scope.products = {};
$http.post( baseurl+"ajax/getall").success(function(data)
{
$scope.products = data;
});
$scope.$watch("products", function(newValue, oldValue) {
if (newValue === oldValue) { return; } // AKA first run
$scope.products= newValue;
});
});
$scope.Hello= function(){
alert("hello");
}
}]);
It will keep on refreshing page and thus don't click event inside ng-repeat which is ng-click.
I have fired ng-click="Hello()" event but it doesn't fire.
You can register a listener to $scope.data in any part of the application that had a reference to scope. This way, everything will keep up to date when data is updated.
Like so:
$scope.$watch('data', callback)
You are thinking the jQuery way. You have to put that away and think data-binding and angularjs.
To do what you are asking is pretty easy if you think the angularjs way.
First of all, you need the php page of yours to print out a html page with a {{updateMe}}
then in your code
.success(function(data){
$scope.updateMe = data
......
I have been trying to figure this out for hours to no avail.
I have the following
http://vitalets.github.com/x-editable/docs.html#newrecord
the new record module/code. Its functionality is, once all the rows have their data, and it is submitted, it retains its value so that it can stay editable.
I have tried adding input, select clearing code in the success of the ajax request and tried putting the .editable function inside an ajaxComplete function to see if it would reload the element on submit but it didnt. look at the demo. enter data, and submit. it then makes the data "permanent" so that it can continue to be editable.
I have removed the code that hides the button.
What i want it to do is, submit the record and reset so i can submit another with the form being 'Empty' and back to default.
I am developing an equipment tracker and would love if techs could just enter records, one after another. im sure its a simple fix to reset the form, i just cannot figure it out.
I have attached a screencast video of it.
http://www.youtube.com/watch?v=dPDuQCgOOSw
as it's popular question, I've added Reset button to documentation.
$('#reset-btn').click(function() {
$('.myeditable').editable('setValue', null) //clear values
.editable('option', 'pk', null) //clear pk
.removeClass('editable-unsaved'); //remove bold css
$('#save-btn').show();
$('#msg').hide();
});
It's better to use .editable('setValue', null) instead of .text('Empty') as we need also to reset internal value.
HTH
If you look how the "save new user button" is implemented, it just selects the anchor tags that have classname myeditable
Either you bind a function to your 'reset' button or have this script onclick
IF onclick:
jQuery.each($('.myeditable'),function() {
$(this).text('Empty') ; //this is your default text
});
OR as a function
function reset_myeditable()
{
jQuery.each($('.myeditable'),function() {
$(this).text('Empty') ; //this is your default text
});
}
and attach this to the onclick handler of your reset button
This I assume you will be putting a 'reset' button
EDIT
Ok zoom in to your $('#save-btn').click(function() success handler
success: function(data, config) {
if(data && data.id) { //record created, response like {"id": 2}
$(this).editable('option', 'pk', data.id);
//remove unsaved class
$(this).removeClass('editable-unsaved');
//show messages
var msg = 'New user created! Now editables submit individually.';
$('#msg').addClass('alert-success').removeClass('alert-error').html(msg).show();
$('#save-btn').hide();
$(this).off('save.newuser');
/**this the edited part**/
jQuery.each($('.myeditable'),function() {
$(this).text('Empty') ; //this is your default text
});
/**end of edit**/
} else if(data && data.errors){
//server-side validation error, response like {"errors": {"username": "username already exist"} }
config.error.call(this, data.errors);
}
},
Basically, I've got a form that submits a post to my wordpress blog depending what's in the form. When submitted, it hides the form from the page using ajax (as below). This works only when I have 1 form on the page.
What I am trying to do is make multiple forms work the same way on a page... Each one hides only itself when it's submitted.
contact_form is the DIV ID of the singular form that works
I added <div id="form'.$formnumber.'"> to the html page, so now there are multiple forms with IDs of form1, form2, form3, etc. form_no is the number on the end that gets sent to this script.
I don't know ajax/javascript very well - How do I make it work on multiple divs? Here's what I have at the moment (I've simplified as much as possible). Thanks!
$(".button").click(function() {
var form_no = $("input#form_no").val();
}
...further down the page...
$.ajax({
type: "GET",
url: "mypage.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("")
.append("")
.hide()
.fadeIn(1500, function() {
});
}
});
return false;
This does the job:
$(".button").click(function() {
var form_no = $("input#form_no").val();
$('#form' + form_no).hide();
});