How to call ajax and output its result inside div and textarea? - javascript

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

Related

Django: can't trigger AJAX call and send values back to my form

I need to run an AJAX call to perform a quick calculation in my django view and return the result in my html page, inside a tag.
I'm very new to Javascript so I don't understand why my AJAX call hasn't been triggered. This is my html and JS code:
<input type="text" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" onclick="calculate()">Estimation</button>
<span>{{estimation}}</span>
<script type="text/javascript">
function calculate () {
$.ajax({
url: '/myApp/templates/homepage/',
type: 'POST',
data: {
SHm2: $('#SHm2').val(),
STm2: $('#STm2').val()
},
success: function(estimation) {
alert(estimation);
document.getElementById("estimation").innerHTML = estimation;
}
});
}
</script>
And this is my views.py:
def homepage(request):
if request.method == 'POST' and request.is_ajax and 'estimation' in request.POST:
SHm2 = request.POST.get('SHm2')
STm2 = request.POST.get('STm2')
estimation = float(SHm2) + float(STm2)
estimation = json.dumps(estimation)
return HttpResponse(estimation, content_type='application/json')
The problem is that the AJAX code isn't triggered since I don't receive the alert. Nevertheless, the code in my django view is running anyway (which is strange, since I specified to run if 'request.is_ajax', which doesn't seem to be recognized on the other hand). It loads a new page where it correctly displays the result. But it's not what I want since I need the result to be in my form within the span tag where {{estimation}} is my variable.
Could you please tell me what I'm doing wrong? Thanks!
UPDATE:
Thanks to your answers, it's getting better. I've replaced in views.py 'request.is_ajax' by 'request.is_ajax()'. I've added the 'id' attribute to my input boxes. This helped me to trigger the AJAX call and not to load stuff in a new page. There is one last thing though. I'm still not able to display in my span tag the value of the estimation variable. I realised that it had no 'id' attribute so I did the following change:
<span id="estimation2">{{estimation}}</span>
Also in my JS code, I replaced in the success part the last line to:
document.getElementById("estimation2").innerHTML = estimation;
Basically I replaced "estimation" by "estimation2".
Unfortunately the span tag is not updated. Any idea what I am missing?
Change name to id. because #means id of the field. Like from name="SHm2" to id="SHm2"
<input type="text" id="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" onclick="calculate()">Estimation</button>
<span>{{estimation}}</span>
<script type="text/javascript">
function calculate () {
$.ajax({
url: '/myApp/templates/homepage/',
type: 'POST',
data: {
SHm2: $('#SHm2').val(),
STm2: $('#STm2').val()
},
success: function(estimation) {
alert(estimation);
document.getElementById("estimation").innerHTML = estimation;
}
});
}
</script>
1st
request.is_ajax is a function
2nd
'estimation' in request.POST
You have it in your statement but you did not pass it to view. Add it to data or remove from statement
It seemed that the issue came from the fact that I didn't declare the type of my button in my html code. The default value (i.e. "submit") prevented it from triggering my AJAX code as needed. So in the end I had to set it to 'type="button"' to make it work.

prevent page reload when calling php with ajax

I have a php function that I call using ajax and then handle the response with ajax. However, I want to prevent the page from reloading.
I have index.php containing a call to function1(), and it includes ajaxcall.js and jquery
Then my functions.php:
function function1(){
echo '
<form id="myform" action="" method="post" enctype="multipart/form-data">
<input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this)" placeholder="type an anime name" title="Type in a name">
</form>
<div id="table_recentanime" class="hscroll">
<table dir="ltr" id="myTable">';
// echo some table rows
}
if (isset($_POST['callyoukai_search'])) {
//echo "!!!" . $_POST['callyoukai_search'] . "the post value in php!!!!!!";
//echo
youkai_search($_POST['callyoukai_search']);
}
function youkai_search ($search_word){
// use $search_word to do a database query
return $result;
}
my ajaxcall.js
function searchfiltersajax(search_word){
if(event.key === 'Enter') {
console.log("yes");
console.log(search_word.value);
document.getElementById("myform").addEventListener("Keypress", function(event){
event.preventDefault()
});
jQuery.ajax({
url: '../wp-content/plugins/youkai_plugin/youkai_plugin.php',
type: 'post',
data: { "callyoukai_search": "1"},
success: function(response) { var container = document.getElementById("myTable");
container.innerHTML = response;
console.log('php gave javascript '); console.log(response); console.log('php gave javascript '); }
});
console.log ("done");
}
}
My ajax call works fine. It calls the php function with the desired search_word, and the search results replaces the div content just like I want. However, right after this, the page reloads.
How do I prevent the reload? I tried preventDefault(), but the way I used it didn't work.
Thanks in advance
Inlining event handlers is a bad practice. But if you need it at least add the event keyword. Change from:
to:
<input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this, event)"
Moreover, don't add the same event handler (i.e.: Keypress) inside another: in this way you are adding more and more times the same event handler. Instead, use the event parameter.
I'd suggest to use the addEventListener() or .on():
$('#myInput').on('keydown', function(e) {
searchfiltersajax(this, e);
});
The snippet:
function searchfiltersajax(search_word, e) {
if (event.key === 'Enter') {
e.preventDefault();
console.log("yes");
console.log(search_word.value);
jQuery.ajax({
url: '../wp-content/plugins/youkai_plugin/youkai_plugin.php',
type: 'post',
data: {"callyoukai_search": "1"},
success: function (response) {
var container = document.getElementById("myTable");
container.innerHTML = response;
console.log('php gave javascript ');
console.log(response);
console.log('php gave javascript ');
}
});
console.log("done");
}
}
<form id="myform" action="google.com" method="post" enctype="multipart/form-data">
<input type="text" name="callyoukai_search" id="myInput" onkeydown="searchfiltersajax(this, event)"
placeholder="type an anime name" title="Type in a name">
</form>
<div id="table_recentanime" class="hscroll">
<table dir="ltr" id="myTable">
<tbody>
</tbody>
</table>
</div>
The function searchfiltersajax takes one parameter named search_word. The first if-statement then checks an event-variable. This variable is declared nowhere in your code, so the code inside the if-statement will never get executed.
To verify this I would recommend to add debugger; as first statement inside the searchfiltersajax function. Then open the debugging console in the browser and reload the page. Do not forget to remove the debugger; statement once you are finished. If you know how to set breakpoints in the javascript debugger, you should not use debugger; statements at all.
As far as I understand you try to prevent a form to be submitted to the server but send an ajax call instead. There are several answers on StackOverflow for this topic, e.g. Prevent users from submitting a form by hitting Enter . You could use a code like this to achieve your goals (taken from the link):
$(document).on("keypress", "form", function(event) {
return event.keyCode != 13;
});
Last but not least, I would suggest not to include raw HTML sent by any server (even your own) to your page:
container.innerHTML = response;
Instead try to send a JSON object containing the information you wish to present and transform this object into HTML elements via JavaScript. This way you have a cleaner interface for data exchange and have to change on piece of code to change styling or other presentation aspects.

