I have been trapped in this on for many hours, wondering if you have could help me out or provide me some suggestion?
Long story short,
I have a asp.net web api application, In one of my page, I am trying to load some data from web api and add them into few dropdown lists.
Anyway, I use jQuery ajax when the page loads
$(document).ready(function () {
//Fires when page loads
LoadMachines();
LoadMachieGroups();
LoadPrinterServer();
LoadSavePreference();
});
Each of the functions does the similar job, for example
function LoadMachieGroups() {
console.log("Before group " + document.cookie);
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/api/Machine/MachineGroups",
//data: "{}",
success: function (response) {
OnMachinesGroupLoadSuccess(response);
}
});
console.log("after group " + document.cookie);
}
The issue is that, we the code runs to the third (LoadPrinterServer) and fourth function (LoadSavePreference). The request header passed the same cookies (DoxMachineId) with different values three times. (Please see the picture), which then cause the trouble in my c# code to find the correct result.
My questions are:
1.) Why could same cookie added in the header multiple times? Is this because of multiple ajax calls?
2.) How to solve the problem? For example: remove the cookies?
Thanks guys in advanced.
Since I stumbled over the same (or pretty similar) problem and could not find a solution elsewhere, here comes my self-found-after-severe-frustration-solution:
When I sent the set-cookie header to the client, I missed to set its path argument to / (the root) on the server side. The client interpreted this as to set the path of the cookie to the parent of the leaf of its current target-path. In my case, that meant /api (since it has been an ajax-call to /api/create).
So, the client ended up with storing one instance of the cookie per path (in my case, for each api-call, there was an instance of the cookie stored at the client-side, as well as one cookie for the root-path that has been set by loading resources).
Whenever the client sent a request to the server later on, it attached all of the cookie-instances (with their respective values) to this request that matched the current target-path (again, in my case, whenever the client requested /api/create it attached the cookie-instance of the path / as well as the instance of the path /api which means the same cookie with two different values).
Related
I have a function called 'delete' like this :
<div onclick="delete($post_id, $_SESSION['id']">somelink</div>
function delete(post_id, session_id) {
var p_id = post_id;
var s_id = session_d;
$.ajax({
url:"delete.php",
type:"POST",
data: {
p_id: p_id,
s_id: s_id
},
});
})
delete.php is a page to delete the post = p_id which was added from user id = s_id.
My problem is any user can delete any post for only the console when typing in it the function 'delete();' with parameters it called and delete posts!
Any ideas, please.
You can not. Nor should you.
You should always assume that data from the client side is corrupted and should be treated accordingly. That includes form data, or in this case, a AJAX request.
This means that you have to apply validation at the server side, let PHP do it for you. E.g.: Limit the number of posts you can delete per X time. And double check that the post actually belongs to the person who is deleting it.
The reason you can't do this, is because you create javascript which is clientside. If you create a function to prevent changing the code, the client can alter the code on their machine to ignore that. You could make a function to check of the function to check is changed, but again; client can change it.
Unfortunately you can't. What you need to make sure though is making the function safe on the server which, in simple terms, boils down to
Validating every request and input parameters on the server so that people won't be able to manipulate or change server side data from client side.
make sure all data that you send to the client is originated from server as well.
one of the ways to prevent calling a function from client side is NOT to expose your methods in the global scope. and remember if your code is very critical and important, always move it to server-side. it is not a good practice to cover application design issues with programming workarounds. calling functions from client side shouldn't be an issue if the program is designed right.
First of all, this is bad. You should have authentication.
However, you can do that:
(function() {
$('#BUTTON_ID').on('click', function(post_id, session_id) {
var p_id = post_id;
var s_id = session_d;
$.ajax({
url:"delete.php",
type:"POST",
data: {
p_id: p_id,
s_id: s_id
},
});
})
})();
And add "BUTTON_ID" as id for your button.
Not that even that way, it is still not secure.
With this way, you can't call delete from the console. But someone can look into the source code and copy your ajax call and paste it into his console and it will works. It is not a good way to prevent people deleting your posts.
You should read about web application security. You should have an authentication process with tokens that expires after x time. Tokens will authenticate the user and from here, you can check if the user have the right to delete post. If the user do not have the right, you don't show the button. Then if the user call it from it console, he will get an error from the backend server.
DISCLAIMER: This question is a question about question. So that makes this question a meta question. It does not have any connection to the previously asked questions. If you find any resemblance, lemme tell you one thing- it's purely coincidental.
I want to make an AJAX request from my web page. I have been trying to do this, but none of the methods worked perfectly. The only post that I found something close to reality is this.
I tried various other methods from SO & other similar sites, but all of those posts said only one thing to me.
"No 'Access-Control-Allow-Origin' header is present on the requested resource."
I know now you are gonna mark this question as duplicate since there are loads of questions similar to this. Now..Lemme tell ya' one thing. I tried every piece of sh*t I found in SO, but none of 'em gave me the result that I was looking for. It's not because they all are wrong. It because I ain't got no knowlegde on how to use 'em. Then finally...I settled on the link I provided above. It's easy..but I need to know certain things about the code.This is the first time I am hearing the beautifully sodding acronym- CORS. So, if anyone can help me understand the questions I raise, Up votes for all of ya'. I wanna resolve this son-of-a-b*tch question before I celebrate my birthday for the third time this year. I will tell ya' what all I have-in form of resources & questions.
1) A rotten server located at Elizabeth town.
2) I need to access it.
3) I am planning to make a HTTP GET request.
4) I have a url. (eg. http://whereismyweed.com)
5) I store it into a JavaScript variable. var stoner='http://whereismyweed.com'
6) I have a HTML div tag in my webpage. (<div id="myprecious"></div>)
7) I wanna display the response I get from the server inside of 'myprecious' div.
8) And last but not the least... my AJAX function. (Courtesy: some website I visited)
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
What is 'myData'?? What does it contain. How can I get the response for this request? What is 'setHeader'?? Does it have any significance??? How can I display the response inside myprecious div? What changes should I make in the function? Is this function correct?
Too many question, Right???? Well...I need only one common answer for it?
Your function is correct.Follow below steps do achieve your goal-
//for getting response modify your code like
success:function(response){
alert(response);
$('#myprecious').html(response); //myprecious is id of div
}
// myData variable is jSon object which contains request parameter has to send.Eg.
var myData = {'first_name':'Foo','last_name':'Bar'} // now on server first_name and last_name treated as request parameter.
// If server not required any special headers to validate request 'setHeader' does not require. by default $.ajax will take care of it. you can remove it.
/// final code looks like
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function(response ) { $('#myprecious').html(response);
},
error: function() { alert('Failed!'); }
});
Thanks in advance for any help.
Is it bad practice and/or inefficient to use multiple $.ajax calls in one javascript function? I've been working on one and have a simple testing environment set up on my computer (apache server with php/mysql), and I've noticed that the server will crash (and restart) if I have multiple ajax calls.
I have two ajax calls currently: one passes 4 pieces of data to the php file and returns about 3 lines of code (pulling info from my sql database), the other simply gets the total rows from the table I'm working with and assigns that number to a javascript variable.
Is it just that my basic testing setup is too weak, or am I doing something wrong? See below for the two ajax calls I'm using:
$.ajax({
type: "GET",
url: "myURLhere.php",
cache: false,
data: {img : imageNumber, cap : imageNumber, width : dWidth, height : dHeight},
})
.done(function(htmlpic) {
$("#leftOne").html(htmlpic);
});
$.ajax({
type: "GET",
url: "myotherURLhere.php",
cache: false,
success: function(data) {
lastImage = data
}
})
Short answer: two ajax request on a page is absolutely fine.
Longer answer:
You have to find the balance between minimalising the number of ajax calls to the backend reducing the traffic and communication overhead; and still maintaining a maintainable architecture (so do not pass dozens of parameters in one call to retrieve everything - maybe only if you do it in a well designed way to collect every parameter to send)
Also most likely there's something wrong with your backend setup, try looking into webserver logs
On one of my pages I have "tracking.php" that makes a request to another server, and if tracking is sucessful in Firebug Net panel I see the response trackingFinished();
Is there an easy way (built-in function) to accomplish something like this:
If ("tracking.php" responded "trackingFinished();") { *redirect*... }
Javascript? PHP? Anything?
The thing is, this "tracking.php" also creates browser and flash cookies (and then responds with trackingfinished(); when they're created). I had a JS that did something like this:
If ("MyCookie" is created) { *redirect*... }
It worked, but if you had MyCookie in your browser from before, it just redirected before "track.php" had the time to create new cookies, so old cookies didn't get overwritten (which I'm trying to accomplish) before the redirection...
The solution I have in mind is to redirect after trackingFinished(); was responded...
I think the better form in javascript to make request from one page to another, without leaving the first is with the ajax method, and this one jQuery make it so easy, you only have to use the ajax function, and pass a little parameters:
$.post(url, {parameter1: parameter1value, param2: param2value})
And you can concatenate some actions:
$.post().done(function(){}).fail(function(){})
And isntead of the ajax, you can use the $.post that is more easy, and use the done and fail method to evaluate the succes of the information recived
As mentioned above, AJAX is the best way to communicate between pages like this. Here's an example of an AJAX request to your track.php page. It uses the success function to see if track.php returned 'trackingFinished();'. If it did then it redirects the page 'redirect.php':
$.ajax({
url: "track.php",
dataType: "text",
success: function(data){
if(data === 'trackingFinished();'){
document.location = 'redirect.php';
}
}
});
The example uses JQuery.
Environment:
Windows 8
Apache 2.4
ZF 1.12
PHP 5.4
YUI framework for the behind-the-scenes connection to the server
I am trying to carry out a very simple ajax/js combination where the user interacts with:
2 of 4 people found this review helpful. Was this review helpful to you? Yes No
When the user hits either yes/no the 2 of 4 should be updated through ajax/js. I have the following code in the init() method of my ReviewController (extends Zend_Controller_Action). Mind you, the view script that follows this action (feedbackAction) is /views/scripts/review/feedback.json.phtml
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('feedback', 'json')
->initContext();
When feedbackAction is executed an exception jumps out stating that it could not find feedback.phtml. This is telling me that AjaxContext is not, in effect, appending the "json" format. Why is this happening?
I read somewhere that the initContext() should be called inside the action. I tried it...same exception.
Then I tried using ContextSwitch, but it seems that it beats the purpose of having AjaxContext be a subclass of ContextSwitch. The code in the init() in ReviewController was replaced by:
$contextSwitch = $this->_helper->getHelper('contextSwitch');
$contextSwitch->addActionContext('feedback', 'json')
->initContext();
This time, inexplicably, the exception does not occur, but instead the following is rendered: the header code (generated by my _header.phtml file called by my layout.phtml file). I don´t understand at all. I had understood (obviously not well) that "addActionContext"+initContext() DISABLED layouts if any was enabled. ¿?
EDIT
I figured out that it wasn´t html content form my _header.phtml file but from another .phtml file that was being rendered because of some actions I had added to my actionStack. Once this was taken care of, what was rendered was the following:
{"originalModule":"default","originalController":"review","originalAction":"feedback","result":true,"id":1,"helpful_yes":"3","helpful_total":"4"}
Which is the variables placed in the $this->view being rendered as json thanks to ContextSwitch helper initiated at the init() method of my ReviewController(). When I say "this was rendred" is because I placed in the address bar the following url: http://localhost/PlacesforKids/public/review/feedback/format/json/id/1/helpful/1
which supposedly is the URL being sent by the YUI framework.
I say "supposedly" because in my javascript success function (being called back by the YUI framework when the ajax call is being executed successfully) I do the fowlling: alert(response), to print out the responce I am getting...and it prints out the whole shabang: html tags, headers...etc. I don´t know how that´s possible.
I thought then that I might be misusing the YUI framework, so I tried to change to jquery.js. To do so I copied the contect of this to a file named jquery.js and placed it under my /public/js directory. Here is the ajax call it´s making to the server:
$.ajax({
url: sUrl,//that would be
//localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
type: "GET",
async: false,
success: function(response){
alert(response);
}
});
Here is the HILARIOUS part of all, the action for my ReviewController is NOT being called whatsoever. Instead, the view that was last rendered is re-rendered, meaning it´s re sending the content generated by the view script called by the last action (which belongs to a different controller than ReviewController). I know it´s been re-rendered because in the action that´s the owner of that view script I added this:
if($this->getRequest()->getQuery('ajax') == 1)
throw new Exception ("WRONG controller's action being called");
But it never throws the exception.
EDIT I THINK I GOT IT but I need to know how to clean the baseUrl()
So I opened up the java console on my chrome browser so I could look up the actual http request that my reviewFeedback.js was making through the $.ajax() method. Funny thing, this is what I got:
Request URL:http://localhost/PlacesforKids/public/place/index/id/localhost/PlaceforKids/public/review/feedback/format/json/id/1/helpful/0
Request Method:GET
Status Code:200 OK
Accept:*/*
Referer:http://localhost/PlacesforKids/public/place/index/id/1
X-Requested-With:XMLHttpRequest
WHY in the world is $ajax() APPENDING the url I have as GET to the EXISTING url? It means that whatever url I am trying to generate through my $.ajax() is gettign APPENDED to my "referer". So, I only need to be to CLEAN it and start from zero, for the url I mean... How could I do that in zend framework? Any ideas?
Now if I enter the string in sUrl (localhost/PlaceforKids/public/review/feedback/format/json/id/1/helpful/0) directly onto the address bar in my broswer, it does as it is supposed to do, print out the variables in $this->view that have been set by ReviewController, and send them as json.
{"originalModule":"default","originalController":"review","originalAction":"feedback","result":true,"id":1,"helpful_yes":"3","helpful_total":"4"}
Same problem I had with YUI framework. I´m going crazy.
I could really use the help, thank you.
You need to change the ajax request to asynchronous mode: async: true
Silly silly silly me. Here is the reason why $.ajax() was appending the made up url instead of sending a new one.
$.ajax({
url: sUrl,//that would be
//localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
type: "GET",
async: false,
success: function(response){
alert(response);
}
I was writing a GET without a leading "http://", which by default, caused it to append to the existing url.
sUrl was localhost/PlacesforKids/public/review/feedback/format/json/id/$id/helpful/$helpful
and should have been http://localhost/PlacesforKids/public...
Though it still baffles me that ajaxContext did not stop layout rendering as it should have, making me use switchContext instead.
The ajax switch in zend 1.1x.x is only for the "special" html context (if memory serves) and you were trying to set it to a json context.