pass object from JS to PHP and back
Posted
by Radu
on Stack Overflow
See other posts from Stack Overflow
or by Radu
Published on 2010-03-22T14:42:23Z
Indexed on
2010/03/22
14:51 UTC
Read the original article
Hit count: 327
This is something that I don't think can't be done, or can't be done easy.
Think of this, You have an button inside a div in HTML, when you click it, you call a php function via AJAX, I would like to send the element that start the click event(or any element as a parameter) to PHP and BACK to JS again, in a way like serialize() in PHP, to be able to restore the element in JS.
Let me give you a simple example:
PHP:
function ajaxCall(element){
return element;
}
JS:
callbackFunction(el){
el.color='red';
}
HTML:
<div id="id_div">
<input type="button" value="click Me" onClick="ajaxCall(this, callbackFunction);" />
</div>
So I thing at 3 methods
method 1. I can give each element in the page an ID. so the call to Ajax would look like this:
ajaxCall(this.id, callbackFunction);
and the callback function would be:
document.getElementById(el).color='red';
This method I think is hard, beacause in a big page is hard to keep track of all ID's.
method 2. I think that using xPath could be done, If i can get the exact path of an element, and in the callback function evaluate that path to reach the element. This method needs some googling, it is just an ideea.
method 3. Modify my AJAX functions, so it retain the element that started the event, and pass it to the callback function as argument when something returns from PHP, so in my AJAX would look like this:
eval(callbackFunction(argumentsFromPhp, element));
and the callback function would be:
callbackFunction(someArgsFromPhp, el){
el.color='red';
// parse someArgsFromPhp
}
I think that the third option is my choise to start this experiment.
Any of you has a better idea how I can accomplish this ?
Thank you.
© Stack Overflow or respective owner