Pass Cookie though Ajax Call or use $_COOKIE in PHP - javascript

Is there a specific reason why passing a cookie through an AJAX call would or would not have an impact on performance or maintaining code as opposed to simply calling $_COOKIE inside of PHP?
In this case, I use this plugin to get cookies in javascript: Cookie Plugin
Example of passing cookie through Ajax call:
$.ajax({
url: 'getCaseManagerReport.php',
method: 'POST',
dataType: 'json',
async: true,
data: {activeDateSelected: Cookies.get('activeDateSelected').replace(/[+]/g, " "), activeProductSelected: Cookies.get('activeProductSelected')}
})
.done(function(response) {
//do stuff
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("There was a problem during verification. Please contact your System Administrator...");
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
});
Then in getCaseManagerReport.php
$activeDateSelected = $_POST[‘activeDateSelected’];
VS using $_COOKIE to retrieve cookie
$activeDateSelected = $_COOKIE[‘activeDateSelected’];

Related

parse error callback function not called jquery ajax error?

I have been trying all the methods that i have seen in the stack overflow asked by other users before.But none of them are working.Please hoping any of you would point me in the right direction
$.ajax({
type: "get",
dataType:'jsonp',
params:jsonData,
jsonp:false,
jsonpCallback:"callbackfn",
headers: { "api_key": "u5FocU4xLq2rBfZ1ZSV8o81R2usYzUEM3NaCinnV"},
url: "http://localhost/url?name=xxx&email=xxxxxx#gmail.com",
success:function(){
alert("sucess function");
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + " and<br> " + errorThrown);
}
});
function callbackfn(data) {
alert(data);
}
the response is {
"firstName":"John",
"lastName":"Doe"
}
Although the response is json,this rises an error
Parse error .callbackfn not called.
In order to use a custom callback function with JSONP, you must declare its scope to be global, i.e.
window.callbackfn = function(data) {
alert(data);
};
Why?
This is because successful JSONP responses return a new JavaScript file, that is, a JavaScript function call encapsulated in <script> tags. Since each script is independently evaluated in the global scope, any script's function you would like to be made available to another script must also be declared in the global scope. Thus all JSONP callback functions should be global.
EDIT
According to OP, the solution found here: Return JSONP via AWS Lambda/API Gateway did the trick. Issue had to do with an improper server-side JSONP response.
Make sure that your response from the server is a function call with the response data as the argument. It appears you are just outputting JSON, but JSONP expects a function call with the response data. Your server response should look like this:
callbackfn({
"firstName":"John",
"lastName":"Doe"
});
You have jsonp: false with a jsonpCallback and dataType: 'jsonp' - which is odd, because you are also supplying a jsonp callback. Perhaps if you don't need JSONP due to cross-origin requests, you should remove the jsonpCallback argument and just manually call that function with the response:
$.ajax({
type: "get",
dataType:'json',
params:jsonData,
headers: { "api_key": "u5FocU4xLq2rBfZ1ZSV8o81R2usYzUEM3NaCinnV"},
url: "http://localhost/url?name=xxx&email=xxxxxx#gmail.com",
success:function(data){
callbackfn(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + " and<br> " + errorThrown);
}
});

Ajax jquery call to GET application/x-javascript

