Ajax returning empty string in Django view - javascript

I am developing a web application through Django and I want to get information from my javascript to a view of Django in order to access to the database.
I am using an ajax call as this post shows.
I am calling the js in html by an onclick event :
sortedTracks.html
...
<form action="{% url 'modelReco:sortVideo' video.id %}">
<input type="submit" value="Validate" onclick="ajaxPost()" />
</form>
...
clickDetection.js
//defined here
var tracksSelected = [];
//function that fill tracksSelected
function tagTrack(track_num){
if(tracksSelected.includes(track_num)){
var index = tracksSelected.indexOf(track_num);
tracksSelected.splice(index, 1);
}else{
tracksSelected.push(track_num);
}};
//ajax function
function ajaxPost(){
$.ajax({
method: 'POST',
url: '/modelReco/sortedTracks',
data: {'tracksSelected': tracksSelected},
success: function (data) {
//this gets called when server returns an OK response
alert("it worked! ");
},
error: function (data) {
alert("it didnt work");
}
});
};
So the information I want to transfer is tracksSelected and is an array of int like [21,150,80]
views.py
def sortedTracks(request):
if request.is_ajax():
#do something
print(request)
request_data = request.POST
print(request_data)
return HttpResponse("OK")
The ajax post works well but the answer I get is only an empty Query Dict like this :
<QueryDict: {}>
And if I print the request I get :
<WSGIRequest: GET '/modelReco/sortedTracks/?tracksSelected%5B%5D=25&tracksSelected%5B%5D=27&tracksSelected%5B%5D=29'>
I have also tried to change to request_data=request.GET but I get a weird result where data is now in tracksSelected[]

I've tried to know why if I was doing request_data=request.GET, I get the data like this tracksSelected[] and get only the last element of it.
And I found a way to avoid to have an array in my data (tracksSelected) on this link
This enables me to have :
in views.py
def sortedTracks(request):
if request.is_ajax():
#do something
print(request)
request_data = request.GET.getlist("tracksSelected")[0].split(",")
print(request_data)
and in clickDetection.js
function ajaxPost(){
tracksSelected = tracksSelected.join();
$.ajax({
method: 'POST',
url: '/modelReco/sortedTracks',
data: {'tracksSelected': tracksSelected},
success: function (data) {
//this gets called when server returns an OK response
alert("it worked! ");
},
error: function (data) {
alert("it didnt work");
}
});
};
This little trick works and I am able to get the array data like this,
print(request_data) returns my array such as [21,25,27]
Thank you for helping me !

According to me to access the data which is sent in the ajax request can be directly accessed .
For Example:
def sortedTracks(request):
if request.method == 'POST':
usersV = request.POST.get('tracksSelected')[0]
for users in usersV:
print users
return HttpResponse("Success")
else:
return HttpResponse("Error")
The correct syntax is data: {tracksSelected: tracksSelected},

Related

Ajax is not sending multiselect data to Django views

I am quite new to Django so bare with me.
I have a multiselct list in my webpage and I need to send the selected items to my views in order to make use of them.
To do so, I used ajax but when it doesn't seem to work for some reason.
This is the script:
$("#var_button").click(function(e) {
var deleted = [];
$.each($("#my-select option:selected"), function(){
deleted.push($(this).val());
});
alert("You have deleted - " + deleted);
e.preventDefault();
$.ajax({
type: "post",
url: "/description/upload-csv/" ,
data: {
'deleted' : deleted }
}); // End ajax method
});
I checked with alert if maybe the variable deleted is empty but it return the selected values so the problem is in my ajax query.
This is the part where I retrieve the data in my views.py
if request.method == 'POST':
del_var = request.POST.getlist("deleted[]")
my_class.del_var = del_var
I changed the data type to text but it doesn't do anything
I cant help you on the Django side.
$.each($('#selector'), (i, e) => {
deleted.push($(e).val());
})
but this will add the value to the "deleted" variable.

Wp_admin ajax request returns with response "0"

