How to refresh an html page using ajax in Django? - html

I know this question has been asked several times, but I cannot find a solution.
I cannot connect the method output in views with html page.
views
def save_form(request):
if request.method == 'POST' and 'save' in request.POST:
lsection = [5]
print("calculate method runs...")
return JsonResponse({'lsection':lsection})
"calculate method runs..." is printed only when I do not use ajax.
html
<form method="post" name="nameForm" id="idForm"
action = "/project/save/" enctype="multipart/form-data">
{% csrf_token %}
...
<input type="submit" name="save" value="Save">
</form>
ajax
var frm = $('#idForm');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('save_form'),
url: frm.attr('/project/save/'),
//data: frm.serialize(), // I tried this as well
data: {},
success: function (data) {
alert(data)
},
error: function (data) {
alert("ajax fails")
},
});
});
Question:
I do not get lsection list on html, I try alert(data) I get an empty html.
How can I get lsection on html?

You need attribute's values:
type: frm.attr('method'),
url: frm.attr('action'),
Correct code:
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data)
},
error: function (data) {
alert("ajax fails")
}
});
.attr

While receiving JSON response in ajax success you used data.
to show the lsection.
alert(data.lsection)
update alert like above

Related

I want to Pass Data in a Form to Codeignhter controller throught ajax. when I use this below code sometimes pass data and sometime doesn't

I want to Pass my HTML Form Data in to Codeignhter controller throught ajax. when I check that data passed or not using var_dump() then someitmes it passed data and sometimes doesn't this is the code that I used..
**jQuery Ajax Code**
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
// Get form
var form = $('#myform')[0];
// Create an FormData object
var data = new FormData(form);
// If you want to add an extra field for the FormData
data.append("CustomField", "This is some extra data, testing");
// disabled the submit button
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: hosturl + "studentDetail",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 800000,
success: function (data) {
$("#output").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#output").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
});
});
CodeIgniter (Controller) file method code
public function studentDetail_post()
{
$stu = $this->input->post();
var_dump($stu);
die();
}
This is my HTML form code
<form method="POST" enctype="multipart/form-data" id="myform">
<input type="text" name="fname" placeholder="First Name"/><br/><br/>
<input type="text" name="lname" placeholder="Last Name"/><br/><br/>
<input type="file" name="files"/><br/><br/>
<input type="button" value="Submit" id="btnSubmit"/>
</form>
pls give me a solution for this
try this
$.ajax({
type: "POST",
url : "name codeigniter controler/ name function of this controler",
dataType: 'text',
data: $('#myform').serialize(),
success : function(text){
console.log("SUCCESS : ", data);
},
});
and url: "/upload.php" is not studentDetail_post()

Formatting entity in json format does'nt show in view

