How to use jQuery AJAX for an outside domain? - php

I am trying to perform a simple jQuery AJAX attempt using either a .get() or a .post().
If I have a local copy on my server and do:
$.get('/hash.php',...,...)
I monitor in my console in firebug that the get is done and I get a response.
All I change is the URI to an outside server and nothing happens.
$.get('https://secure.mysite.com/subdir/hash.php',...,...)
Doesn't help if I take the 's' off or if I use post instead. Am I missing some parameter that I should use in jQuery?
EDIT: I forgot to mention the reason I'm doing this is because I am eventually migrating from a PHP4 site to a PHP5 site, but for now the live PHP4 site needs a function that isn't in PHP4. So I am calling a PHP5 server to do it. I think I have a good workaround. Thanks!

You cannot send an Ajax Request to another domain than the other on which your application is deployed. This is because of the Same Origin Policy implemented in web-browers -- a security measure.
There are two possible solutions, though :
sending the request to your own server, that will act as a proxy to another (either via a PHP script, or, better, using some of Apache's mod_proxy_http module)
or not using "Ajax", but other techniques, like dynamically creating <script> tags -- which are not subject to the SOP constraint.

It's true that you normally can't do Ajax outside your domain due to the browsers. However using JSONP it is possible to do this. jQuery also has a jsonp param for Ajax now. To make this work you need to control the output of the server though.

Javascript cannot access a server outside of where the javascript file came from.
That is a security feature.
Depending on how browser-specific you want to get you may get around this, but that becomes a bit of a slippery slope.

You cannot do cross domain ajax requests directly, this would be a security concern.
You will need to call your local php file from jquery and have the php file talk to the other domain.

There's a method called JSONP which is used to circumvent that. See the 2nd reply on SO #570100

Related

How to debug Javascript + PHP + Web services

Disclaimer: May be a insane question but I have suffered a lot so came here.
I am working on a legacy application which uses JS + PHP + Web services (Written in spring).
Flow of the application :
Whenever any web service is called from JS it is redirected to one php file. The php file authenticates the user(using one web service) and then forwards the request to actual web service.
How can I debug this application ? I have debugged JS using Firebug and servr side code using Eclipse but never debugged such a application.
~Ajinkya.
I think there are a variety of things that need to be done, and I must say this question is sufficiently general as to not have a straight answer so I will do my best. As xdazz mentioned, var_dump (and die) are necessary from the PHP standpoint.
Whenever anything is returned to JS console.log it. In addition, ensure XHTTP requests are turned on for Firebug or alternatively view the output of each request in the Chrome Network tab.
With a combination of console.log, var_dump, and die, you can trace non-functioning parts of the application repeatedly step by step until you come across the bug.
Alternatively, and in the long run you ought to be doing this anyway, build error handling code into all the PHP code that is only activated when a debug flag is set to true. This way you can get detailed error messages and then when you deploy, you can turn them off to avoid compromising security.
If you are needing to inspect the entire lifecycle of a Web service request in your scenario you will need to combine a several techniques. Considering the fact that the scope of your scenario spans from client to server you will need to decide with what you will persist the information you need to inspect.
Personally, I would choose the path of least resistance which in my case would probably be cookies. With that being said you should be able chronologically log the necessary information via JavaScript and PHP, both before, during and after the request and even redirect has occurred.
This strategy would then allow for the information logged with cookies to then be dumped or analyzed via JavaScript, WebKit inspector or Firebug. Again, this is probably how I would handle such a scenario. Lastly, you can apply different storage strategies to this technique such as using a session or database for persistence.
Note: You can use something like WebKit Inspector, and possibly Firebug, to analyze data transmitted and received for GET, POST and even WebSocket requests.

How to debug AJAX requests? How to know which PHP function is invoked?

I'm debugging Ajax calls.
How do I know which specific PHP function is called by an ajax call ?
I can only see the request and the javascript code triggering the request, but I dunno how is handled on the request on server side ?
I'm currently inspecting all php code, but I was wondering if there is an easier way..
thanks
An Ajax call does not call a specific function, it merely executes a script. Look at the script, search for its "main" (Whatever name it has in your script) and you'll have the exectued function.
If you want a real debug environment and be able to set breakpoints in your php-code, refer to the zend debugger or xdebug. Both can be controlled with the pdt eclipse-plugin or other IDEs.
If you just want to see some small pieces of information, you can of course just add some echo's or var_dump's to your php-code and then use the firebug firefox extension to view the response to your ajax-requests, which contains the echoed strings.
I would recommend you make use of FireBug and FirePHP. FirePHP allows you to log from PHP to FireBug console. In this way you can log anything for example all the queries being run or log from methods/functions.
Just use firebug and after the request is sent, look for the response. e.g. function1 echo foo, function2 echo bar, if it's blank...none of those 2 function was called.
On my end, I'm using Safari and finding both request / response from an ajax call to a PHP script is a breeze.
Debugging using Firefox's addon FireBug, you can check out the request and response data content easily.
http://www.daniweb.com/web-development/php/code/216729
So by right, Ajax cannot access remote web server content, so you need the proxy page in the middle of the whole architecture flow.
So which means:
[Within Same Server]
PHP page using AJAX -> Web Services / Web Server that contains your response functions
[Within 2 Servers, Connecting to Remote Server]
PHP page using AJAX -> PHP Proxy Page -> Web Services / Web Server that contains your response functions
So the overall proxy page acting like a "middle-man" to connect to remote site.
[IMPORTANT]
Don't confuse router proxy and proxy page, but have the same theory but it is different thing.

Asynchronous cross-domain GET requests

Does anyone has any solutions on accomplishing asynchronous cross-domain GET requests. I am looking to make a site that checks available names of other sites. The faster the better.
I'd like it to use my server if possible, as its most likely faster than the client. Would most likely send it a huge array (300-10000) requests.
Examples, links, anything will work.
You would have to make a same-domain get request to your server, and have your PHP script do the checking (maybe using CURL) before responding to the request.
http://www.php.net/manual/en/curl.examples-basic.php
Do you want to perform the Cross-Domain Check using JavaScript or using PHP?
If using JavaScript you will probably be restricted by the Same-Origin Policy, though some pages may allow your browser to access them using Ajax.
If using PHP there is no way to perform a asynchronous request, because PHP is synchronous all over.
Maybe a good variant would be to send a request to a Node.JS server from your JavaScript and then let Node.JS get the page without blocking a process?
Check out curl http://us.php.net/curl

How can you make a php script only answer requests made from the same server?

How can I get my PHP script to only answer requests if the requesting script is on the same domain?
** Edit:
The PHP file is being accessed by an ajax request and is proxy, so I don't want others directly requesting it to come up, is this possible?
You could use $_SERVER['REMOTE_ADDR'] to compare the IP of the user requesting the page. Or you could simply make it a command line script that (obviously) requires you to run it from the command line.
edit:
You want to prevent people from using that script other than via AJAX? Impossible, as AJAX itself is executed by the client, as such the request starts there. And it will be always possible to call that script alone; you can make it harder, but you won't be able to prevent it.
There is no safe way to do that. Some developers will naively use the HTTP referrer header field, but anyone smart enough to abuse your ajax interface will have no problem forging the referrer.
You shouldn't be sending requests to your own server. You should include the file and execute the functions directly.

Best method for debugging a called webservice in php?

I have an n-tier system where a frontend templating layer makes calls out to a backend application server. For instance, I need to retrieve some search results, and the frontend calls the backend to get the results.
Both the templating engine and the appserver are written in PHP. I currently use PHPed to initiate debug sessions to the templating engine, however, when the http request goes out to remote service my debugger just sits and waits for the IO to complete.
What I would like to do is emulate the HTTP call but really just stay inside my PHP process, do a giant push of the environment onto some kind of stack, then have my appserver environment load and process the call. After the call is done, I do an env pop, and get the results of the http call in a var (for instance, via an output buffer). I can run both services on the same server. Does anyone have any ideas or libraries that already do this?
Can you not run a debugger and set a breakpoint in the appserver too? Two different debug sessions - one to trap the templating engine call and one to trap the call in the appserver.
You should be able to trace the output from the appserver in the templating engine debugging session.
If it is not possible to run two debug sessions then create some test inputs for the appserver by capturing outputs from the templating engine and use a single debugger with your test appserver inputs.
This is embarrassingly crude, and quite free of any study of how the debugger works, but have you tried adding
debugBreak();
at the entry points to your called routine? (Assuming both processes running on the same machine).
I have used this technique to break back into a process called via AMFPHP. I have had a PHP file loading Flash file into browser, which then calls back to PHP using AMFPHP, all on the same server. When I hit the debugBreak() line, PhpED regains control.
Why don't you use an HTTP sniffer? Something like tcpflow.
Alternatively, you could just log the complete XML to a file for each request & response.
Unfortunately it's not clear from your question what you're trying to achieve so these are just guesses. You should probably state more clearly exactly what problem you're trying to solve.
You could possibly re-factor your code that calls out to the remove service and use dependency injection and mocks. That would allow you to isolate the development of the front-end with the back by suppling "mocked" but valid data.
Hope that helps.
Can I assume you're talking about the lack of threads in PHP, so the service stops the flow of your program and halts the debugger? There's ways around it, but they are hard, cumbersome and hackish.
For example, if you use a framework like Zend for the HTTP traffic, you can hack the HTTP class to use primitive sockets for the service reading/writing instead of the built-in stuff, and create a small task switcher (loop :) to track what's going on.
You could of course use fopen ( 'http://...' ) and fread in chunks in a loop as well, that could do the trick, but you need http: support in streams turned on.
I don't know much about PHP debugging, and I'm not sure I follow 'push of the environment onto some kind of stack', but I wonder if netcat + some shell scripting could be useful here for troubleshooting ?
You can use netcat to:
Spoof an HTTP Request
Act like a webserver (listen on a port - pick a port, any port!)
http://www.plenz.com/netcat-tips
You could use it to stub out a fake webservice on the one end:
echo "<xml .. <node>hello php!</node>" | netcat -lp 80 ... etc
... and you can certainly use it listening on a port to very clearly see what the incoming requests to the webservice look like.
Could you use a shell script with netcat as middle man that acts like your webservice, immediately returns something generic to make your PHP happy, then passes the request on to your actual appserver and logs the results?
Super simple.
netcat webserver http://img240.imageshack.us/img240/791/netcat.jpg
This is not open source, but check out Charles. It works as a proxy, and is the best debugging proxy I've seen to date. It works on linux, os/x and windows.
Pretty much any HTTP library will allow you to specify a proxy.
PhpED supports parallel debug sessions - meaning you can start debugging code that issues request to initial server and then inter-server requests too. All you need is to set breakpoints in corresponding projects and pass debugger request between the servers. Normally you can do this by re-transmitting value of DBGSESSID (the debugger request) variable with its value to the 2nd server. The variable can be found among $_COOKIES and/or $_GET (depending on how you start debugging -- from the IDE or usign Debugger Toolbar). To re-transmit the variable to the secondary server(s) you can add it to POST variables or as URL parameter or cookie. If you can't do that f.e. if your server filters out all from get/post/cookies, try to embed DebugBreak() call.
Make sure that all your servers can find the IDE by its IP address in the request and allowed to connect back to the IDE -- e.g. you have necessary rules in firewall and LinuxSE (buy default this SE layer is enabled in all modern Linuxes these days). It took me a day to figure out why my server can't connect.
In case if connection from the server to the IDE is not possible (if workstation with the IDE is in a different network, for example at your home), you can use ssh tunnels. In this case the IDE address is localhost, of course.

Categories