foshoeiyyy
foshoeiyyy

Reputation: 471

How to send data from javascript to php

$('myBtn').on("click",function(){
var parent= $(this).parent();// will give you the Parent Object of the button, that has       been clicked
});

I need to send var parent to php so it knows where to display the html data (in the correct are div/class, how would i do this.

Upvotes: 0

Views: 1373

Answers (5)

Quentin
Quentin

Reputation: 943142

The short answer is that "You can't".

Communication between the browser (where your JS is running) and the server (where the PHP is running) is handled via HTTP. If you want to send a JavaScript object then you have to serialise it to a string and deserialise it at the other end. There is no sane way to represent an HTMLElementNode (or a jQuery object that wraps on) in that process (not least because PHP doesn't usually represent HTML in a DOM and when it does it won't be the same DOM instance as the browser is using).

Usually in this type of situation, you would request some data from PHP (possibly using one of jQuery's ajax methods) and then use JavaScript to turn it into DOM elements and insert it into the document.

Upvotes: 3

Brigand
Brigand

Reputation: 86220

As far as I know, you can't pass a DOM object directly to the server -- there's too much information stored for it to be practical. You could send the HTML of the object though.

Here's an example that sends the HTML to the server. You would process it, but we just echo it back.

http://jsfiddle.net/hLD4F/

Try clicking on any of the buttons, and it will send a request. In PHP you could access this information via $_POST['html'].

Upvotes: 0

Muhammad Atif Agha
Muhammad Atif Agha

Reputation: 1545

Please use Jquery and use $.ajax for this purpose

$.ajax({
type: "POST",
url: "yourPHPPage.php",
data: "parentvar="+parent,

//parent is a javascript variable

success: function(msg){


//Message received from server,
    // if you would write some code in echo there, like echo "hello";
    // you would get that in msg.


}

});

to access this variable on php, use $_POST["parentvar"]; You can also send multiple values by concatinating them with & operator. Like data:"parentVar="+parent+"&name=atif&age=23"; etc

Please let me know if further help needed.

Further help on http://api.jquery.com/jQuery.ajax/

Upvotes: 0

SlavaNov
SlavaNov

Reputation: 2485

Try JSON and Ajax (XMLHttpRequest) as the "client to server" mechanism

JavaScript is evaluated on client-side, when PHP is server side. You don't have trivial way to do it.

Upvotes: 2

Alasjo
Alasjo

Reputation: 1240

If the html data is not already generated, you would have to make a new request to the server, preferrably by the jQuery $.get function, then pass the output (again via jQuery) to the parent element.

Upvotes: 0

Related Questions