The idea is: i have a main DIV with content mini divs of cars info divided two per row, that i'm getting with a query from DB, i want when pressing that button to make reload of that main content with new content from the DB, is that possible to do ? please advise.
code looks like this:
<div class="SearchBlocks">
<div class="row">
<div class="car_section">INFO</div>
<div class="car_section">INFO</div>
<div class="car_section">INFO</div>
<div class="car_section">INFO</div>
......
</div>
<h2 class="load_more"><a id="more_link" href="#">Load more <i class="icon-custom_arrow"></i></a></h2>
</div>
function reload(url){
$.get(url, function(data){ // $.get will get the content of the page defined in url and will return it in **data** variable
$('#row').append(data);
}
}
$('#more_link').click(function(e){
e.preventDefault();
var url = 'http://example.com/somepage.html';
reload(url); // this calls the reload function
});
You haven't shown the exact code you're using to generate your AJAX request, however the general pattern will be something like this, where the update logic is extracted in to it's own function which is called both on load of the page, and click of the #reload_cars button.
function getData() {
$.ajax({
url: 'yoururl.foo',
success: function(data) {
$('#row .car_section').remove();
$('#row').append(data);
}
});
}
$('#reload_cars').on('click', getData);
getData();
just use
function refreshDiv(){
var container = document.getElementById("divId");
var content = container.innerHTML;
container.innerHTML= content;
}
Related
I am writing an AJAX function in ASP.Net MVC5 and I am getting a problem that the form AJAX request goes only one time. It is a search page. After I choose the filter I press search I get the correct result. However if I changed the filter and click the search submit again, nothing will happen.
var ajaxFormSubmit = function() {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var target = $($form.attr("data-enbw-target"));
target.replaceWith(data);
debugger;
});
return false;
};
$("form[data-enbw-ajax='true']").submit(ajaxFormSubmit);
<form method="get" id="documentForm" action="#Url.Action("Index", "DocumentSearch")" def data-enbw-ajax="true" data-enbw-target="#documentSearchResult">
<button type="submit" id="submitbtn" name="submitbtn" tabindex="100" class="k-button">
<img src="~/Content/search_small_icon.png" />
#WebResources.DocumentSearchButton
</button>
</form>
#Html.Partial("Results", #Model)
public ActionResult Index(DocumentSearchInput model)
{
if (Request.IsAjaxRequest())
{
return PartialView("Results", result);
}
return View(result);
}
I do not get any error. and when I get a debugger; in javascript. the new data is correct. can you please help me.
You are replacing the form in your ajax success. As such, the new form will not have the submit binding on it. If you truely want to do this you will have to rebind to the new form, or possibly use a delegate instead.
$('parentSelector').on('event', 'childSelector', function(){});
parentSelector - A parent element of the child that pre-exists the child element and should typically not be removed/created during the page lifespan.
childSelector - A selector for the element that will be created/changed/removed at some point in the lifespan of the page.
I found the answer.
the problem wasn't with the submit. the problem was with re-writing the data.
$.ajax(options).done(function (data) {
$("#documentSearchResult").empty();
$("#documentSearchResult").html(data);
});
simply, I empty the div then write inside.
The title of this question might be unclear, but thats why I'm trying to explain it right here. I've got a contenteditable div which acts like a textarea for the articles of my blog (adminpanel). Getting the db data to display properly in the contenteditable div is no problem. But when I save the updated article version to my database, it aint saving the div styles ( as example) which are in the contenteditable div.
Example:
<div id="article_content" class="edit_article_content_container_inner" contenteditable="true"><?php echo $db_content ?></div>
outputs:
<div id="article_content" class="edit_article_content_container_inner" contenteditable="true">
<div>Dear visitor,</div>
<div><br /></div>
<div>Thank you for visiting</div>
</div>
When I make changes and decide to save the new version, the db_content column gets updated and looks like:
Dear visitor,Thank you for visiting this page
So the contenteditable div destroys my div styles when saving the new updated article. Is there a way to still store these div styles?
Thank you.
This is the part where I make the ajax call
$("#btn-save-new-article").on('click', function (event) {
var article_id = $('.edit_article_title_container').attr('data-article-id');
var article_title = $("#article_title").text();
var article_content = $("#article_content").text();
event.preventDefault();
$.ajax({
type: "POST",
url: "/includes/db-requests/admin/db-save-edited-article.php",
data: {article_id: article_id, article_title: article_title, article_content: article_content},
success: function(data,textStatus,jqXHR){ finish_editing_article(data,textStatus,jqXHR); }
});
});
function finish_editing_article(data,textStatus,jqXHR) {
//alert (data);
if (data == "article_edited_success") {
//location.reload();
alert(data);
} else {
alert(data);
}
}
As you can see, I'm storing the article_id, article_title and article_content.
Receiving the data to actual store it:
//DIV SUBMITTED DATA
$article_id = safe($mysqli,$_POST['article_id']);
$article_title = safe($mysqli,$_POST['article_title']);
$article_content = $_POST['article_content'];
.text() returns just the text content of an element. .html() returns the content with the HTML intact.
var article_content = $("#article_content").html();
I am trying to make load more button. My goal is to call ajax and put the response inside div and textarea.how to place the response inside div and textarea? Currently the response only shows in messagebox but i want to append the result into div.
*Note:*Response is html hyperlinks produced by process.php and i want those hyperlinks placed inside the div
<html>
<head>
<script>
//initialize page number to 1 default
var pagenumber=1;
//pass pagenumber to function to fetch correct page records
function getResult(pagenumber){
alert('me here'+pagenumber);
$.ajax(
{
type: 'GET',
url: './process.php?ID=1234&type=1&moviePath=1234/1212/Love&title=Love&page='+pagenumber,
data: $("#myform").serialize(),
data: {
},
success: function (good)
{
//handle success
alert(good)
},
failure: function (bad)
{
//handle any errors
alert(bad)
}
});
//after every call increment page number value
pagenumber++;
}// end of getResult Function
function addMoreItems()
{
pagenumber++;
getResult(pagenumber);
}
</script>
</head>
<body>
<div id="myDiv"></div>
<div class="MoreButtonSection">
<div class="RedButton">
<span class="LeftEnd"></span>
<span class="Centre">see more</span>
<span class="RightEnd"></span>
</div>
</div>
<br>
<br>
<form id="myform" name="myform" action="./2.php?Id=&title=" method="post">
<td>
<textarea rows="7" cols="15" name="outputtext" style="width: 99%;"></textarea>
</td>
</form>
</html>
You say your result is only showing in the message box, instead of alerting it, simply append. Assuming the below div is what you want to append to:
<div id="myDiv"></div>
You can modify your success function:
success: function (good)
{
//handle success
$("#myDiv").append(good);
},
Also, get rid of that second data: {}, -- it's doing nothing.
There are a number of issues.
There is no indication that you've included jQuery.
You've declared data: twice.
As Dmitry pointed out, you should probably be posting this.
And finally, where are you actually calling getResult()? It doesn't look like it's being called.
In addition, it is worth noting that from jQuery 1.8 and higher, .success() and .failure() are now deprecated and have been replaced with .done() and .fail().
http://api.jquery.com/jQuery.ajax/
I tend to use jQuery in these situations to make life a little easier, and work with the $('#yourDiv').append() function. For instance you can create variables i.e. var mug; and once it is filled with your data append mug to the document through $('#yourDiv').append("<p>"+mug+"</p>);
An example - Ajax Twitter API call that returns tweets to specific lists within a div (page source)
Hope that helps!
I think I get what you are trying to do but that code is a mess. As #David L has stated, you need jQuery. But then you do not need all the code you have written. It can be done in a few simple lines. Please replace the actual element selectors with your correct ones.
function addMoreItems() {
pagenumber++;
// get form values
var params = $('#myform').serializeArray();
// add predefined values
params.push({name: 'ID', value: '1234'});
params.push({name: 'type', value: '1'});
params.push({name: 'moviePath', value: '1234/1212/Love'});
params.push({name: 'title', value: 'Love'});
params.push({name: 'page', value: pagenumber});
// do request and insert response from server in div with id='divresults'
$.get('process.php', params, function(data) {
$('#divResults').append(data);
});
}
I have the following html code:
<div>
<form id="ChartsForm">
<div id="optionsheader">
<p>Choose your page:</p>
<div id="dateoptions">
<p>Until date: <input type="date" name="until_date" value="Until date"></p>
<p>Since date: <input type="date" name="since_date" value="Since date"></p>
</div>
</div>
<select name="accmenu" id="accmenu" style="width:300px; float:left; clear:both;">
<?php
$user_accounts = $facebook->api('/me/accounts','GET');
foreach($user_accounts['data'] as $account) {
?>
<option data-description="<?php echo $account['category'] ?>" data-image="https://graph.facebook.com/<?php echo $account['id']; ?>/picture" value="<?php echo $account['id'] ?>"><?php echo $account['name'] ?></options>
<?php
}
?>
</select>
<div class="insightsoptions">
<p>Choose your insights:</p>
<input id="newLikes" class="insightsbuttons" type="submit" name="submit" value="Daily new likes">
<input id="unlikes" class="insightsbuttons" type="submit" name="submit" value="Daily unlikes">
</div>
<div class="insightsgraphs">
<div id="dailyNewLikes"></div>
<div id="dailyUnlikes"></div>
</div>
</form>
</div>
which has a form with the id=ChartForm that contain two date inputs until_date and since_date, one select accmenu and two submit inputs with the values Daily new likes and Daily unlikes. I use the following Jquery function:
$(function () {
$('#accmenu').change(function() {
$(".insightsgraphs div").hide();
$(".insightsoptions input").attr("class","insightsbuttons");
});
$("#newLikes").one('click', function () {
$.ajax({type:'GET', url: 'newLikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
var json = response.replace(/"/g,'');
json = "[" + json + "]";
json = json.replace(/'/g,'"');
var myData = JSON.parse(json);
var myChart = new JSChart('dailyNewLikes', 'line');
myChart.setDataArray(myData);
myChart.setSize(960, 320);
myChart.setAxisNameX('');
myChart.setAxisValuesColorX('#FFFFFF');
myChart.setAxisNameY('');
myChart.setTitle('Daily New Likes');
myChart.draw();
}});
return false;
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
});
$("#unlikes").one('click', function () {
$.ajax({type:'GET', url: 'unlikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
alert(response);
$("#dailyUnlikes").html(response);
}});
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
});
});
for the application flow in the following manner: every time I click on one of the input submit buttons the script will make only one Ajax GET request to a specific php file that send me back a response with which I create a Chart in a hidden div with the id=dailyNewLikes or id=dailyUnlikes by case (for testing purposes I work for the moment only on the first button). The button it will change his background color into green and the div it will be shown. I use $("#newLikes").on('click', function(){ for change back and forth the background color and the display time of the div. (from green and display:block to red and display:none, you get the point I hope :D). Also I use $('#accmenu').change(function() { to change all buttons to red and hide the respective div in case an option from the select is changed. My problem is that after I refresh the page (Ctrl+R) choose since and until date, click on the first button (it change to green and the div is shown, also the toggle is working fine) and then click on the second button which works fine on the first click (is becoming green and div is shown) but on the second click I have an issue: the script is making another Ajax GET request (a wrong URL one) and the page is refreshed. Ex. of a good reguest URL:
http://localhost/smd/unlikes.php?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701
and an ex. of a wrong request URL:
http://localhost/smd/?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701&submit=Daily+unlikes#_=_
Like it can be seen (it doesn't need in the first to make this extra request) the php file is not present and also a new submit parameters is added. This also happen if I change from the select with another option. What am I do wrong? I really need to know, not just to have my code "fixed". It bugging me for a little while. Any feedback is more than welcomed. P.S. Also, how can I start the .one function only if both date inputs has been choosen? Something like how could help me?
var until = $('#dateoptions input[name="until_date"]').val();
var since = $('#dateoptions input[name="since_date"]').val();
if (until == "" || since == "") {
alert('Until date or Since date missing!');
return;
}
it will work that way? Sorry for the long question...
i think you should make your question a little shorter and just point what you need and what errors are you getting ..anyways...going through your code i see you have two click event for same button at the end for $("#unlikes").one and $("#unlikes").on(..and no return false in other function.
try adding return false
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
my guess is that , since you have two click event..when it gets clicked ..these event will fire and since you are missing return false in second click function...the form gets submitted hence refreshing the form.
however its better if put your codes in single click function than creating two seperate click event.
I was wondering how do I cache results from the .load function in javascript, I'm loading a html file like the one below, what I want to be able to do is load the cache by Parent-ID then when each child-ID is called it doesn't have to reload the html file everytime.
<div id="provider1">
<div id="thumb1">
content1
</div>
<div id="thumb2">
content2
</div>
<div id="thumb3">
content3
</div>
</div>
And the javascript I've been using:
var titleID = $(this).attr('id');
$('#content').prepend('<div id="loading">load</div>')
.load('test.html #'+ titleID')
Thanks a lot
$.ajaxSetup ({
cache: true
});
var titleID = $(this).attr('id');
$('#content').prepend('<div id="loading">load</div>')
.load('test.html #'+ titleID')
Rewrite load logic like this:
if (stuff in localStorage) {
// take it from there
} else {
// load
// on complete, put stuff in localStorage
}
Check http://diveintohtml5.ep.io/storage.html. There is also jQuery.data(), you can do some simple caching with it too.