How do django send ajax response? - ajax

Here is my code ,I got response is 200 OK but ajax came to error part
I can't figure it out
My html:
$(".statics").click(function(){
var name = $(this).attr("data-name");
$.ajax({
url: 'statics/',
data: {
'name':name
},
type: 'POST',
async: false,
dataType: 'json',
success: function(dataArr){
console.log("ssss:",dataArr)
if(dataArr == "IS_PASS"){
alert('PASS!');
}else if(dataArr == "NOT_PASS"){
alert('NOT_PASS');
}
},
error: function(ts){
console.log("eeee:",ts)
alert('fail');
},
});
});
My views.py
def statics_r(request):
if request.is_ajax():
name = request.POST['name']
...
if is_pass:
return HttpResponse("IS_PASS")
else:
return HttpResponse("NOT_PASS")
And the console is : eeee: Object {readyState: 4, responseText: "NOT_PASS", status: 200, statusText: "OK"}
Why it is not success???

For an ajax response, you should be returning json, the easiest way is to use the JsonResponse class instead of HttpResponse, or set the content_type
HttpResponse("{'result': 'IS_PASS'}", content_type="application/json")
You would need to adjust your success function to access the results, i.e dataArr.result

Related

Detect successful response from ajax function

I have a function which is triggered via AJAX and will run the following when successful:
wp_send_json_success();
I am then doing a console log of the response and trying to detect if success = true:
.done(function (response) {
if( response['success'] == true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Currently I am getting "add to cart failed" despite the output of response looking like it should be successful:
console.log(response);
// Response in the browser console:
{"success":true}
Am I detecting the true response incorrectly?
Update - PHP function the AJAX is triggering. Removed most code just as a test.
function fbpixel_add_to_cart_event_conversion_api() {
echo 'hello world';
wp_send_json_success();
die();
}
add_action('wp_ajax_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
add_action('wp_ajax_nopriv_fbpixel_add_to_cart_event_conversion_api', __NAMESPACE__.'\\fbpixel_add_to_cart_event_conversion_api');
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'fbpixel_add_to_cart_event_conversion_api',
product_id: productId,
variation_id: variationId,
},
})
.done(function (response) {
console.log(response);
console.log(productId);
console.log(variationId);
console.log(response.success);
if( response.success === true ) {
I always use dot notations to check the response returned from wp_send_json_success, and it always works. So use it like this:
if( response.success === true ) {
console.log('add to cart successful');
} else {
console.log('add to cart failed');
}
Give it a shot and let me know if you were able to get it to work!
I should have pasted the entire code sorry. I had the wrong dataType set within $.ajax:
Before
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'html',
})
After
$.ajax({
url: MyAjax.ajaxurl,
type: 'POST',
dataType: 'json',
})

Ajax call from extjs to Yii action url not showing post data

I am trying to pass data to yii controller through ajax.
This is my ajax code in extJs:
Ext.Ajax.request({
url:action_url,
type: 'POST',
dataType: 'json',
data:{insurance: insurance_id},
success:function(res){
console.log(res);
},
In Yii Controller :
public function actionTest()
{
$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_JSON;
if(Yii::$app->request->isAjax)
{
$data = Yii::$app->request->post();
$response->data = ['data' => $data];
} else {
$response->data = ['fail' => 'failed'];
}
return $response;
Yii::$app->end();
}
I am getting the response as :
{request: {…}, requestId: 6, status: 200, statusText: "OK",…}
responseText:"{"data":[]}"
I am stuck with this. please help.
Added _csrf with other parameters.
Ext.Ajax.request({
url:action_url,
method: 'POST',
dataType: 'json',
params:{insurance: insurance_id, _csrf : csrf_tok}
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
success:function(res){
console.log(res);
},

django ajax MultiValueDictKeyError

I am receiving this error:
MultiValueDictKeyError at /orders/ajax/add_order_line
"'cart'"
Here is my script
var cart = {
0: {
id: "1",
quantity: 50
}
}
$.ajax({
url: myURL,
type: "post",
data: {cart: cart},
success: function() {},
error: function(){}
});
Meanwhile in my django views, the error was found in this line:
def something(request):
cart = request.POST['cart']
Use get method of multivaluedict
request.POST.get('cart')
Your data is a nested array, so you can't send it using the default default application/x-www-form-urlencoded content type.
You can send the data as json:
$.ajax({
url: myURL,
type: "post",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({cart: cart}),
success: function() {},
error: function(){}
});
Then in your view, you have to load the json string from request.body instead of using request.POST (which is for form-encoded data only).
import json
def my_view(reqest):
data = json.loads(request.body.decode('utf-8'))
cart = data.get('cart')

ajax post request to view

I am trying to make a simple ajax request to a view but keep having a not Found error for the given url:
Not Found: /myapp/start_session/1/scan_ports/
"POST /myapp/start_session/1/scan_ports/ HTTP/1.1" 404 5711
js
$(document).ready(function() {
$.ajax({
method: 'POST',
url: 'scan_ports/',
data: {'csrfmiddlewaretoken': '{{csrf_token}}'},
success: function (data) {
alert("OK!");
},
error: function (data) {
alert("NOT OK!");
}
});
});
url
url(r'^scan_ports/$',views.ScanPorts,name='scan_ports'),
view
#login_required
def ScanPorts(request):
user = request.user
if request.method == 'POST':
currentSetting = models.UserSetting.objects.filter(isCurrent=True)
if currentSetting.serialPort:
print("GOT IT!")
return HttpResponse('')
Is the ajax request not set properly?
Assuming you are in the "myapp" app, replace:
method: 'POST',
url: 'scan_ports/',
for this:
method: 'POST',
url: '/myapp/scan_ports/',
First check your urls, the url on which you posted is incorrect hence 404 not found error.
Try to define your url in your JS as: {% url 'scan_ports' %} which will search your urls with the name your provided in urls.py
In addition, this may not be a good approach to submit a form via ajax.
Your JS should be something like this:
$('.form-class-name').on('submit', function (e) {
e.preventDefault();
console.log("ajax is called");
$.ajax({
type: $(this).attr('method'),
url: "/url-name/",
data: $(this).serialize(),
dataType: 'json',
success: function(data) {
alert("success");
},
error: function(data) {
alert("Failure");
}
})
}
e.preventDefault() prevents the natural/default action, and prevents from submitting the form twice.
.serialize(), serializes the form data in a json format.
append a "/" before and after your action url.
Your view must return a dictionary as ajax deals with JSON format.
Edit your view like this:
if request.method == "POST":
currentSetting = models.UserSetting.objects.filter(isCurrent=True)
if currentSetting.serialPort:
print("GOT IT!")
a = {'data':'success'}
return HttpResponse(json.dumps(a))
This will return a dictionary required by the ajax.

Ajax POST with csrfmiddlewaretoken and csrftoken cookie set still gets django 403 Forbidden

I've read that both the csrfmiddlewaretoken and the csrftoken cookie have to be the correct value for a django POST request to succeed (django: csrftoken COOKIE vs. csrfmiddlewaretoken HTML Form value). This is the case for me yet I still get a 403:
In the chrome console:
document.cookie
returns
"csrftoken=Wt9eeJop5Vb3OmeNTvogegckm1pVM5MD"
but
$.get('https://learningdollars.fwd.wf/csrftoken/', function(data){
console.log(data)
token = $.parseHTML(data)[0].value
console.log(token)
$.ajax({
type: "POST",
url: 'https://learningdollars.fwd.wf/confirmemail/',
data: {email: 'gdasu#alumni.stanford.edu', csrfmiddlewaretoken: token},
contentType: "application/json"
})
.done(function(response) {
console.log('done!')
})
.fail(function(error) {
console.log('fail!')
})
})
returns
> Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
> <input type='hidden' name='csrfmiddlewaretoken' value='Wt9eeJop5Vb3OmeNTvogegckm1pVM5MD' />
> Wt9eeJop5Vb3OmeNTvogegckm1pVM5MD
> POST https://learningdollars.fwd.wf/confirmemail/ 403 (Forbidden)
> fail!
I have
'django.middleware.csrf.CsrfViewMiddleware',
activated in my django middleware.
My root urls.py contains:
url(r'^csrftoken/$', views.get_csrf_token),
url(r'^confirmemail/$', views.confirm_email, name='confirm_email'),
And, my views are:
def get_csrf_token(request):
c = {}
c.update(csrf(request))
print c
return render_to_response('csrf.html', c)
def confirm_email(request):
print 'here'
return JsonResponse({'response': 0})
And by the way, the contents of csrf.html are just the csrftoken (inside an input tag):
{% csrf_token %}
What am I doing wrong?
Well, I found a solution. It was just sending in the data as a URI rather than as json. (I by the way tried specifying dataType: 'json' in the above to no avail.) The following is in the chrome console:
> email = 'gdasu#alumni.stanford.edu'
< "gdasu#alumni.stanford.edu"
> csrftoken = 'L2MxD1XQIF1Xto5NkzUgGUYiHPyyz3K5'
< "L2MxD1XQIF1Xto5NkzUgGUYiHPyyz3K5"
> $.ajax({
type: "POST",
url: 'https://learningdollars.fwd.wf/confirmemail/',
data: "email="+ encodeURI(email) + "&csrfmiddlewaretoken=" + encodeURI(csrftoken),
success: function(data) { console.log(data); }
})
< Object {response: 1}
Still unsure what I was doing wrong on the json side, but the following is what I tried:
$.ajax({
type: "POST",
url: "https://learningdollars.fwd.wf/confirmemail/",
data: JSON.stringify({ email: email, csrfmiddlewaretoken: csrftoken }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
You can forbid Django CSRF by adding csrf_exempt to tell the view not check csrf token.
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def get_csrf_token(request):
c = {}
c.update(csrf(request))
print c
return render_to_response('csrf.html', c)
#csrf_exempt
def confirm_email(request):
print 'here'
return JsonResponse({'response': 0})

Resources