jquery form plugin and show content of div - javascript

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)

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.

JavaScript jQuery issue with submit button

I have a problem. I think it's because of the rendering but I don't know because that topic is new to me.
Okay, I have a simple form:
<form method="post" action="/send-mail">
<input type="text" name="msg" value="">
<input type="submit" value="send that fancy mail">
</form>
Now i want to catch that submit using jQuery like:
$('[type=submit]').submit(function(e) {
e.preventDefault();
var formHtml = $(this).parent().html();
$.ajax({
..all these options..,
beforeSend: function(xhr) {
$('form').html("sending mail");
},
success: function(data) {
$('form').html(formHtml); // I think here's the problem...
}
});
});
okay, that code works really good. It does what it should do. But, If I want to send a second request, the submit button doesn't work anylonger as intended. It tries to send the form using the default-action although I prevnted that - at least that's what I thought.
I did use google but I don't even know how to explain my problem.
Hopefully someone can help me, thanks a lot!
Greetz
Instead of .html() you can use:
.clone(true): Create a deep copy of the set of matched elements.
.replaceWith(): Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
The event must be click if attached to submit button or submit if attached to the form.
The snippet:
$('[type=submit]').on('click', function (e) {
e.preventDefault();
var formHtml = $(this).closest('form').clone(true);
$.ajax({
dataType: "json",
url: 'https://api.github.com/repos/octocat/Hello-World',
beforeSend: function (xhr) {
$('form').html("sending mail");
},
success: function (data) {
console.log('Success');
$('form').replaceWith(formHtml); // I think here's the problem...
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="/send-mail">
<input type="text" name="msg" value="">
<input type="submit" value="send that fancy mail">
</form>
Use $(document).on("click", "[type=submit]", function (e) { for dynamically created ekements instead of $('[type=submit]').submit(function(e) {
Use <input type="button"> instead of <input type="submit"> and add an onclick function like this:
<input type="button" onclick="_submitForm()" value="send that fancy mail">
And then your js will be:
function _submitForm(){
var formHtml = $(this).parent().html();
$.ajax({
..all these options..,
beforeSend: function(xhr) {
$('form').html("sending mail");
},
success: function(data) {
$('form').html(formHtml); // I think here's the problem...
}
});
}
I hope that solved your problem.

AJAX / jQuery $.get method works, but $.post does not

Yesterday I made my first successful AJAX call using this function which was linked to a button click event.
function function1(){
$.get("ajax/calendar.php", function(data){
$('#ajaxResponse').html(data);
});
};
Now I would like to use the $.post method so that I can pass in 2 values that I had simply hard coded when I used the $.get method.
Here are my inputs and submit button:
<div ... >
<div ... >
<div ... >
<span ... >From:</span>
<input ... name="strDte">
</div>
<div ...>
<span ... >To: </span>
<input ... name="endDte">
</div>
</div>
<div ... >
<button type="submit" onclick="dateRange(strDte, endDte)">OK</button>
</div>
</div>
I created a similar function to my $.get method:
function dateRange(startD, endD){
$.post("ajax/calendar.php", {startDate : strDte, endDate : endDte}, function(data){
$('#ajaxResponse').html(data);
});
};
and I updated "ajax/calendar.php" to accept the value that were hard coded before:
$formStartDate = $_POST['startDate'];
$formEndDate = $_POST['endDate'];
EDIT: my console is telling me that the parameters are not being recognized by function call in the event handler.
Does anyone see what my issue is? I'd also love some design suggestions if you think there is a better way of achieving this function.
You are passing up form elements, not the values of the elements. You have wrong variable names.
Give the inputs ids
<input ... name="strDte" id="strDte">
<input ... name="endDte" id="endDte">
Update the JavaScript to reference the value.
function dateRange(startD, endD){
$.post("ajax/calendar.php", {startDate : startD.value, endDate : endD.value}, function(data){
$('#ajaxResponse').html(data);
});
};
You are using bad practice by referencing elements directly by their name/id and inline events are not the greatest thing to use. You should use getElementById or querySelector to reference the elements.
The variable names used in your function definition should match the names you use within your function. That is
{startDate : strDte, endDate : endDte}
should be
{startDate : startD, endDate : endD}
I suggest you play around with this fiddle: http://jsfiddle.net/Uwcuz/3657/
It is using a service from JSFiddle to echo back what you send to it. I changed the AJAX call to use $.post() instead of $.ajax() since this is the function you are playing with! :)
Some additional tips when learning such technologies. Always check with your browsers developers' tools. There you can follow the request being sent to your backend and catch any errors. The "Network" and "Console" (on Chrome dev tools, but Firefox has similar, too) tabs are your friends in this case!
Enjoy and happy learning!
Since you are not using a form, you should be declaring your button to be a button type to show that you are not submitting a form.
<button id="submitBtn" type="button">OK</button>
Your problem is that you are not supplying an id attribute for your <input> tags. name is only used in forms. Change your <input> tags to be
<input id="strDte">
<input id="endDte">
Then in your script, you can use
$("#submitBtn").click(function () {
var start = $("#strDte").val();
var end = $("#endDte").val();
$.post("ajax/calendar.php", { startDate: start, endDate: end }, function (data) {
$("#ajaxResponse").html(data);
}
});
The variable names you pass into the function must pass those you use in the data parameter of $.post(). You're passing:
startD but trying to use strDte .. and
endD but trying to use endDte .... strDte and endDte are not defined anywhere.
Try this instead:
function dateRange(startDate, endDate){
$.post("ajax/calendar.php", {startDate : startDate, endDate : endDate}, function(data){
$('#ajaxResponse').html(data);
});
};
UPDATE
Now that I know where the confusion was coming from the best approach is one that allows you to separate, clearly, your JS from your HTML.
Per your request for suggestions, here's how:
$(function() {
$('#my_form').on('submit', function(event) {
//stop the form from submitting via default submission
event.preventDefault();
//get form data
var formData = $(this).serialize();
//see what the data looks like
console.log( formData );
//make ajax call
$.post('ajax/calendar.php', formData, function(data){
$('#ajaxResponse').html(data);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="my_form">
<div><label for="strDte">Start Date:</label>
<input type="text" name="startDate" id="strDte"/>
</div>
<div><label for="endDte">End Date:</label>
<input type="text" name="endDate" id="endDte"/>
</div>
<div>
<input type="submit" value="OK" />
</div>
</form>
here is a simple ajax post you can play around with...
<input id="start_date" name="startDate" />
<input id="end_date" name="endDate" />
<button type="submit" id="submit_dates">Submit</button>
$(document).ready(function(){
$("button#submit_dates").click(function(){
var startDate = $("#start_date").val();
var endDate = $("#end_date").val();
$.ajax({
type:'POST',
url:'ajax/calendar.php',
data:"startDate=" + startDate + "&endDate=" + endDate,
success:function(data) {
if(data) {
$("#ajaxResponse").html(data);
} else {
// no response
}
}
});
});
});

AJAX returns data twice on submit

Instead of redirecting the user to a new page, I want to add an overlay over the form. Somehow, the following code returns the overlay twice.
AJAX
$(document).ready(function ()
{
$('#form_informations').submit(function ()
{
$.get('php/formulaires.php', $(this).serialize(), function (data)
{
$('#form_informations').append('<div id="conf_informations" class="confirm"><p><img src="img/check.png" /><br /><?=FORMULAIRE_SAUVEGARDE;?></p></div>');
});
return false;
});
});
The id #form_informations is only used once.
For now, the second overlay is not created in php/formulaires.php because the file is empty as I have not started parsing the data.
Why is this happening? I don't see where this second overlay is coming from.
This is the HTML form:
HTML Form
<form id="form_informations" method="post" enctype="multipart/form-data">
<!-- form here -->
<input type="submit" name="submit_general" value="Save" />
</form>
May be you can add some code like this in the submit function
if(!$("#conf_informations").size()) {
$.get... //your get request here
}
Final solution
if(!$("#conf_informations").length()) {
$.get... //your get request here
}

Categories

Resources