We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Form/links with ajax(jquery)

Hey guys,

First I have to say that I'm not an expert in php etc. :/

On my page their are 4 div container (header, navi, content, footer) and only the content div should be changed everytime a link is clicked or a form is submitted. I chose Jquery/ajax for this.

Currently I use for example this code:

<script type="text/javascript">
            $(document).ready(function() {
                $("#searchform").submit(function() {
                    var clustername = $("#cname").val();
                    $("#content").load("search/" + clustername);
                    return false;
                });
            });
        </script>

And the controller:

public function searchAction($cname)
    {
        //Nach Cluster suchen      
        if (!empty($cname)) {

            $result = cluster::find(array(
                "clustername like :clustername:",
                "bind" => ["clustername" => $cname] 
                )); 
            if ($result == false || empty($result) || count($result) == 0) {

                $this->flashSession->notice("Kein Cluster gefunden!");
                return $this->response->redirect("cluster/noCluster");

            };

            return $this->view->clusters = $result;
        }
        else {
            $this->flashSession->error("Es wurde kein Name eingegeben!");

            return $this->response->redirect("cluster/noCluster");
        };
    }

But I think this is only a workaround? and there has to be a diffrent method to achieve the same result.

So I tried something like this:

<script type="text/javascript">
            $(document).ready(function() {
                $("#searchform").submit(function() {
                    var clustername = $("#cname").val();
                    $.ajax({
                        type:"POST",
                        url:"cluster/search",
                        data:{cname:clustername},
                        success:function(){
                            return false;
                        };
                    });
                });
            });
        </script>

And I changed my controller to this:

    public function searchAction()
    {
        $cname = $_POST["cname"];
        ....
    }

But I do something wrong, because it shows a new blank page with the result of my search.

I hope someone could help me with "my problem" and give some hints/examples.

PS: Sry for my bad english



58.4k
edited Mar '14

@Fuhunter In controler for you check ajax working

public function searchAction()
    {
       $request =$this->request;
       if ($request->isPost()==true) {
            if ($request->isAjax() == true) {
                    echo $cname = $_POST["cname"];
        ....
    }


8.1k
edited Mar '14

Don't forget turn off view service using Ajax

$this->view->disable();
edited Mar '14

@oleg why i have to turn view off when using ajax? How do I get my results without using php echo ".." in my controller?

@duythien I get strange results... The value of my two textfields will be changed to what I've typed in for searching. Have no idea why. I used this:

 function searchAction()
    {
       if ($this->request->isPost() == true) {
            if ($this->request->isAjax() == true) {
                    echo $cname = $_POST["cname"];
                    exit;
             };
       };
        ....
    }


8.1k
edited Mar '14

When you disable view service, you can respond result of your Ajax request like:

echo json_encode(mixed your_result);

Example

$result = [
    'name' => 'john',
    'rating' => '123'
];

echo json_encode($result);

This response you willn't see on browser. You can receive this respond via succes function of you Ajax request. And handle it trouth javascript(Jquery) and DOM.

edited Mar '14

Seems logic, didn't know that this works.

Thanks so far.

I know that this isn't the right forum for the following question, but how do I load the result into my Div container with the success function?

How can I replace this:

<div id = "content">
            <h3>Suche oder erstelle einen eigenen Cluster</h3>
            {{ form("id":"searchform") }}

                <label>Clustername:</label>
                {{ text_field("cname", "class":"inputfeld", "id":"cname", "size": 20, "maxlength": 20) }}
                <br>
                {{ submit_button("Suchen", "class":"button") }}
                {{ flash.output() }}
            </form>
            <br>
            {{ form("cluster/create", "id":"createform") }}

                <label>Clustername:</label>
                {{ text_field("cname", "class":"inputfeld", "size": 20, "maxlength": 20) }}
                <br>
                <label>Clusterkürzel:</label>
                {{ text_field("ckuerzel", "class":"inputfeld", "size": 5, "maxlength": 5) }}
                <br>
                {{ submit_button("Gründen", "class":"button") }}
            </form>
        </div>

With my old .volt file/the result ?

{% for cluster in clusters %}
    <span id = "{{ cluster.clusterid }}">{{ link_to("cluster/show/" ~ cluster.clusterid, cluster.clustername) }}</span>
{% endfor %}

EDIT:

I have to convert my result to an Array with:

echo json_encode($result->toArray());

otherwise it wouldn't work.

furthermore my error function of my ajax request is triggered

$.ajax({
    type:"POST",
    url:"cluster/search",
    data:{cname:clustername},
    success:function(results) {
        $("#content").text("Hello");
    },
    error:function() {
        alert("FEHLER!");
    }
});

But the data is passed correctly to the controllerAction. I don't have a single clue, why?!



7.9k
edited Mar '14

i think that you use wrong attribute, content is a container(div) thus you should use html() instead of text()


$("#content").html("please wait");

$.ajax({
    type:"POST",
    url:"cluster/search",
    data:{cname:clustername},
    success:function(results) 
    {
       //results is what controller / action replied
       //controller  / action can reply a json array or even html markup ready to replace current content's 
       //do something with results, 
       //or print something for test :
       $("#content").html("Hello");
    },
    error:function()
    {
        //alert("FEHLER!");
        $("#content").html("could not update content");
    }
});

Ah ok, wasn't sure which one I should use, but the Error function is still loaded with this error: "Not connect. Verify Network." I host the Website on my Computer with XAMPP, but I don't know why I get this error.

edited Mar '14

Do you request the same domain in ajax?

Maybe you violated Same Origin Policy? https://en.wikipedia.org/wiki/Same_origin_policy

Yep it's the same domain. I checked this earlier and tryed e.g. JSONP but still got this error message.