This is the view, the success function should make changes in the <p id="mondiv"></p>tags.
<input type="button" value="Refuser" class="refuser" id="{{ demande.id }}">
<p id="mondiv"></p>
<script>
$(".refuser").click(function () {
$.ajax({
url: '{{ path('verifier_demandes') }}',
type: 'POST',
data: {'id_demande': this.id},
dataType: 'json',
success: function (data) {
$.each(data,function (i,e) {
$('#mondiv').append('<ul>'
+'<li>'+e.id+'</li>'
+'<li>'+e.etat+'</li>'
+'<li>'+e.user.nom+'</li>'
+'<li>'+e.user.prenom+'</li>'
+'<li>'+e.user.username+'</li>'
+'</ul>');
})
},
error: function(data) {
alert('error');
}
})
}
);
This is the controller, the entity gets deleted like intended but since then i can't change my view element ( the success function )
if($request->isXmlHttpRequest())
{
if ($request->get('id_demande')) {
$id_gerant = $request->get('id_demande');
$gerant = new Gerant();
$gerant = $em->getRepository("GestionBoutiquesBundle:Gerant")->findOneBy(array('id' => $id_gerant));
$em->remove($gerant);
$em->flush();
$demandes = new Gerant();
$demandes=$em->getRepository('GestionBoutiquesBundle:Gerant')->findBy(array('etat'=>false));
$ser= new Serializer(array(new ObjectNormalizer()));
$data=$ser->normalize($demandes);
return new JsonResponse($data);
}
}
I have looked from both sides, the controller sending back the Json response, and from the view, but couldn't find any result.
EDIT: knowing that the $demandes i'm trying to send back with Json is an array of users, each user has an id, etat, nom, prenom, username..
You made a POST request so you should be able to access to the post data as follow:
$id_gerant = $request->request->get('id_demande');
if($id_gerant) {
....
instead of:
if ($request->get('id_demande')) {
$id_gerant = $request->get('id_demande');
....
As described here in the doc Symfony Request Object
Hope this help

Capture JSON at VB.NET REST

I have 2 checkboxes. I need to capture the checkboxes clicked and send it to REST SERVICE, I am able to capture checkboxes clicked at fnt end but I don't know how to capture it in the REST (VB.Net).
Below is the front end file:
<form>
<input type="checkbox" class = "checkBoxProp" id = "1" name="checkBoxProp" value="1">Graph1<br>
<input type="checkbox" class = "checkBoxProp" id = "2" name="checkBoxProp" value="2">Graph4<br>
<input id="btnGetResponse" type="button" value="ClickMe!"/>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("#btnGetResponse").click(function()
{
var ids = $('.checkBoxProp:checked').map(function() {
return this.value;
}).get();
console.log(JSON.stringify(ids.join()));
$.ajax({
type: "POST",
url: "http://localhost:51349/SMS_Rest.svc/v1/usercheckboxes",
data: {ids: ids} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response)
{
alert('success');
},
failure: function(response)
{
alert('fail');
}
});
});
So how to capture JSON at REST.
Public Function CheckBoxDetails(ByVal requestData As **WHAT TO WRITE HERE**) As String Implements iSMS_Rest.CheckBoxDetails
// SOME LOGIC
End Function
Your method at server-side should be a POST and you should capture the data from body of the request instead of querystring. So, the argument list should have [FromBody] attribute and it would be abetter way if you can create a input model class with similar structure as the input data and have similar properties, use that object as the parameter to the POST method.

How can I use JSON to link my html form to update a sharepoint list?

At the moment I'm just trying to add name to the list. I'll add more when I get that working.
I'm currently getting errors in the debugger with the following :
var siteurl = _spPageContextInfo.webAbsoluteUrl;
Also, I've more than one column in the list, could that be it?
What I have:
$('#submitdata').click(function () {
//this gets the value from your name input
var name = $('#name').val();
var data = {
__metadata: { 'type': 'SP.Data.ProjectsListItem' },
"name": name,
};
$.ajax({
var siteurl = _spPageContextInfo.webAbsoluteUrl;
$.ajax({
url: siteurl + "/mysite/Lists/getbytitle('ChangeOfAddressList')/items",
method: "POST",
data: JSON.stringify(data),
headers: { "Accept": "application/json; odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert('Item added successfully');
},
error: function (error) {
alert("Error: "+ JSON.stringify(error));
}
});
});
HTML:
<body>
<form id="COA_Form" name="myForm" method="post" action="" >
<input type='text' id='name' />
<input type='submit' id='submitdata' value='submit' />
</form>
</body>
To test your code, change the line
var siteurl = _spPageContextInfo.webAbsoluteUrl;
to
var siteurl = 'https://spsitedomain';.
Of course you would want to use your actual SharePoint site domain instead of 'spsitedomain'.
You can open the console and see what the _spPageContextInfo object yields. In my browser, I either get undefined or I get an object that does not have a webAbsoluteUrl property (depending on the page I am viewing), so your mileage may vary when using this object.

Data not getting saved using JQuery.ajax

I want to save data from Textbox on Button click. I am using JQuery AJAX for this task like below. Please note that I made this tags inside theme function.
function theme_user_post_block($vars)
{
$themeUserCommentInput ='';
$themeUserCommentInput .= '<textarea id="txt_1"rows="1" cols="50"></textarea>';
$themeUserCommentInput .= '<input type="submit" value="Post Comment" align="center"
class="btnPostComment" id="btn_1" />'
return $themeUserCommentInput;
}
This able to show me Textbox and Button inside the page. Now here is my JS code:-
(function($)
{
Drupal.behaviors.PostComment= {
attach: function (context, settings) {
$('.btnPostComment', context).click(function (event) {
var post = "&newcomment=Comment1&logid=log1";
jQuery.ajax({
url: 'postcomment',
type: 'POST',
dataType: 'json',
data: post,
success: function (data) { alert(data); },
error: function(jqXHR, textStatus, errorThrown){alert(textStatus +
errorThrown);}
});
});
}
}
})(jQuery);
Next I create a Menu Page with URL Name as follows:-
function postcomment_menu(){
$items=array();
$items['postcomment']=array(
'title'=>t(''),
'type'=> MENU_CALLBACK,
'page callback' => 'user_comment_post',
'access arguments' => array('access content'),
);
return $items;
}
function user_comment_post(){
global $user;
$cid = db_insert('user_comment')
->fields(array(
'comment_user_id' => $user->uid,
'reference_id' => $_POST['logid'],
'comment_desc'=>$_POST['newcomment'],
'createdon'=>REQUEST_TIME,
))
->execute();
if($cid!=0)
{
//GetUserComments($i);
drupal_json_output("success");
}
}
So I have done all things that is required for jQuery+Ajax Submit functionality. When I press "Post Comment" button it gives me error in alert says "errorundefined". The alert shows as a result of error inside the jQuery.AJAX function. Also the custom menu callback is also not getting called.
post the data as object...and make sure your post url is correct.. the url doesn't looks correct
var post = {newcomment: 'Comment1',logid:'log1'};
I came to end of this problem. I dont know what might be the resolution or root cause but I end up solving this problem. I meagre add one line(async: false) in my jQuery.ajax function and everything works perfectly. Please see the code below:
jQuery.ajax({
url: 'postcomment',
type: 'POST',
dataType: 'json',
async: false,
data: post,
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + errorThrown);
}
});
If anyone have any knowledge as what this line will do then please share with us.