jquery ajax request wrapped in jQuery()'s .text() isn't the same as the div's .text()?

I know this is a very concrete issue but I've struggled with this code for the last 2 hours and I can't find anything on the topic or figure out how to solve it.
I have an issue with a jQuery Ajax Post request. I am trying to make a section on my page where I display the users current level. When a user interacts and does something that increases the level on the site the level should also increase in the DOM/client's browser. Therefore I've added a setinterval that allows the request to run every 5th second. And if the $(response).text() is different from the current div's .text() where i am rendering the current level I want to append this new response from the ajax request.
Maybe the answer is more obvious than I think.... I have added the code below
Ajax page:
$(document).ready(function () {
function getLevel() {
var getLvlData = $.ajax({
url: "AjaxRequests.php",
type: "POST",
data: {type: "4", lvl_r_type: 1}
});
getLvlData.done(function (response, textStatus, jqXHR) {
var innerLevelHTML = $("#LevelContainer");
if (($(response).text()) != ($(innerLevelHTML).text())) {
innerLevelHTML.html("");
innerLevelHTML.append(response);
}
if ($(response).text() == $(innerLevelHTML).text()) {
alert("the same");
}
});
}
var levelChecker = setInterval(function () {
getLevel();
}, 1000);
getLevel();
});
AjaxRequests.php:
if ($_POST["type"] == "4" && isset($_POST["lvl_r_type"])) {
$returnVal = htmlentities($_POST["lvl_r_type"]);
if (!empty($returnVal)) {
if ($returnVal == 1) {
?>
<div id="chartWrapper">
<div>
<canvas id="doughnut-chart"></canvas>
</div>
<div id="chart-center">
<div>
<div><h1>0%</h1></div>
<div><p>GX 0 / 1</p></div>
</div>
<div><p>LVL 0</p></div>
</div>
</div>
<div id="progressList">
<div><p>View tasks</p></div>
</div>
<?php
}
}
}
?>
html page
<div id="LevelContainer"></div>
Try using trim since a white space could be treated as a part of the text.
if (($(response).text().trim()) != ($(innerLevelHTML).text().trim())) {
...
One alternative approach I can think of, off of my head is, to set a hash inside a data attribute say data-hash="" whenever you set the html of that div, and then whenever you have a new ajax response you can generate a hash on the fly and compare that to the existing one and if a change is found just update the html and the hash value for that attribute.
This process minimises the confusion that may be caused due to dom being updated by some script.
Also, Instead of
innerLevelHTML.html("");
innerLevelHTML.append(response);
Why not just just set the html directly as
innerLevelHTML.html(response);

jquery form plugin and show content of div

I use jquery form plugin and i try show the result when i submit my form in one div but no get result
<script>
jQuery(document).ready(function()
{
jQuery('#base64').ajaxForm(
{
dataType:'json',
success:edit64,
target: '#htmloutput'
});
});
function edit64(datasend64)
{
if (datasend64.edit_result64=="ok")
{
jQuery('#htmloutput').fadeIn('slow');
}
}
</script>
I donñt know if i put all well or no , i try mant times and no get the result of form inside div , only show nothing
<div id="htmloutput" style="display:none;"></div>
<form action="admin_db_edit.php" name="base64" id="base64" method="post">
<input type="text" name="value_base64" value="" class="db_edit_fields" />
<input type="hidden" name="send64" value="ok" />
<input type="submit" name="send" value="send" class="db_edit_submit" />
</form>
Thank´s for the help , regards
First... you have no url specified for the form. second, try adding a function to handle the error case. This can help you understand if the issue is happening on the client or the server.
jQuery(document).ready(function() {
jQuery('#base64').ajaxForm({
url: ????
dataType: 'json',
success: edit64,
error: onError,
target: '#htmloutput'
});
});
function edit64(datasend64) {
if (datasend64.edit_result64 == "ok") {
jQuery('#htmloutput').fadeIn('slow');
}
}
function onError(response, error, reqObj){
alert(response);
}
if you are trying to send the data somewhere, you are probably missing the url attribute(as shown in the offical docs: http://malsup.com/jquery/form/#options-object)
however, trying to log the datasend64 value will help to determind if the function have been called or not. so... in your code:
function edit64(datasend64)
{
console.log(datasend64);
if (datasend64.edit_result64=="ok")
{
jQuery('#htmloutput').fadeIn('slow');
}
}
if a result is shown in the developer console - you can watch the object and seek for your values (if there are any at all). if you don't see anything - the success event havn't occoured (again, i think you are missing the url parameter)

How to render HTML with jQuery from an AJAX call

I have a select box with a list of books. The user can select a book and hit the submit button to view the chapters on a separate page.
However, when the user changes the select box, I would like a partial page refresh to display the past notes the user entered on the book, and allow the user to write a new note for that book. I do not want the review and creation of notes for a particular book done on the next page with the chapters, as it will clutter it up.
I'm using Python/Bottle on the backend and its SimpleTemplate engine for the front end.
Currently, when the select box is changed, an ajax call receives a Json string containing the book information and all the notes. This json string is then converted into a json object via jQuery.parseJson().
What I would like to be able to do is then loop over the notes and render a table with several cells and rows.
Would I have to do this in jQuery/js (instead of bottle/template framework) ? I assume so as I only want a partial refresh, not a full one.
I'm looking for a piece of code which can render a table with variable numbers of rows via jQuery/js from a json object that was retrieved with ajax.
<head>
<title>Book Notes Application - Subjects</title>
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<script>
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
alert(data)
json = jQuery.parseJSON(data);
},
error : function() {
alert("Error");
}
});
})
})
</script>
</head>
<body>
<!-- CHOOSE SUBJECT -->
<FORM action="/books" id="choose_subject" name="choose_subject" method="POST">
Choose a Subject:
<select name="subject_id" id="subject_id">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</select><input type="submit" name="sub" value="Choose Subject"/>
<BR />
</FORM>
This greatly depends on how your JSON and HTML are formatted. But with a table somewhere like:
<table id="books">
<tr>
<th>Chapter</th>
<th>Summary</th>
</tr>
</table>
You could do something like:
$(function(){
$('#choose_subject').submit(function () {
var subject_id = $(this).val();
$.getJSON("subject_ajax?subject_id=" + subject_id, function(data) {
console.log(data);
$.each(data.chapters, function (index, chapter) {
$('#books').append('<tr><td>' + chapter.title + '</td><td>' + chapter.summary + '</td></tr>');
})
});
return false;
})
})
This supposes JSON like:
{
"notes": [
"Note 1",
"Note 2"
],
"chapters": [
{
"title": "First chapter",
"summary": "Some content"
},
{
"title": "Second chapter",
"summary": "More content"
}
]
}
Other notes:
If you use HTML 4 or earlier, keep all your tags in upper case. If you're using XHTML or HTML5, keep all your tags in lower case.
You don't need $(document).ready(function () {...}), with recent versions of jQuery $(function () {...} ) works the same and it's easier to read.
You can use $.get instead of $.json if you're only using the success state (as you are here). And if you're confident that the data you'll get is valid JSON, you can use getJSON instead of get. It will parse the JSON for you deliver it to you as a JavaScript object automatically.
It's usually more convenient to use console.log rather than alert when you're testing. Actually, it's usually a bad idea in general to ever use alert.
I'm not familiar with Python/Bottle or its SimpleTemplate engine, but you could consider generating the html for the table on the server side and returning it in the ajax response, rather than returning JSON.
var subject_id = $(this).val();
$.ajax('subject_ajax', {
type: 'get',
data: { subject_id: subject_id },
dataType: 'html',
success : function(html) {
// Insert the html into the page here using ".html(html)"
// or a similar method.
},
error: function() {
alert("Error");
}
});
When calling .ajax():
The "type" setting defaults to "get", but I prefer to explicitly set it.
Use the "data" setting for the ajax call to specify the URL parameter.
Always specify the "dataType" setting.
I also recommend you perform the ajax call in an on-submit handler for the form, and add an on-change handler for the select that submits the form.
$(document).ready(function(){
$('#subject_id').change(function() {
$(this.form).submit();
});
$('#choose_subject').submit(function(event) {
event.preventDefault();
var subject_id = $('#subject_id').val();
if (subject_id) {
$.ajax(...);
}
});
});
This way your submit button should work in case it is clicked.
There are a few things you need to look at:
1) Is your SimpleTemplate library included?
2) Have you compiled your template via compileTemplate()?
Once you know your library is included (check console for errors), pass your data returned to your success handler method, compile your template, that update whichever element you are trying to update.
I'm not sure that you want to update the same element that you're defining your template in.
$(document).ready(function(){
$('#subject_id').change(function(){
var subject_id = $(this).val();
$.ajax({
url : "subject_ajax?subject_id=" + subject_id,
success : function(data) {
var template_data = JSON.parse(data);
var template = $('#subject_id').toString(); // reference to your template
var precompiledTemplate = compileTemplate(template);
var result = precompiledTemplate(template_data);
$('#subject_id').append(result);
},
error : function() {
alert("Error");
}
});
})
})
You might also try moving your template out of the element you're trying to update like this:
<script type="text/template" id="subject-select-template">
% for subject in subjects:
<option value="{{subject.id}}">{{subject.name}}</option>
% end
</script>
Then just create a blank select element like so:
<select id="select_id"></select>
Update references. Anyway, hope this is helpful. It should work but I can't test without your specific code ;)
Also, check out this demo example if you haven't yet:
https://rawgithub.com/snoguchi/simple-template.js/master/test/test.html

Categories

Resources