I am new to code, and trying to learn things by doing them.
Currently, I am trying to do something very simple using wordpress. which I am trying to create some posts in wordpress, using some external data.
I can fetch the data using CURL. No problem with that and post it using Wp_insert_post, directly.
But, What I want to do is trigger the wp_insert_post function on click of a button in the admin panel ( I have created this as a plugin and a separate plugin dashboard, where the button Is embedded). I have been messing around with the code, and sending the data to wp-admin-ajax.php work fine, and gives the response code 200. But, the response receiving is "0" . if the data passed through are correct, I presume, the response should be "1" ?
I have the following code at the moment.
//Button
<form id="formtesting">
<input type="text" id="name" placeholder="Name">
<input type="submit" id="user-submit" value="user-submit">
//Ajax Call
$(document).ready(function() {
var userSubmitButton = document.getElementById('user-submit');
var adminAjaxRequest = function(formData, myaction) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wpdevelopment/wp-admin/admin-ajax.php',
data: {
action: myaction,
data: formData
},
success: function(response) {
if (true === response.success) {
alert('success');
} else {
alert(response);
}
}
});
};
userSubmitButton.addEventListener('click', function(event) {
event.preventDefault();
var formData = {
'name': document.getElementById('name').value
};
adminAjaxRequest(formData, 'data_submission');
});
});
And here is my test function // to test whether the function initiate properly, i try to send a Json error, So then I can include wp_insert_post details.
function data_submission(){
wp_send_json_error( 'I am an error' );}
add_action( 'wp_ajax_data_submission', 'data_submission' );
add_action( 'wp_ajax_nopriv_data_submission', 'data_submission' );
Could not locate where the faulty is. Some help would be appriciated
tks
Use add_action(' wp_ajax_myaction', 'yours_callback_fanc');
wp_ajax_
Remain part is yours action name that is defined into yours ajax call. In yours case it's myaction.
First this is not a standard way to use ajax in wordpress,
use wp_localize_script for embedding the global ajax_url variable,
wp_register_script('plugin-ajaxJs', plugins_url('/js/ajax-call.js', __FILE__));
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax_url', array('ajax_url' => admin_url('admin-ajax.php')));
Now as url in ajax you can add my_ajax_url.ajax_url,
this will send a request to admin-ajax.php.
Now coming to your question
you are returning an wp_json_error so the result is 0,
use this and return whatever data you wants in ajax success,
$responce['result'] = 1
wp_send_json( $response );

PHP not reciving data with AJAX's POST

