How to send XMLHttpRequest to specific php function? - javascript

I am trying to do a image uploading with ajax. I have run into a bit of problem. I have two functions in func-ajax.php : function doSth(){} and function doSthElse(){}. I want to target the doSth() function
This is my javascript side:
var xhr = new XMLHttpRequest();
xhr.open("POST", 'func-ajax.php', true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
How can I specify whick function to send the request?

You cannot run a specific function from the func-ajax.php file.
What you should do is create something like ajax-controller.php, containing
$functionName = $_POST["func"]; // func parameter should be sent in AJAX, determines which function to run
if (function_exists($functionName)) { // check if function exists
$functionName(); // run function
}
And send all requests from JS to this file xhr.open("POST", 'ajax-controller.php', true);
Hope you get the idea.

You want to send GET/POST parameters along with your request, and catch those in the PHP script.

You can't send an HTTP request to a function.
You make a request for a resource. That request can include POST data and it can include HTTP headers.
The server then decides how to respond the request. It might choose to run a PHP program.
It is up to the PHP program to look at the requested resource / POST data / headers and determine which function(s) to run.

You can add a parameter in the data being sent and that you check for in some sort of if block that you call the function manually from. You could also introduce a framework like Slim, to create an REST-api point that you can hit.

Related

Can't send large json data via XMLHttpRequest - javascript

I need to pass a json variable as a paramater to a php script that will process the json data and store it in Database.
So first, in javascript, i was testing sending data like this :
$('#sendResult').load('http://localhost/myurl/phpFile.php?mrData=' + jsonArrFinal);
This was working well when passing small records (records can vary, it depends the data that user insert).
But when i increased the records, it started appearing this error in console:
414 (Request-URI Too Long)
I've changed the js code to:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost/myurl/phpFile.php?mrData=' + jsonArrFinal );
xhr.setRequestHeader("Content-type", "application/json; charset=utf-8");
xhr.send();
But still appearing the same error with POST method.
I've checked the json param and it has 5439 characters.
How can i resolve this? Thanks in advance.
Please note that the length can be 8x more than 5439 characters.
Don't use a GET request.
You're storing data, so you should be using a POST request anyway.
Use $.post instead of $.load and write your own logic to display the response in the done() handler.
I've changed the js code to:
You need to put the data in the body of the request. POST requests don't change the rules for how much data you can put in the URL.
$.post("http://localhost/myurl/phpFile.php", { mrData: jsonArrFinal })
.done( data => $("#sendResult").html(data) );

XMLHttpRequest() JSON throws a network error but similar jQuery .getJSON code works

I have a JSON script loaded from an external website. In its simplest form, the code has been like this (and working):
jQuery.getJSON("http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?",
function(data){
document.querySelector("output").textContent = data.postal_codes[0].city;
});
However, the website owner don't want jQuery if it's not crucial, so I recoded .getJSON to the request = new XMLHttpRequest(); model:
request = new XMLHttpRequest();
request.open("GET", "http://adressesok.posten.no/api/v1/postal_codes.json?postal_code=" + document.querySelector("input").value + "&callback=?", true);
request.onload = function() {
var data = JSON.parse(request.responseText);
document.querySelector("output").textContent = data.postal_codes[0].city;
};
request.onerror = function() { /* this gets called every time */ };
I've modified my code many times, read documentations over and over again, yet the .onerror function is the only one always displaying. This is the console:
Which in Norwegian says that this script requested CORS, that it can't find the origin in the head of Access-Control-Allow-Origin, and that the XMLHttpRequest had a network error, and says "no access".
There could be several reasons as to why this occurs:
1: There's something wrong with the new code
2: There's something in the .getJSON jQuery function (a hack?) that prevents the error from happening
3: There's something crucial in the new code that I have forgot adding
4: There's something with my browser (IE 11 at the moment)
5: Something else?
It would be lovely with some help on this.
DEMO: http://jsbin.com/muxigulegi/1/
That isn't a network error. It's a cross origin error. The request is successful but the browser is denying access to the response to your JavaScript.
Since you have callback=? in the URL, jQuery will generate a JSONP request instead of an XMLHttpRequest request. This executes the response as a script instead of reading the raw data.
You are manually creating an XMLHttpRequest, so it fails due to the Same Origin Policy.
Create a JSONP request instead.
From http://api.jquery.com/jquery.getjson/:
JSONP
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
You do have a callback. Which means that the JQuery function can request data from another domain, unlike your XHR call.

getjson - not returning object to console

I am trying to retrieve a json feed every 1 second. The URL that I am trying to retrieve displays JSON in the browser but will not be retrieved via a jquery getJSON
http://www.ridestreamline.com/Services/JSONPRelay.svc/GetMapVehiclePoints
function getBusLoc() {
$.getJSON('http://www.ridestreamline.com/Services/JSONPRelay.svc/GetMapVehiclePoints?callback=?', function(data) {
console.log(data);
setTimeout(getBusLoc, 1000);
})
}
getBusLoc()
It has something to do with the above link. What am I missing? Fiddle here
This is because of same origin policy, you can't sent ajax request from host A to host B, you can use jsonp instead (if your service supports this) , or if you has control to server side and you don't mind to old browsers you can use x-access-control-allow-origin http header in response to OPTIONS request (more info here https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS)