How do I get content of "application/x-javascript" using jquery Ajax call?
As it keep getting me null content.
What I am trying to use for now:
$.ajax({
dataType: "json",
contentType: "application/x-javascript;charset=utf-8",
url:the_url,
async:false,
success:function(r){
console.log("el result" + r) ;
response = r;
}
});
This:
dataType: "json",
tells jQuery to ignore what the server claims it is sending back and to process the result as JSON. JavaScript isn't JSON, so this breaks it.
Remove that line.
Then you should get the data in the success function.
Asides:
This:
contentType: "application/x-javascript;charset=utf-8",
claims you are sending JavaScript. You aren't making a POST request, so you aren't sending anything. Remove it.
Even if you were sending JavaScript to the server, the application/javascript MIME type hasn't been experimental since 2006, so it shouldn't have the x- prefix on it.
async:false, is a terrible idea. It locks up the JS event loop waiting for the response. You shouldn't use it.
response = r;: assigning data to globals is usually a terrible idea. Process the data in the success event handler instead.
Try this out :
$.ajax({
url: 'my/url',
type: 'GET',
data: 'test=mytest&test2=mytest2',
success: function (data) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
And read the documentation, to see what each parameter is made for :
http://api.jquery.com/jquery.ajax/

Ajax call to JSON service isn't working

I'll admit my exposure to JQuery / Ajax has been somewhat limited thus far, I am attempting to get JSON data from two web services:
http://w.xaviertidus.com/Json.svc/getInServiceTransponders
http://w.xaviertidus.com/Json.svc/latestTransponderUpdates
Using the following code:
function fetchTransponderData() {
$.ajax({
url: "http://w.xaviertidus.com/Json.svc/getInServiceTransponders",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (response) {
return response;
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
function fetchFarcsData() {
$.ajax({
url: "http://w.xaviertidus.com/Json.svc/latestTransponderUpdates",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (response) {
return response;
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
Unfortunately it keeps throwing an error (the alerts under 'error' in the ajax statement fire) and not giving me detail, i have used fiddler and it is making a request to the webservices and going to them myself yields expected JSON results.
Can anyone shed any light on this problem for me? Many thanks!
Could be a cross domain request. If so you must set the appropriate header (Access-Control-Allow-Origin: *) or use a proxy server.
You can try using JSONP to get around the same origin policy. However, a better option would probably be to call the external site from your server side code and rely on your server to forward that result back to your client.

How do i read simple json result with jquery and how to post new

I built a WCF service which produces JSON. I want to make an external website which uses this webservice. For now I am executing the WCF service over LAN by IIS, so I can connect to the service by going to http://myownaddress/blabla.svc/
I tried to learn some json and to get some results from my service.
For example if I want to use this method:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "json/{id}")]
string JSONData(string id);
I'll go to http://myownaddress/blabla.svc/json/123
And as result I get:
{"JSONDataResult":"You requested product 123"}
Now I have tried to receive this result with the JQuery statement getJSON. But I don't see any results.
My question is how can I get this simple data?
And secondly how can I post data(with javascript) back on to the wcf service is it also possible with json?
-edit-:
I have now updated my code and put this into my document ready function which is located between the <head> <script> .... on my page:
$.getJSON(
'http://myownaddress/blabla.svc',
function(data)
{
alert(data.JSONDataResult);
});
But this won't give the alert with the result. It doesn't even give an alert.. Besides that, in the function I need to give a parameter of id, so for example 123 (look in text above) don't I need to put that in the function also?
To get data use getJSON():
$.getJSON(
'http://myownaddress/blabla.svc/',
function(data) {
alert(data.JSONDataResult);
}
);
To post data you can use this:
$.post('http://myownaddress/postservice.svc', function(data) {
$('.result').html(data);
});
or this (if you need more control):
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
You can also use the ajax for getting the data instead of the getJSON method .
UPDATE:
try using ajax method as it gives you more control:
$.ajax({
type: 'GET',
url: "http://myownaddress/blabla.svc/json/123",
success: function(data){alert(data)},
dataType: "json",
complete: function(data){alert(data)},
error: function(jqXHR, textStatus, errorThrown){alert(errorThrown)}
});
Also, if you use firefox, check out firebug extension, it will help you greatly.
If you use chrome then use chrome developer tools.
In order for your to get the json data from a WCF service that is outside your website using Jquery you need to use JSONP.
You can perform the call as shown below:
$.ajax({
url: "http://myownaddress/blabla.svc/",
dataType: "jsonp",
type: "GET",
timeout: 10000,
data: null,
jsonpCallback: "MyCallback",
success: function (data, textStatus, jqXHR) {
alert(action.toLowerCase());
},
error: function (jqXHR, textStatus, errorThrown) {alert('error is:' + errorThrown);
},
complete: function (jqXHR, textStatus) {alert('complete');
}
});
JSONP is used when you want to perform a cross domain calls using Javascript.
Also your WCF service should be compatible to handle JSONP calls by injecting the results to the response stream using the callBack method specified in the URL.
Do you have your code like this ?
$.getJSON(
'http://myownaddress/blabla.svc/',
function(result) {
alert(result.JSONDataResult);
}
);
Remember getJSON will not immediately return you the data, you have to make use of the result in a callback function.
Why did you change your url?
$.getJSON(
'h t t p://myownaddress/blabla.svc' ==> 'h t t p://myownaddress/blabla.svc/123',
function(data)
{
alert(data.JSONDataResult);
});

Post form data created by an ajax call to a remote url

I would like to perform a two stage post. The first is an AJAX post to my own service that creates form data such as "email=blah&dude=car" etc.
In the callback for the AJAX call I need to repost that data to a remote site, in a normal post.
I was thinking something like:
var formData = "some form data";
$.ajax({
type: 'POST',
url: '/myservice',
data: formData,
success: function(data, status) {
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","http://remotepage.com",true);
xmlhttp.send(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//display error message },
dataType: "text",
});
However, the httpRequest will fail due to XSS prevention on remotepage.com. How can I easily repost the processed form data to the remote URL?
You realize that due to same origin policy restrictions sending an AJAX request to http://remotepage.com (xmlhttp.open("POST","http://remotepage.com",true);) wouldn't work unless your site is hosted on http://remotepage.com.
So to achieve this you would need to setup a server side script on your domain which would act as bridge between your domain and the remote domain and you would then send an AJAX request to your script. Also because you are using jquery it would seem more natural to use it in the success callback as well:
var formData = "some form data";
$.ajax({
type: 'POST',
url: '/myservice',
data: formData,
success: function(data, status) {
$.post('/some_bridge_script', formData);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//display error message },
dataType: "text",
});
If the remote domain supports JSONP you could directly send the request to it but it is only limited to GET requests.
You need to send a background GET request to remotepage.com asking for the form for the resource you want to modify/create. This will allow remotepage to set authenticity tokens in your cookie store. Keep this form hidden, populate it with data that was successfully posted to myservice, and post the hidden form. This way remotepage.com will have a chance to check that you are trusted.
EDIT: added code samples
Here's a bit of sample code on what I'm envisioning:
var formData = "some form data";
$.post({
url: '/myservice',
data: formData,
success: postToRemote,
dataType: "JSON",
error: function(XMLHttpRequest, textStatus, errorThrown) {
// display error message
},
});
So instead of returning text, myservice should return a json object containing the processed data you talk about in your comment below. The callback will request the form you want from remotepage. Once its done loading, the block in the anonymous function() will be executed, which populates the form, then submits it.
function postToRemote(data, status) {
$("#empty_container_for_form").load("http://remotepage.com/get_hidden_form", function() {
$("#hidden_form input#attribute_1").val(data.attribute1);
$("#hidden_form input#attribute_2").val(data.attribute2);
$.post({
url: "http://remotepage.com",
data: $("#hiddenForm").serialize()
});
});
}
Also, make sure the form is hidden using css:
#empty_container_for_form { display: none; }

Categories

Resources