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

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

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.

AJAX Form, passing return message

I have my AJAX form it works great.
Every time I submit the form It returns the result inside the <div id="message"></div>, but it gets complicated when I have multiple forms. So I was wondering if their is a way to indicate inside the form what <div> to return the message to.
Here is my AJAX.js
$("form#ajaxForm").on("submit", function() {
var form = $(this),
url = form.attr("action"),
type = form.attr("method");
data = {};
form.find("[name]").each(function(index, value){
var input = $(this),
name = input.attr("name"),
value = input.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$("#message").html(response); //I would like to interactively switch the return div, from #message to like #message2
$("body, html").animate({
scrollTop: $( $("#message") ).offset().top - 5000
}, 600);
}
});
return false;
});
In the form I would like to indicate where the return div is, like
<form action="../forms/add_event_form.php" method="post" id="ajaxForm">
//Can I add an input somewhere here? To indicate where I want the return to go too? Like <input type="hidden" value="message2" name="return">
<input type="text" class="formI" name="date" id="dateI" placeholder="Date">
<input type="submit" name="submit" class="btn btn-primary" value="Add">
</form>
Thank you for reading this. Have a good day! And Thank you in advance for your responses.
Yes, it will not work automatically, but you can add some information to the form and then use it to decide where to put returned HTML. Doing that with additional inputs may not be the best way though, as it can be achieved with far less impact on the DOM: with an attribute on the form itself.
Here's an example of how you may do that.
$(".ajaxForm").on("submit", function(e) {
e.preventDefault();
var form = $(this);
// using jQuery's `data()` to get an ID of response element from the 'data-response' attribute
var responseElementId = form.data("response");
var response = $(responseElementId);
response.html(produceResponse(form));
// function that produces some html response
// you'll use AJAX request to the server for that
// so don't mind its complexity or bugs
function produceResponse(form) {
var data = form.find("input").map(function(i, el) {
return "'" + el.name + "': " + el.value;
});
return "<p>You've submitted:\n<pre>" + Array.prototype.join.call(data, ",\n") + "</pre></p>";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Form #1</h2>
<form action="#" class="ajaxForm" data-response="#response1">
<input name="first-name" type="text">
<button>Submit</button>
</form>
<div id="response1"></div>
<h2>Form #2</h2>
<form action="#" class="ajaxForm" data-response="#response2">
<input name="last-name" type="text">
<button>Submit</button>
</form>
<div id="response2"></div>
Here I use a data attribute because it was designed for cases like this: to store arbitrary data related to the element, but which doesn't have any defined meaning for the browser. Accessing data stored in such way is really convenient with its HTML5 API, but because of pretty low support from IE (it has it only starting from the version 11), one may use jQuery's method data() to do the same.

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 can I filter data returned from jQuery?

jQuery code:
$(document).ready(function() {
$('#s-results').load('get_report1.php').show();
$('#search-btn').click(function(){ showValues(); });
$(function() {
$('form').bind('submit', function() { showValues(); return false; });
});
function showValues() {
$.post('get_report1.php', { name: form.name.value },
function(result) {
$('#s-results').html(result).show();
}
);
}
});
HTML:
<form name = "form">
<div>Enter name</div>
<input type="text" name="name" id="fn" />
<input type="submit" value="Search" id="search-btn" />
<div>
<input type="text" id="se2" name="search22">
</div>
</form>
<div id = "s-results" style="height:50px;">
</div>
Up to this the script is running perfectly. Now I just want to filter the returned HTML from the above function again.
For implementing this I have tried this line of code:
$(result).filter('#se2');
under the function with the result parameter, but it is not working.
So how can the returned HTML code be filtered?
You probably need find() instead of filter as you need to get the descendant whereas filter "Reduce the set of matched elements to those that match the selector or pass the function's test"
Live Demo
$(result).find('#se2');
If the #se is added in DOM then you can directly use the id selector
se = $('#se2');
I made another demo (as I am still waiting for your demo that is not working) to further elaborate how a string containing the html you have could be passed to jQuery function $() to search elements within it using find.
Live Demo
html = '<form name = "form"> \
<div>Enter name</div> \
<input type="text" name="name" id="fn" /> \
<input type="submit" value="Search" id="search-btn" /> \
<div> \
<input type="text" id="se2" name="search22" value="se2"/> \
</div> \
</form>\
<div id = "s-results" style="height:50px;"> \
</div> ';
alert($(html).find('#se2').val());
Note You can further check the code working in the example above by using find wont work by using filter over this jsfiddle example
The issue
You are successfully adding the result to #s-results:
$('#s-results').html(result).show();
And then tried to select #se2 from the added results like this, with no success:
$(result).filter('#se2');
It didn't work because you didn't get it from the dom added in the second step.
Actually, it is creating a new unattached dom with the same result variable.
The solution
To select #se2 from the added result content correctly, try the following:
$('#s-results').filter('#se2');
Or, as suggested by #zerkms, you could select it directly through:
$('#se2');
These possibilities will work, because now it is referencing something attached to dom, which will search into the same elements you added in the first step.
You can try to use ajax for this as below:
$(document).ready(function () {
$('#s-results').load('get_report1.php').show();
$('#search-btn').click(function () {
$.ajax({
type: "POST",
url: "get_report1.php",
data: {
name: $("#fn").val()
},
beforeSend: function () {
//do stuff like show loading image until you get response
},
success: function (result) {
$('#s-results').html(result).show();
},
error: function (e) {
alert("Error in ajax call " + e);
}
});
});
});
Note: When you click on search-btn each time it will call the get_report1.php file and retrieve the data base on the text-box value that you have passed. I assume that in ge_report1.php file you are using the tex-box value like: $_POST['name'] and you are fetching the data using MySQL search query.
You can use JQuery find instead of filter.
$(result).find('#se2');
Then add to your variable like this
var your_element = $('#se2');

How to submit a form with specific fieldset

I have a form like this:
<form name="paymentForm" id="paymentForm" action="/submit.jsp" method="post">
<fieldset id="ccData">
<input id="ccNumber" name="ccNumber"/>
</fieldset>
<fieldset id="otherData">
<input id="requestId" name="requestId"/>
</fieldset>
</form>
When you slick submit, I would like to submit(via ajax) only #ccData filedset to some different url (e.g. submitCC.jsp) and based on response I want to submit full form to actual url.
How can I achieve that ?
Use jQuery's serialize method
var formData = $("#ccData").serialize()​;
$.post("TheUrl",formData);
You could do that with JavaScript - e.g jQuery. You build an eventHandler like
$('#paymentForm').on('click', function () {
$(this).preventDefault();
if ($(this).hasClass('first_send')) {
$.ajax({
url: "your_url",
data: { ccData: $('#ccData').val()}
}).done(function ( data ) {
$('#paymentForm').addClass('first_send')
// examin the data, insert stuff you need and send the form again
// with ajax
})
} else {
$(this).removeClass('first_send')
// this is the second send - so do stuff here - show a result or so
}
})
With the class first_send you can check if it is the first send or the second. This is just an untested, incomplete idea how you could do it. I guess you get the big picture ...

Categories

Resources