Make an ajax POST request to a server through ajax/jQuery

I am trying to send a post request through ajax to another domain and get a json response. The server is situated in my company premise and through the logs, I can see that it is sending response with a json.
Following is a sample of my tries:
1)
function makeRequest(strURL){
$.get(strURL+"?callback=rest.draw_table_dyn", "{}",
function(resp){
rest.draw_table_dyn(resp);
});
}
2)
xmlhttpPost : function(strURL) {
var xmlHttpReq = false;
var self = this;
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader("Content-Type", "application/json");
self.xmlHttpReq.onreadystatechange = function() {
rest.draw_table_dyn(self.xmlHttpReq.responseText);
}
self.xmlHttpReq.send(null);
}
However, following are the problems I encounter:
1) Always the server is hit with a "OPTIONS" request rather than a "GET" or "POST" request. I understood from this link(http://engin.bzzzt.biz/2010/01/25/cross-domain-xhr-access-control-preflight/) that it is a preflight request as per the standards.
But is it possible for me to make a POST request? I tried using $.post, $.ajax or even $.get, but to no avail.
2) The response data is empty. I require the data to populate the page with items. Is there a way to read the json? Currently I am getting only an empty string with the return status a 0.
I tried xmlHttpRequest, $.ajax, $.get and $.post to send the request and receive the json to no avail.
I read here(http://stackoverflow.com/questions/4221458/how-to-make-a-jsonp-call-to-an-api-using-jquery) about keeping the script in the tag. This also didn't worked for me. Any ideas what I am doing wrong here?
Currently, the only way to POST to another origin via Ajax is if the server responds with an appropriate CORS Allow-* header:
Access-Control-Allow-Origin: your.origin
Without such a header, the request will be refused by the browser due to the Same-Origin Policy.
In your 1st example, it appears you're attempting to use JSONP (?callback=...). Such requests are strictly limited to GET as they are made by appending a new <script> element to the page rather than via XMLHttpRequest:
<script src="http://remote.origin/resource?callback=rest.draw_table_dyn"></script>
CORS is also limited in browser support to those with either XMLHttpRequest Level 2 or XDomainRequest (IE8/9).
Beyond that, you're limited to having to create a server-side proxy that mediates between the browser and the remote server.
It is possible to make a POST request using $.post and $.ajax.. Use $.ajax and provide functions for 'success' and 'failure'. In the 'error' function read the error message. This is should provide you a idea on why the ajax request is failing.
My guess is the ajax request is returning a 404 error..
P.S. $.get and $.post are shorthand versions of $.ajax ..
You can not make an ajax call to a page sitting outside your site (different domain) because of the Same Origin Policy
There are some workarounds available including using JSONP as datatype.

How to use JSONP to overcome XSS issue?

I have a piece of javascript executing on a jetty server which is sending a XMLHTTPRequest to a scoket on another server(wamp server). The request gets sent to the socket, however the XHR response seems to be getting blocked.
I have heard that I can use JSONP to overcome this problem.
However as I am new to both javascript and I have never used JSONP technique before I would greatly appreciate any help in how to use this technique?
function sendPost(url, postdata, callback) {
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null) {
alert ("Browser does not support HTTP Request")
return
}
xmlHttp.onreadystatechange=callback
xmlHttp.open("POST",url,true)
xmlHttp.send(postdata);
}
function sendInitRQ(width, height) {
var post = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><command type=\"init\"><width>" + width + "</width><height>" + height + "</height></command>";
sendPost("http://localhost:80/socket.php", post, initReturned);
}
I know that the php socket is recieving the post as when i check the server log i get a 200 on the get request.
I just want to know how can I use the JSONP approach?
I have seen exampples of the approach but Iam stilll unsure of how to do it.
The JSONP technique uses a completely different mechanism for issuing HTTP requests to a server and acting on the response. It requires cooperating code in the client page and on the server. The server must have a URL that responds to HTTP "GET" requests with a block of JSON wrapped in a function call. Thus, you can't just do JSONP transactions to any old server; it must be a server that explicitly provides the functionality.
The idea is that your client-side code creates a <script> block dynamically, with the "src" attribute set to the URL of the JSONP server. The URL should contain a parameter telling the server the name of the Javascript function you expect it to call with the JSON data. (Exactly what parameter name to use depends on the server; usually it's "callback", but I've seen some that use "jsonp".) The client must of course have that function in the global scope. In other words, if you have a function like
function handleJSON(json) {
var something = json.something;
// ... whatever ...
}
then your URL tells the server to call "handleJSON", and the server response should look like this:
handleJSON({"id": 102, "something": { "more": "data", "random": true }});
Thus when the <script> block is loaded from the "src" URL you gave, the browser will interpret the contents (the response from the server) and your function will be called.
It should be clear that you should only make JSONP requests to servers you trust, since they're sending back code to execute in your client, with access to any active session(s) your client has with other secured sites.
edit — Here's a nice article: http://www.ibm.com/developerworks/library/wa-aj-jsonp1/

Categories

Resources