How to send data from javascript to php - 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.

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.

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.

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.

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/

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'].

Related

Connecting JQuery generated elements to a database via PHP

I have a JQuery script which dynamically generates HTML elements on button click.
I am connecting to a mysql database using PDO and PHP but am wondering how you can target dynamically generated variables in an external JS file directly from PHP.
I have tried using AJAX but as far as i can understand it seems to only get data from PHP pages and not the opposite.
The JQuery code is like this...
//Where i want to use indexes from a lookup table to populate the select element
$("#main").append('<select><option value=""></option></select>');
I tried AJAX in this way
function getData(dataToPass)
{
$.ajax({
type: "POST",
url: "getData.php",
data: dataToPass,
success: function (returnedData)
{
$("#main").html(returnedData);
}
});
}
But you cant pass variables this way can you?
Im very new to PHP and JQuery and would appreciate the help.
First off, PHP has nothing to do with JavaScript. They are totally different languages, in their own separate domain. They co-work however if you want to. PHP can generate JavaScript code, which will then run on the client browser. The client browser though has no idea that the JavaScript code that is running was generated by PHP. Neither does PHP have any idea how to work with a browser. PHP doesn't even have any idea about HTML.
Thus, you can't pass to PHP a complex JavaScript object, the same way as you can't pass an object from PHP to JavaScript. However you CAN pass values and data structures (arrays, data objects).
In this case, you can either get the inner HTML code of the jQuery object in your JavaScript, by running
dataToPass = {html: $("#main").html()}; //it will be a string
or by constructing an object that will have just the data you need, for example:
dataToPass = {elements: [
{node: "select", options: [{node: "option", value: ""}]},
{node: "input", value: "someValue", type: "text"},
]};
As you have this JavaScript, it will send this data via the script you already have, to the server. On the server side you will have to intercept the $_POST superglobal, and ask for either the HTML string, which will be $_POST['html'] if you chose the first example, or access an array of elements by $_POST['elements'] if you used the second example.

Sending php variables to Javascript variables

Is there any way to do it without doing this:
send javaScript variable to php variable
OR can I do that, and "cover up" my url to the original one, without refreshing the page(still keep the php variables)?
I believe you are incorrect - you actually DO get the 'javascript' variable to PHP - using the jQuery code snippet below by #MikeD (jQuery is a javascript library containing many and many functions that you can then use in your code - making things little easier to do) above you can pass the javascript variable to PHP page.
On the php page you can assign this variable (originating on client side - browser) to PHP variable using something as simple as this:
$variable = $_REQUEST['javascriptVariable'];
A nice and easy way to do this is like this:
PHP
<div id="something" data-info="<?php echo $info ?>"></div>
Jquery
var info = $("#something").data("info");
EXPLANATION
Put the variable as a data attribute in some div using PHP, and then grab the data attribute from the DOM using JQuery.
There's two points that you can use PHP to create javascript vars, the first being when the "page" is created on the server, the second point is during the operation of the javascript application (once the page is loaded). The second point will require some sort of client side request (ajax, websocket, etc).
The best way to do it (in my experience) is using PHP's json extension which allows you to encode a PHP object/array into a json serialized string that can be unserialized/decoded within the browser into equivalent javascript types.
To do this during page generation can be done similarly as follows:
echo "jsvar = eval('('+".json_encode($phpvar)."+')')";
Note that the eval occurs on client side within browser and is common in every major js library.
Requesting an object during the normal operation of your javascript app will vary depending on how the data is requested, but each way will involve an asynchronous javascript request, a PHP script to handle the request (on the server side), and then a javascript side handler/callback that is called when data is received within javascript as a response to the request.
I typically use PHP to echo a json_encode()'ed string as plain text, then code the javascript side response callback to decode the response and fire an event. For a basic example:
PHP side:
<?php echo json_encode($responce_object); // DONE ?>
javascript side:
on_responce(responce)
{
var res_obj = eval('('+responce+')');
fire_event(res_obj);
}
The example above is very simple and generic to show how it works, but not much more is required for a fully functional solution. The real magic for a specific solution will happen within the "fire_event()" method - this is where the object can be handled via jquery or whatever.
You would want to wrap a lot of security around this code before putting it anywhere you care about, but it illustrates the principles without putting too much mud in the water:
<head>
<script>
function loadDiv(url)
{
$('#YourDivID').load(url);
}
</script>
<body>
<?php
$thisID = 1; //set here for demonstrative purposes. In the code this was stolen from, a MS SQL database provides the data
$thisGroup = "MyGroup";
$thisMembers = "TheMembers";
$thisName = "Just a example";
echo "<button onclick=loadDiv('http://siteonyourdomain.com/yourpage.php?ID=$thisID&group=$thisGroup&members=$thisMembers');>$thisName</button>";
//note this only works for sites on the same domain. You cannot load google.com into a div from yoursite.tv
//yourpage.php would have some code like this
// if(isset($_GET['thisID'])) {$myID = $_GET['thisID']} else {$myID = NULL}
?>
<div id="YourDivID">
Before
</div>
<?php
//I tested this code before posting, then replaced the domain and page name for security's sake
If you use $.ajax to make the submission to php you won't need to refresh the page. The code for the example on that page would look like this
var javascriptVariable = "John";
$.ajax({
url: '/myphpfile.php',
type: "GET",
dataType: "json",
data: {
name: javascriptVariable,
},
success: function( data ) {
// do success function here
},
error:function( xhr, ajaxOptions, thrownError ) {
// handle errors here
}
}, "json");

PHP Array in Javascript Variable - JS Element

