I have a form which only consists of a submit button, which, when clicked, should send an Ajax request to the same page. PHP should then echo $_GET[‘name’] but doesn’t. This is just a stupid example but why doesn’t it work?
when clicked, should send an Ajax request to the same page.
Don’t do this. If you want to have a traditional form submit to the same page, that’s fine because you’re missing the trialing html tags. But an AJAX call should be separate and if all you want to do is return text, you don’t need any html tags at all.
You should probably do some hackey PHP stuff to have it return the AJAX call then die(); but that’s not good either. Just create a new page if you’re not using any kind of MVC type structures.
You’re sending the request but not doing anything with it. There should be a success callback within the object literal passed to the jQuery.ajax function. Furthermore, you are going to get back the entire page. You would need to clear the output buffer in php and kill the script using exit or die for the response to only contain “jane”. However, as mawburn pointed out you should probably be using a separate script for this considering you’re not using any type of routing system or mvc patterns. Though I would recommend writing the processing logic first than worrying about making it function without a page load. Once that is done you can then just post back to the same page and add flag to trigger the proper response when the request is being made via ajax and form was submitted.
I was actually making a request to another PHP script, but wanted to try a request to the same page. I see that this is problematic - as oddz pointed out, the entire page is returned.
Thanks, I’ve fixed that. After searching the Internet, I came across some people asking about how to filter the contents returned from an Ajax response. Would this be a feasible option under some circumstances?
One thing I have to ask: Can I run a PHP script after having received a successful Ajax response? I need to run some PHP code if the response is successful.
Thanks again for all of your help. Hopefully what I posted is somewhat clear!
In an ideal world the response would only contain what is necessary to update page. That is what you should shoot fore unless there is an existing workflow/system in place that makes it difficult to do that. However, that doesn’t seem the case here.
That would require another AJAX request. Though at that point you should probably be doing that in previous one and sending back whatever you need to update the front-end. It really depends on the architecture of the system and exact business requirements. If the task is completely unrelated perhaps.