DVCITIS
DVCITIS

Reputation: 1037

Best Practice: Using jquery .load() with PHP to both pass data from Javascript and retrieve from PHP. How to pass data?

Lots of info/questions on Ajax/.load() and a little overwhelmed. Looking to take the most efficient approach.

Goal: Execute ajax request onclick; pass the innerHTML of clicked item to PHP for use in MySQL DB query. Write query result to particular element.

Progress:

Not sure whether to use .load() or .ajax().

.load() option allows a 'plain object or string' to be sent to the server with the request and easy to specify where to write the data using selector. Jquery documentation: .load( url [, data ] [, complete ] ).

Trying to implement this method first.

 $(".classExample").click(function(){
 innerHTMLtoBeUsedInPHP = this.innerHTML;
 $("#writeDataHere").load("dateAjax.php",innerHTMLtoBeUsedInPHP);
 });


<?php echo 'Passing data from PHP back to client-side is sorted with the echo'.$_GET['innerHTMLtoBeUsedInPHP']; ?>

According to the jquery documentation, the POST method is used if data is provided as an object; otherwise, GET is assumed. The innerHTML is a string so GET used.

Why can I not access the 'innerHTMLtoBeUsedInPHP' in my PHP script?

Upvotes: 0

Views: 102

Answers (1)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15301

What you are sending to the server is by GET, so your url will look like dateAjax.php?<li>asdf</li>...more html. Probably not ideal. You could still access the data using $_SERVER['QUERY_STRING'] in php but there would be a limit on how much data you could send which is likely smaller than you need. I would suggest changing the innerHTML in the load call to something like {"data":innerHTMLtoBeUsedInPHP} which would change the call to a post and make the data available as $_POST['data']

Upvotes: 1

Related Questions