I've spent hours looking up this issue with no avail.
I am having issue with post data from an html page I am sending {'username': 'username'} but when I do request.POST.get('username') it returns none, I alos tried {username, 'username'}
def test_post(request):
if request.method == 'POST':
print(request.POST.get('username'))
return HttpResponse("Good!")
else:
return HttpResponse("Bad.")
Console Development Server
None <<<<
[12/Feb/2018 19:39:53] "POST /test_post HTTP/1.1" 200 5
(edited)
I am sending the data as {'username': 'username'}
That works correctly how come I am unable to get it to show up?
This is the Javascript code that calls from the page:
document.getElementById('submit').addEventListener('click', function(e) {
e.preventDefault();
var username = document.getElementById("username").value;
data = {username: username};
console.log(data);
var request = new XMLHttpRequest();
request.open('POST', '/getuser', true);
request.setRequestHeader('Content-Type', 'x-www-form-urlencoded');
request.send(data);
});
In the django view test_post, request.POST is a Query Dict (aka Dictionary).
When you use the method .get(key), it looks for the key in the dictionary and returns you the value corresponding to the key.
In the test_post method, you have written request.POST.get('username') which means the string 'username' as a key should be present in the POST dictionary.
When you do a POST using Javascript, and do data = {username: username}; you are essentially making the key dynamic.
Eg. when you input "Bob" in username and click on submit, the variable data
will be {'Bob': 'Bob'}
Instead you should do:
data = {'username': username} //This ensures that the key remains same
Related
My javascript code in my HTML template, test.html, in my /test route.
var p = (correct/5) * 100;
var score = {p: p};
fetch("http://127.0.0.1:5000/score", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(score)
})
.then (res => {
return res.json()
})
.then(console.log(score))
.catch(error => console.log('ERROR'))
As you can see from the code above, I am trying to send score to the /score route.
Below is my python code:
#app.route("/score", methods=["POST", "GET"])
def score():
if request.method == "POST":
data = request.get_json()
score = data['p']
return render_template("score.html", score=score)
return render_template("beforetest.html")
When I do print(score), it prints the correct value so that works fine. However, it doesn't pull up the score.html page, I'm guessing because it is not a GET request but I am not sure how to do both a POST and GET request in this situation.
Also, one other thing I noticed (not sure if this is related to this issue or not) is that in the /test route, when I open the console, in the first line it has the correct value of p as intended but on the next line it has "ERROR" (from the .catch method).
How can I return the render_template to pull up the page and why am I getting an error with the .catch method?
EDIT: The suggested link in the comment got rid of the console error, but it still doesn't pull up the page. I noticed that it had "1 hidden" in the top right and when I opened it, it had:
XHR finished loading: POST "http://127.0.0.1:5000/score" but it still doesn't pull up score.html
DellContact=(emailcontact) => {
let {xhttp}=this.DbConn('DELETE','.json?orderBy="email"&equalTo="' + emailcontact + '"');
xhttp.send();
}
DbConn (method, addon){
let xhttp = new XMLHttpRequest();
let url = "https://phonebook-496ff-default-rtdb.firebaseio.com/Contacts" + addon;
xhttp.open(method,url,true);
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
return {xhttp};
}
hello, im trying to delete the specific data from firebase by comparing the JSON value named "email" with the value emailcontact. i get a bad request 400. its something with the request syntax i think, because with GET/POST it works.
firebaseURL/Contact.json?orderBy="email"&equalTo="abc#gmail.com" <-- This is the request that sent
Any suggestions ?
Firebase Realtime Database doesn't support update or delete queries. To delete a node, you need to know its exact path.
So you'll need to:
Execute a GET for the query to determine the results.
Then loop over the results in your application code.
Execute a DELETE request for each individual result.
I want create API for contact form 7.
How to send data from front-end to Contact Form 7 using WP rest api?
I mean, what should the data structure be to send it via the POST method?
http://xx.xxx/wp-json/contact-form-7/v1/contact-forms/<id-form>/feedback
I trying different ways, but request always return response “validation_failed”, “One or more fields contain erroneous data. Please check them and try again.”
I did not find anything about this in the documentation.
Were you able to find the solution? I've been working with the Contact Form 7 REST API and there are a few things you need to do to be abled to get a 'success' response, instead of validation_failed.
First, you need to know what form fields you need to submit. This is set up in your CF7's contact form. The field's name is defined in contact form. Most likely, CF7 uses the naming structure your-name and your-email. So you will need to format your post body to match this.
Next, you will need to submit it using FormData() https://developer.mozilla.org/en-US/docs/Web/API/FormData. From personal experience, I found that if I send my request as a normal object by using post, CF7 sends back validation_failed.
Note: I am using Nuxt's http package to submit data, but you are able to use axios here.
// Format your body response
const emailBody = {
"your-name": this.form.name,
"your-email": this.form.email,
"your-message": this.form.message,
};
// Create a FormData object, and append each field to the object
const form = new FormData();
for (const field in emailBody) {
form.append(field, emailBody[field]);
}
// Submit your form body using axios, or any other way you would like
const response = await this.$http.post(this.getEndEndpoint, form);
This is working for me, I am no longer getting the status validation_failed. Instead I now get a spam status. Trying to solve this problem now
Good luck
add_filter( 'wpcf7_mail_components', 'show_cf7_request', 10, 3 );
function show_cf7_request( $components, $wpcf7_get_current_contact_form, $instance ) {
print_r($_REQUEST);
die();
return $components;
};
Don't try on LIVE ;)
// google recaptcha integration v3 with contact form 7 Rest API
let email = $('input.email').val();
let g_recaptcha_response = $('textarea.g-recaptcha-response').val();
let data = new FormData(form);
data.append("email", email);
data.append("_wpcf7_recaptcha_response", g_recaptcha_response);
// _wpcf7_recaptcha_response key is important and should be same
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/wp-json/contact-form-7/v1/contact-forms/783/feedback",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
}).then((data) => {alert(data.message);});
In Django, I tried using form.errors.as_json() to get all form errors and here is sample json data strings.
{"password2":[{"message": "This password is too short. It must
contain at least 8 characters.","code":"password_too_short"}]}
I wanted to loop and get all under "message" key in json so I can use it to notify the user after ajax call.
Thanks
Anyways, I just resolved my issue and just wanted to share what I did.
views.py
if form.is_valid():
...
else:
# Extract form.errors
errMsg= None
errMsg = [(k, v[0]) for k, v in form.errors.items()]
return JsonResponse(errMsg)
Ajax Event
$.ajax({
method: "POST",
url: '\your_url_here',
data: $form.serialize(),
cache: false,
dataType: "json",
beforeSend: function(){
//Start displaying button's working animation
//Do some button or loading animation here...
}
},
success: function(jResults)
{
//This line is to remove field name display
var strErr = jResults + ''; //make json object as string
strErr = strErr.split(",").pop();
alert(strErr);
}
});
Hope this help to anyone out there facing similar issue. By the way, I'm using Django 2.0 and Python 3.6+
Thanks
MinedBP
The correct answer should be:
return HttpReponse(form.errors.as_json(), status=400).
In the AJAX call you can get the content doing:
`$.post("{% url 'your_url'%}", your_payload).done(function(data) {
do_something();
}).fail(function(xhr){
// Here you can get the form's errors and iterate over them.
xhr.responseText();
});`
You are sending a 200 HTTP response, that it is wrong, you should return a 400 HTTP response (Bad request), like Django do without AJAX forms.
I am using Angular4 with TypeScript version 2.2.2
My web app is running fine when I call JSON with Filters but my NativeScript app fails when I call the Filter Values as an Object but works fine when I call filter values as a string.
Error Response with status: 200 for URL: null
THIS WORKS
https://domainname.com/api/v1/searchevents?token=057001a78b8a7e5f38aaf8a682c05c414de4eb20&filter=text&search=upcoming
If the filter value and search value is STRING it works whereas if they are objects as below, it does not work
THIS DOES NOT WORK
https://api.domainname.com/api/v1/searchevents?token=057001a78b8a7e5f38aaf8a682c05c414de4eb20&filter={"limit":"12","skip":"0"}&search={"search":"","latitude":"","longitude":"","categories":"","address":"","type":"upcoming"}
The Code I used is below
getData(serverUrl, type, skip_limit) {
console.log(serverUrl);
let headers = this.createRequestHeader();
let token_value = localStorage.getItem('access_token')
let url;
var filter;
filter = '{"limit":"10","skip":"0"}'
url = this.apiUrl + serverUrl + '?token=' + token_value + '&filter=' + filter
return this.http.get(url, { headers: headers })
.map(res => res.json());
}
The URL as formed above for the API is fine and works fine. Yet the error comes Error Response with status: 200 for URL: null
CAN ANYONE HELP ME SOLVE THIS?
Looks like the issue is the "filter" values are of different type and from what you mentioned as what worked, your service is expecting a string and not an object/array. So it fails to send the proper response when it gets one. With an object in the URL, you may have to rewrite the service to read it as an object (parse the two attributes and get them individually)
To make it simple, you can make these two as two different variables in the URL. like below,
https://api.domainName.in/api/v1/oauth/token?limit=10&skip=0
Be more precise in whats happening in your question,
1) Log the exact URL and post it in the question. No one can guess what goes in "text" in your first URL.
2) Your URL which you mentioned as worked have "token" as part of path, but in the code, its a variable which will have a dynamic value from "token_value".
3) Post your service code. Especially the signature and input parsing part.
Got the solution:
All you have to do is encode the Filter and Search Parameters if it is an Object or Array using Typescript encodeURI()
var filter = '{"limit":"12","skip":"0"}'
var search = '{"search":"","latitude":"","longitude":"","categories":"","address":"","type":"upcoming"}'
var encoded_filter = encodeURI(filter);
var encoded_search = encodeURI(search);
url = this.apiUrl+serverUrl+'?token='+token_value+'&filter='+encoded_filter+'&search='+encoded_search