again, I got another problem with casperjs, now with sendAJAX function.
It says that sendAJAX has 5 parameters which are these followings :
url: The url to request.
method: The HTTP method (default: GET).
data: Request parameters (default: null).
async: Flag for an asynchroneous request? (default: false)
settings: Other settings when perform the AJAX request (default:
null)
So, it says the data method is object so, it should be filled with :
var data = new Object();
data.amount= 15;
and also with this one,
var data = {amount:15};
but there were no successful value send to my web service (always send 0 as value, but ajax request successful, even returning the json data) which has an url like this
"http://localhost:9000/TempCountryAmountREST/setCountryAmount"
It will be succeed if I direct bind my data variable to my url like this :
"http://localhost:9000/TempCountryAmountREST/setCountryAmount?amount="+amount
[UPDATE]
The TempCountryAmountREST is my controller name and setCountryAmount is my function inside my controller.
[UPDATE]
I forgot to include my usage of sendAJAX(), here is the code that I use :
return JSON.parse(__utils__.sendAJAX(wsurl, "POST" , data, false, { contentType: "application/json" }));
So how does I fill the data in the sendAJAX parameter?
Thanks in advance...
Sorry, I've found what the answer is.
I make some mistakes in contentType which I was set with contentType: "application/json" instead of contentType: "application/x-www-form-urlencoded" }
If we are looking about how ajax send the content from method send(), they were use x-www-form-urlencoded. See this for more detail
When we see through casperjs clientutils.js script, we should found how sendAJAX work.
On the `this.sendAJAX = function sendAJAX(url, method, data, async, settings) {
}
there are url construction logic which transformed our Object (if so) to x-www-form-urlencoded form. So that we need to set our contentType as application/x-www-form-urlencoded
Very well, thanks for your attention...
Related
I use Vuejs to create my frontend for my project.
At the creation of one component ('TimeCapsy.vue'), I make an AJAX call to my backend like this:
created: function () {
if (verify.verify_login()) {
let token = this.$cookies.get('jwt_us_cas');
let params = {'jwt': token};
console.log(params);
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
params: queryString.stringify(params)
})
.then(response => {
console.log(response.data)
})
}
}
As you can see I use the
this.$cookies.get('jwt_us_cas');
to get the a json web token, that I set on the client at the login.
I use the queryString Library to stringify my parameters for my request.
I also tried it without the queryString.stringify(params) call, but I get the same error, e.g. the parameter still turns into null.
When I look at the console log, where I check the params variable, I get this output:
{jwt: "my token comes here"}
So I can see, that it gets the correct value from the cookie.
But when I check the answer from my backend (PHP), I get this error:
Undefined index: jwt in <b>D:\casb\public\index.php</b> on line <b>52</b>
Of course I know that it means, that jwt is null, but I can't understand why.
As I said, right before I make the call I check the params and it shows the token.
I checked the endpoint with Postman and the token as the jwt parameter and it returned a successfull call with the correct answer.
A correct answer is basically just a nested object with some information in it.
My PHP endpoint is pretty basic too:
Router::add('/getuserinfoobject', function () {
$response['response'] = User::getUserInfoObject($_POST['jwt']);
echo json_encode($response);
}, 'post');
So I guess that right before or in my call it nulls my parameter. But I can't understand how, since I make a lot of requests and never had this problem.
From axios docs
params are the URL parameters to be sent with the request
Which means, you should get the value with PHP $_GET.
Or $_REQUEST (which stores both $_GET, $_POST. Also $_COOKIE).
The other hand, you can use data key as docs says
data is the data to be sent as the request body
Only applicable for request methods PUT, POST, and PATCH
So the value would be available in $_POST
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
data: {
jwt: token
}
})
Is it possible to enable date field in to http requests? I have an object on my client side:
let init = {
method: typeof method === 'string' ? method : 'GET',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Accept': 'application/json',
'Accept-Language': getLanguage()
}
The problem is I adding 'Date' : new Date() to the header server doesn't get any key-value pair (via WebApi). Also in network section of browser there is no above field. I've read some information this field is closed for any manipulation. As I understand I need to enable it for including not by hands. So, how can I tell to browser to send it?
Unfortunately, that's not possible once the browser is supposed to set the header, not you. If you were able to set the header, that would defeat the purpose of the security feature.
Also, if you try to force it you'll probably get the error:
Refused to set unsafe header "Date"
Once we try the request without setting this header, we'll see that the browser doesn't set it for you (only for response object, which is easier to manipulate).
Some alternatives:
Create custom headers and receive their values at the WebApi
Or even pass the value as a parameter (body POST, e.g)
I'm trying to process the response headers but not sure how to query for them. Here's the code snippet. I commented out a couple of lines when I attempted to read the headers and put some comments on what I noticed.
$http({
method: 'POST',
url: URL,
data: $.param(data),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function (data,status,headers) {
//Need to process the header to understand the server response
//console.log(headers()); //This returns null
//console.log(headers('custom-myapp-text');// Obvisouls returns null as the headers() returns null
deferred.resolve();
});
return deferred.promise;
};
As per their documentation, the 'headers' returns a function?? Not sure how to query for header values based on this.
data – {string|Object} – The response body transformed with the
transform functions.
status – {number} – HTTP status code of the response.
**headers – {function([headerName])} – Header getter function.**
config – {Object} – The configuration object that was used to generate the request.
statusText – {string} – HTTP status text of the response.
I just tried it with a valid header and it was fine:
console.log(headers('Content-Length'));
This console logged 2 in my example. It will allow you access to any of the valid response headers.
I am new to Django.I am sending a ajax POST request to a python function which in turn stores the data in the variables from the ajax and return the HttpResponse .So i checked request.method in python its coming as GET.
$.ajax({
url:"create_post/",
type:"POST",
data : {F_Name: First_Name ,L_Name: Last_name,Eadd: Email , Password: Pass},
success:function(){
window.location.href="create_post/";
console.log ("Success")
},
cache:false,
failure: function(errMsg) {
alert(errMsg);
}
});
this is my ajax request.
its sending the data to this function .
def create_post(request):
if request.method == 'GET':
First_name=request.GET['F_Name'];
Last_Name=request.GET["L_Name"];
Email_address=request.GET["Eadd"];
Pass=request.GET["Password"];
return HttpResponse("<html><body>hi this is me .</body></html>");
When I checked as return(request.method) its giving me GET.
Can some one explain this behavior?
And in the function i have request.method==GET in this scenario DJango is giving me internal server 500 error.
Thanks
I am surprised to see that none of you didn't noticed that he has define method: "POST" in his ajax and his function is used on "GET" request.
And the main reason he is getting the output for print request.method = "GET" and 500 error is because of using window.location.href="create_post/" in his ajax success function. Every request is by default a get request unless we explicitly define it "POST" or any other.
So here it goes like this,
- Ajax calls the url via POST, for unknown reason the response comes in success function(weird coz according to the view posted POST method return nothing to ajax request).
- The success function again calls the same url(page refresh) via a GET request and he sees print request.method as "GET" with 500 error coz this is wrong way to do so.
your ajax method is post, so i think your views.py may try this
def create_post(request):
if request.method == 'POST':
First_name=request.POST['F_Name']
Last_Name=request.POST["L_Name"]
Email_address=request.POST["Eadd"]
Pass=request.POST["Password"]
return HttpResponse("<html><body>hi this is me .</body></html>")
Here is a very simple example of a call to Twitter's search API to get all tweets from a tag known to have tweets, #fml.
I believe I am correctly using the application-only authentication as explained here: https://dev.twitter.com/docs/auth/application-only-auth (see Step 3 for example of a call)
I am being asked for a solution that does not involve any server-side code so I am including the bearer code in the javascript, which isn't good to begin with, but....
I would expect this code to work. Instead it produces the error '400 (Bad Request)'. Any ideas?
$.ajax({
url: "https://api.twitter.com/1.1/search/tweets.json",
dataType: "jsonp",
data: "q=%23fml",
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Bearer XXmyBearerCodeXX");
},
success: function(json){ alert(json); }
});
EDIT 1 - Validated Twitter call
Using hurl.eu I was able to get a successful response from the API with the above query and Authorization header, so I assume this means my Twitter call is correct, just not set up correctly within jQuery.ajax(), but I just don't see what is missing.
You cannot set request headers using AJAX calls with dataType JSONP.
See this question: Set Headers with jQuery.ajax and JSONP?
The best solution is to use a server-side proxy to do the search for you. I know you are looking for a client only solution, but with this restriction, and with no way around CORS, this is how it seems to be done today for the Twitter API.
Edit It may be possible using a proxy like Yahoo's YQL if you don't have access to one.
on your severside create a jsp or servlet and from the client side make a JSON call to the .jsp/servlet and that will return back the json object to the javascript. In serverside use the twitter4j api.
sample code:
`
$.getJSON(http://localhost:8080/test.jsp?callback=?",
{
jspqueryStr : queryStr,
jspgeocodeStr : geocodeStr,
lat:latStr,
lan:lngStr,
radius:radiusStr,
}, displayResult);
//This function returns the data as json object from server.
function displayResult(data) {}
In the jsp the code is like below
<%
String jspqueryStr = request.getParameter("jspqueryStr");
String jspgeocodeStr = request.getParameter("jspgeocodeStr");
String diseasename = request.getParameter("jspqueryStr");
String lat = request.getParameter("lat");
String lan = request.getParameter("lan");
String radius = request.getParameter("radius");
Gson gson = new Gson();
String json = gson.toJson(tweetList);
json = request.getParameter("callback") + "(" + json + ");";
out.println(json);
public List<Status> searchstream(){
//here all the twitter4j api code to get the data
retrun tweetList;
}
%>
`