2

I’m using Zend framework (php) and I’m trying to submit a from using ajax/jquery.

Here’s the .phtml:

<form id="find">
    <input type="text" name="name">
    <input type="submit" id="submit" value="Submit">
</form>

Here’s the ajax/jquery part:

$(document).ready(function() {
    $("#submit").click(function(){
        $.ajax({
            type:'POST',
            url: "<?php echo SITE_URL;?>Training/test", 
            data:$('#find').val(), 
            success: function(response) {
                alert (response);
            }
        });
    });
});

Here, “Training” is the controller and “test” is the action inside the controller. The action has just 1 line of code which is echo “hello”. After the user types a number in the box and clicks on “submit”, the control has to go to the controller thus displaying “hello” on success. However, nothing happens when I click on it. Please help me. Thanks in advance.

Robert
  • 19,800
  • 5
  • 55
  • 85
user2509780
  • 121
  • 2
  • 9
  • Does your javascript file actually get parsed by PHP before sent to the client? –  Jul 15 '13 at 11:50
  • I don't really understand what you mean.... – user2509780 Jul 15 '13 at 11:54
  • You use PHP code in the javascript (`url: "Training/test",`). If you request this file from a browser, that PHP code is most likely not executed and you end up with that literal code in your javascript. How does the javascript look clientside? –  Jul 15 '13 at 11:58
  • I use it the same way with other ajax/jquery calls and it works – user2509780 Jul 15 '13 at 12:09

3 Answers3

2

You didn't name parametr in Ajax call

data:$('#find').val(), 

change it to

data:{'param': $('#find').val()}, 

About Zend it doesn't matter if it's zend or not. You can handle request just providing proper URL. You can access param value in Zend via $this->getParam('param') method.

Also you don't prevent default submit action. Change your function to:

$("#submit").click(function(ev){ 
          ev.preventDefault();

or use in the end of function return false;

Robert
  • 19,800
  • 5
  • 55
  • 85
  • You don't have preventDefault or return false; – Robert Jul 15 '13 at 11:51
  • so do some debuging use prevent default then just simply alert('it works'); you can also use absolute url without need of php parsing it. – Robert Jul 15 '13 at 11:57
0
  1. I did not test your jQuery. But note you need the instruction event.preventDefault to ensure you haven't the normal form submit action.
  2. The main problem is at your zend Controller because you need a special response. I suppose you have a controller to perform the request logics. I'll name it AjaxController and I'll name the action ajaxrecuestAction to illustrate how to send a proper response.

    <?php
    // Filename: yourProject/module/ModuleName/src/Controller/AjaxController.php
    namespace ModuleName\Controller;
    
    use Zend\Mvc\Controller\AbstractActionController;
    use Zend\View\Model\ViewModel;
    
    class AjaxController extends AbstractActionController {
    public function ajaxrecuestAction(){
      // This function is called by zend to procces your ayax request
      // you must test if it's an xmlHttpRequest
      $request = $this->getRequest();
      $is_xmlHttpRequest = ($request->isXmlHttpRequest()) ? 1 : 0;
      if(!$is_xmlHttpRequest){
        // If not you must return a normal page, a message page
        // perhaps a forgiven message page, etc. It depends on your site
        // logics
      }else{
        // The solution's KEY
        // You must disable the zend's normal output
        $viewmodel = new ViewModel();
        $viewmodel->setTerminal($is_xmlhttprequest);
        // Proccess the input and prepare your output
        $output = CallTheLogicsToPrepareIt($request->getContent());
        // send your response
        $response = $this->getResponse();
        $response->setContent($output);
        return $response;
      }
    }
    
-1

**EDIT: Just noted that, in your HTML, you didn't give an ID attribute to the "find" field. Therefore $('#find').val() will give you an error, something like "cannot find method val() of undefined. Add the id=find tag to your and it should work.

** Other Edit: Sorry about the confusion. Your form has id=find but what you want to send to the server (I believe), is the value of the fields. So give an ID=name to your input then use:

var data = {find: $('#name').val()};

You should start by using your console to see if the event is triggered. Something like:

<script>
$(document).ready(function() {
    $("#submit").click(function(e){
        e.preventDefault ? e.preventDefault() : e.returnValue = false;  //This will prevent the regular submit
        console.log('Hello');
    });
});
</script>

(You do use Fire bug or the Chrome dev tools, right) ? If not, look at the end of this post. If you can see the Hello in your console, you're on the right path. Then try to set your url in a variable and try to check it in your console:

<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
    $("#submit").click(function(e){
        e.preventDefault ? e.preventDefault() : e.returnValue = false;  //This will prevent the regular submit
        console.log(url);
    });
});
</script>

Then you should see the url in the console, meaning you're still doing good.

If that works, try to set the data and check the output in the same way:

<script>
var url = "<?php echo SITE_URL;?>Training/test";
var data = {
    find: $('#find').val()
};
$(document).ready(function() {
    $("#submit").click(function(e){
        e.preventDefault ? e.preventDefault() : e.returnValue = false;  //This will prevent the regular submit
        console.log(data);
    });
});
</script>

Hoping everything still works (you saw the data), then try the actual full code and see if you have an error or something. Also, be sure to include an error function to your ajax call so you will have a response if something went wrong on the server.

<script>
var url = "<?php echo SITE_URL;?>Training/test";
$(document).ready(function() {
    $("#submit").click(function(e){
        e.preventDefault ? e.preventDefault() : e.returnValue = false;  //This will prevent the regular submit
        var url = "<?php echo SITE_URL;?>Training/test";
        var data = {
            find: $('#find').val()
        };
        $.ajax({
            type:'POST',
            url: url, 
            data: data, 
            success: function(response) {
                alert (response);
            },
            error: function(resp) {
                alert(resp.responseText);
            }
        });
    });
});
</script>

Some tools to help you out:

If you are using FireFox, use FireBug for your debugging: https://addons.mozilla.org/fr/firefox/addon/firebug/

If you are using Chrome (my personal favorite), learn a bit more about Chrome Developer Tools: https://developers.google.com/chrome-developer-tools/?hl=fr

If you are using IE, please switch to something else for development purposes, then try it in IE to make sure you code is compatible (most likely won't be but it will be easier to find out why it doesn't work afterwards).

As for the line e.preventDefault......, look into this SO post for more details: https://stackoverflow.com/a/15913969/1483513

Hope this helps !

Community
  • 1
  • 1
Joel Lord
  • 2,175
  • 1
  • 18
  • 25
  • However, the "find" is not a field. It is the id of the form – user2509780 Jul 15 '13 at 14:45
  • ` e.preventDefault ? e.preventDefault() : e.returnValue = false; ` this line makes no sense in Jquery all he needs is just `e.preventDefault()` check Jquery Manual. – Robert Jul 16 '13 at 06:11