I have a Javascript variable which I am setting a PHP variable to.
function cancel(number) {
var message = "<?= $message[" + number + "]; ?>";
}
$message is an array. "number" is the element of the array I want to set message to. Basically, I want to set a Javascript variable to a PHP variable using a Javascript variable as the element picker. So if "number" was 2, it would select:
$message[2];
However, the above approach doesn't work, and I'm not even sure if this is possible.
It isn't. Use XHR to retrieve the value from the server.
It doesn't seem at all possible; PHP is evaluated server-side, and javascript is evaluated client-side. So PHP would see it as $message["+number+"], and try to find the value at the index of "+number+". You'd probably have to do something like an AJAX request to get the data you're looking for.
What you are doing isn't possible; since php is a server-side language, it's executed first, and the js is executed after; there isn't any way to control which is executed first. You must retrieve the variable using AJAX.
Something like this will work:
<script type="text/javascript">
var messages = <?= json_encode($message) ?>;
function cancel(number) {
var message = messages[number];
}
</script>
Of course this will output the entire array in the JavaScript source. If it is large, then you are better off using AJAX.
Tip: if you "view source" it should be painfully obvious why your method doesn't work.
You simply cannot do this using this methodology. PHP is server-side code, meaning that it runs on the server, while JavaScript is client-side code, meaning it runs on the client, or your browser.
Once the PHP runs, it generates an HTML document and sends that document in the response to the browser. Once that's complete, the only way you can get data back to the server is to send it via a form POST, send it via AJAX, or send it via script tag remoting.
Consider looking at some examples on the Internet of how to POST data back to the server via a form and via AJAX. It's clear you're struggling with some concepts regarding how to properly architect your program, and looking at some examples would be a great way for you to learn and master these techniques.
PHP Submit Form Example
PHP Tutorial
You need to use AJAX call to resolve your issue.

call a php function from jquery

I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:
JQUERY:
$.ajax({
type: "POST",
url: post_url,
success: function(group) //we're calling the response json array 'tree'
{
//WANT TO CALL THE PHP FUNCTION HERE
} //end success
}); //end AJAX
PHP:
<?php
foreach($groups as $group){
echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
In your php script that builds your response, just add an extra property to your object that is the html string you want to put into your page and then have javascript put it where it needs to go. You have no choice but to run php functions on the server.
If you want to call a php function from your javascript you will have to execute an AJAX request to the function, in its own file, on the server. This is because javascript executes client side and PHP executes server side. Therefore, javascript does not have direct access to PHP functions.
You can use your PHP to write JavaScript, or you can call a php file from a javascript via AJAX.
Can you replicate the functionality of the PHP function with a JavaScript function?
Would this, or something similar, work for you:
$.ajax({
type: "POST",
url: post_url,
success: function(groups) //we're calling the response json array 'tree'
{
for(group in groups){
document.writeln("<option value='"+groups[group].id+"'>"+groups[group].group_name+"</option>";
}
}
}); //end AJAX
Alternatives:
Change the PHP that backs the original AJAX call so that, instead of sending back JSON, it sends back HTML exactly as you want it.
Chain a second AJAX call "inside" the success of the first, so that a second round-trip to the server is done for the JSON->HTML conversion.
Accept that sometimes you need to "duplicate" presentation-rules when you are working with multiple languages, and use something like EJS to do the same <option> stuff that PHP does elsewhere.
You have to be aware that you're dealing with two paradigms here, the first one is server-side logic (PHP) and the second one is client-side logic (JavaScript).
Unfortunately there is no way to call PHP from JS from the client without performing an AJAX call and rendering the content you want to show. However, you could prepare the result and set the body of the AJAX response with your requested HTML string.
If this is not possible, I suggest to look at the diverse number of JS frameworks that will provide helpers to generate options for select fields.

How to query database using javascript?

Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.
if ($publish == '') {
Link to publish.html
} else {
Link to edit.html
}
What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.
How can it be donw using javascript, jquery or ajax?? Please assist.
Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. Since you mentioned jquery, you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
$("a.youra").text('edit').attr('href', resp);
});
url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php.
After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.
I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.
Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.
PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.
For example, you could have javascript call a script like:
http://www.myserver.com/ajax_function.php?do=queryTheDatabase
In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.
Let me try, you want to change the link in a page from a pop-up that handles a form processing. Try to give your link a container:
<div id="publish_link">Publish</div>
As for the form submission use Ajax to submit data to the server to do an update and get a response back to change the link to edit or something:
$.post("submit.php", { some_field: "some_value"}, function(response) {
if(response.isPublished)
$('#publish_link', window.opener.document).html('Edit');
});
Basically your publish link is contained in a div with an ID publish_link so you change its content later after data processing without reloading the page. In the pop-up where you would do the form processing it is done using jQuery Ajax POST method to submit the data. Your script then accepts that data, update the database and if successful returns a response. jQuery POST function receives that response and there's a check there if isPublished is true, get the pop-up's opener window (your main window) and update the link to Edit. Just an idea, may not be the best out there.
It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.
Well, i think i understand your quaestion, but you have to get a starting point, try to understand this:
try to understand what are client variables and server variables.
javascript does not comunicate with database.
you can use javascript to retrieve data to a specific "Object variable".
Using ajax methods of jquery you can post that data do other page, that will execute the
proper actions
you can ;)
at first you must create php file to query database and return something like true or flase and then with file url check the function and get answer
function find_published(folder_id) {
var aj_url = "{{server_path}}/ajax/url"
var list;
$.getJSON(aj_url+"?callback=?&",
function(data) {
//here is your data... true false ... do every thing you want
}
);
};
this app for node.js does mysql queries https://github.com/felixge/node-mysql
You need to use AJAX for this, like .post() or .get() or JSON.

Categories