I have to say I saw a dozens of topics similar to my problem, but most of them were typos or spelling.
My PHP file does not seem to receive any data from AJAX POST function (I'm getting Undefined Index). Here is my code:
var login = $("#log_l").val();
var pwd = $("#pwd_l").val();
alert(login);
alert(pwd);
$.ajax({
type: "POST",
url: 'app/menu/login.php',
data: {
login1: login,
pwd1: pwd,
},
cache: false,
success: function (data) {
if (data == 'fail') {
alert('test2');
$('#failure_log').show();
}
else {
document.location = " {$conf->action_root}postlogin";
}
}
});
return false;
And the login.php:
$login = $_POST['login1'];
$haslo = $_POST['pwd1'];
...
I tried with both:
login1:login,
pwd1:pwd,
And:
'login1':login,
'pwd1':pwd,
But in both ways I receive "Undefined index" error in .php file on 'login1' and 'pwd1' variables.
I checked that ajax 'reaches' file and it even receives the echos from .php file, but the variables are not sent/received.
Do you have any ideas what might be wrong?
You need to use file_get_contents to capture ajax calls or you need to define. Check this
How to get JSON data in php ?
Or
you need to set the ajax call as form_encoded_url
contentType: "application/x-www-form-urlencoded",
refer this link
Submitting HTML form using Jquery AJAX

Laravel 5.2 - Return view from controller after ajax request

I have a javascript function that sends to a Controller some information (mostly vars like arrays and ids) to be inserted in a table, the problem is after the insertion is completed I want to return to a different view with a data array and i cant seem to do this (I think its because of the ajax request)
Javascript Code
$('#importar').submit(function(e) {
e.preventDefault();
fdata=preparePostData();
$.ajax({
type:'POST',
url: $(this).prop('action'), // url, from form
data:fdata,
processData: false,
contentType: false,
success:function(data) {
window.location.replace(data.url);
}
});
}); // end form.submit
Function Prepare PostData()
var file_data=$('input:file')[0].files;
var postdata=new FormData();
postdata.append('_token',token);
postdata.append('startFrom',startFrom);
postdata.append('idList',idList);
postdata.append('nomeCampos',nomeCampos);
postdata.append('posicaoCampos',posicaoCampos);
postdata.append('file',file_data[0]);
return postdata;
Controller Expected Code
Do all inserts and functions and in the end
$data = array('listNome' => $listName, 'contacts' => $contacts, 'errors' => $erro);
return view("XPTO", $data);
You should not return a view from an ajax call, because you'd get the view processed code as a parameter to the ajax callback. Think of an ajax call as an async 'behind the scenes' call to the server in which you pass parameters and get some other parameters back
You should instead return a JSON response from the controller with all the parameters you'll need to call the route from JS, and parse it in your success callback. For example:
Controller
//here you should store all the parameters you need in your JS calback
$data = array('status' => 'ok', 'url' => $redirect_url );
JS
success:function(data)
{
//data will contain the parameters you set in the controller, so you can use them to call the route
if ( data.status == 'ok' )
window.location.replace(data.url);
}
Just elaborating previous answer , Ajax call controllers are used to supply some data behind the scenes and standard controllers are used to control the view so best practise is to return data (JSON) form Ajax controller to the same view which requested the data. while the standard controller should be used to control the views.
SOLVED
Not the most elegant solution but what I did was set the array with errors as an session variable and get that session var in the specific controller I need.
Controller
$request->session()->put('importErrors',$erro);
$response = array('status' =>'success','url' => '/ListarContactos/'.$idList);
return response()->json($response);
JavaScript
$('#importar').submit(function(e) {
e.preventDefault();
fdata=preparePostData();
$.ajax({
type:'POST',
url: $(this).prop('action'), // url, from form
data:fdata,
processData: false,
contentType: false,
success:function(data) {
if(data.status=='success'){
window.location.replace(data.url);
}
}
});
}); // end form.submit
XPTOController
$errorArray= $request->session()->get('importErrors');
After using it you can destroy the session variable or keep it(depending if you need it or not).

Django + Ajax error in returning data

I have a model called Item and I'm trying to create Items with Ajax, everything looks to be working ok, but I'm getting and error at the end of the process, in the success function in Ajax. I have been reading a lot of answers to questions like this here in StackOverflow but I couldnt make it work:
This is my model:
PRIORITY_CHOICES = (
(1, 'Low'),
(2, 'Normal'),
(3, 'High'),
)
class Item(models.Model):
name = models.CharField(max_length=60)
description = models.TextField(max_length=1000)
created = models.DateTimeField(auto_now_add=True)
priority = models.IntegerField(choices=PRIORITY_CHOICES, default=1)
done = models.BooleanField(default=False)
meeting = models.ForeignKey(Meeting)
def __str__(self):
return self.name
This is my view, whichs is working Ok and saving the data into de database:
from .forms import AddItemForm
from .utils import render_to_json_response
class AjaxFormResponseMixin(object):
def form_invalid(self, form):
return render_to_json_response(form.errors, status=400)
def form_valid(self, form):
# save
self.object = form.save()
# initialize an empty context
context = {}
# return the context as json
return render_to_json_response(self.get_context_data(context))
class AjaxItemCreateView(AjaxFormResponseMixin, CreateView):
form_class = AddItemForm
def get_context_data(self, context):
context['success'] = True
context['name'] = self.object.name
context['description'] = self.object.description
return context
as you can see, I'm using a custom shortcut called render_to_json_response in order to parse data in Json
this is the code of the shortcut (Please notice that I'm printing the context, in order to verify the data):
from django.http import JsonResponse
def render_to_json_response(context, **response_kwargs):
print (context)
return JsonResponse(context)
(if you're wondering why I'm using this simple shortcut it's because previously I was trying to return the response with HttpResponse and specifying content_type="application/json", but it also wasn't working)
This is my ajax code:
function AddItem(event){
var csrftoken = getCookie('csrftoken');
var item_name = $('#item-name').val();
var item_desription = $('#item-description').val();
var item_priority = $('#item-priority').val();
var item_meeting_pk = $('#item-meeting-pk').val();
var url = "/item/add/";
$.ajax({
type: "POST",
url: url,
data: {
'name': item_name,
'description': item_desription,
'priority': item_priority,
'meeting': item_meeting_pk ,
'csrfmiddlewaretoken': csrftoken
},
success: function(data){
alert("success");
alert(data);
},
complete: function(data){
alert("completed");
alert(JSON.stringify(data));
}
});
}
and, finally, this is the form that calls the AddItem() function:
<form>
{% csrf_token %}
<input type="text" placeholder="Nombre del item" id='item-name'/>
<input type="text" placeholder="DescripciĆ³n del item" id='item-description'/>
<select id="item-priority" name="provider" class="form-control">
<option value="1">Baja</option>
<option value="2">Normal</option>
<option value="3">Alta</option>
</select>
<input type='hidden' id='item-meeting-pk' value='{{ meeting.pk }}'>
<button onclick='AddItem()' class="button-blue" >Agregar</button>
</form>
When I submit the form, everything goes fine, and in my django shell I can see that the post request is returning 200 and the data is printing ok:
{'name': 'asdkkasd', 'description': 'sdksdksjd', 'success': True}
[29/Aug/2015 08:34:22]"POST /item/add/ HTTP/1.1" 200 65
in the ajax function I have javascript alerts in both success and complete, but only the complete's one is executing and this is what I'm getting with the execution of alert(JSON.stringify(data));:
{"readyState": 0, "responseText":"", "status":0, "statusText": "error"}
I hope you can help me, thank you :)
Your form is almost certainly invalid; you're returning a 400 status in that case from form_invalid, which triggers jQuery to call the failure function if there is one, rather than success.
Unfortunately, you can't use proper RESTful status codes in this kind of situation. An invalid form submission should still return a 200.
There is a difference between success and complete function of the ajax function that you are using...
success
It gets called on a response of 200 (OK).
complete
This will get called always , well as the name suggests the request did succeed, even if was a failure on the server side or OK response. It just succeeded (ie: landed your server and brought something back to offer to your client(browser,mobile whatever).So that's complete method for.
You can do away with this method and can use only success if not needed otherwise.
For more info. Read here
FYI :
The readystate output you showed says 0 , hence the request isn't initialized.It should be 4 for the request to be complete.

Categories

Resources