views:

31

answers:

1

Hey guys How do I use the PHP variable $contact['id'] in my ajax call? I'm trying to create a page that retrieves all notifications associated with a user. When the page load I already know the id of the user, how do I use this parameter in my ajax calls from the beginning? At the moment I am using the php preprocessor by splitting up the php string and inserting the variables but I know this isnt a particularly good solution and doesnt for example allow me to refactor the javascript out into its own file. I am using the Zend PHP Framework by the way. Anyone know how best to achieve what I am trying to do?

<?php $this->headScript()->appendScript('
dojo.require("dijit.form.Textarea");

function getNotes(){
    dojo.xhrGet({
        url: "/manager/contacts/get-notes-html",
        content: {
            "contactId" : '.$this->contact['id'].',
        },
        load: function(response) {
                console.log("Form successfully submitted");
                dojo.byId("notesDiv").innerHTML = response;
        },
        error: function() {
                console.error("Error on submission");
                alert("error error errrrror");
        }
    });


}
dojo.addOnLoad(getNotes);
');
?>

<div id="notesDiv">

</div>
+1  A: 

just put your contact_id in a variable in javascript, so you can keep the same code no matter what and it's a bit more clean.

if you don't want to pollute the global namespace just create your own like data.

i.e.

<?php $this->headScript()->appendScript('
 contact_id = ' . $this->contact['id'] .';
');

PS: also Zend Framework provide some captureStart() and captureEnd() so you can do that job in the controller

$this->view->headScript()->captureStart();
echo "foobar = {$foobar};\n";
$this->view->headScript()->captureEnd();
RageZ
Hey thanks for the quick response however is there not a better way? Because if I refactor the javascript into its own file with .js instead of .php extension then I think the php preprocessor will ignore and $this->contact['id'] wont work.
Nick
I don't really know what this id is used for. but if you are able to guest it on server side you shouldn't push it on client side. After if this id is linked to whatever page and you still want to do some ajax I am afraid there is no other solution.
RageZ
you don't need to make php process .js file, just code you javascript and use variable when it's coming from the server. On your action controller add the variable in javascript and you are done
RageZ