Assign Javascript variable to PHP with AJAX - php

I understand...
the disparity between PHP being server-side and Javascript being client-side.
AJAX can patch this issue.
the XMLHttpRequest object is significant.
However, I still can't work out how to pass the variable between the two languages.
Any assistance would be much appreciated!
EDIT: Thanks for your replies so far, I should clarify that I would like to do this without loading a new page.

You need to send an AJAX request containing the value of the variable in the query string or POST body.
The PHP script at the other end of the URL can read the value from the query string or POST body.

you could use JSON with JS and decode it with php, but as the post above states, it involves ajax.

UPDATE: Tutorial found at link
You should give a more detailed example of what you want to accomplish. But if I understand correctly, you want to use a value from your JavaScript code in your PHP code?
You should try using POST or GET parameters to pass values into PHP. For PHP to be able to do anything, you will have to load a new page.
Lets say you have list.php serving a list of posts. You want to "like" a post. Your JavaScript is on this page. When you click "like", an AJAX POST is sent to like.php with POST parameter id=123.
In like.php, you get the value from the request (using $_POST['id'] or something more appropriate), do your magic (save to db) and echo some result, json_encode(array('success' => true)) for example.
The JavaScript-code that called like.php can then use it's callback to check if the "like" was a success or not and display feedback. The like.php could be any page, you could use list.php if you'd want. I used like.php for clarity.
If this is not at all what you wanted, please provide more information.

If you haven't looked at jQuery framework for javaScript, do it.
If you have a variable called city in JS, you can pass it to the file.php by using
var city = "London";
$.get("file.php", {location:city} );
Which is a HTTP GET request.
In PHP(file.php), you then grab it by using
$city = $_GET['location'];
echo $city; //London

Related

JQuery - passing variable to php script

im stucked with following issue. I have an javascript (jquery) function where i need to pass a variable to php ON .success method. See below Please:
http://paste.org/55404
Any idea how to achieve this? Or is it even possible?
Thanks in advance.
jQuery runs in the browser. PHP runs on the server. So you can not mix and match them like that.
Instead, you will have to use AJAX or another mechanism to contact the server and get the information you need.
Depending on your use case, there may be other solutions, such as inserting the values into the page when the server generates it, or putting the values in a cookie.
Referring to your code, The .success method is called, when your ajax request to "index.php" returns a successful response.
Since you need to get the PHP variable in this function, you can attach the value of "genNavSide()" to the response as a parameter. It is the same way you assigned pageName value, and content value to the response data.
For example, instead of :
<?php echo pagesSideBar('data.pageName') ?>
call the function from your index.php, during the ajax call.
$sidebar = pagesSideBar($PageName);
$response->sidebar = $sidebar; // I just mentioned object, you can assign whatever way you are following to create the response
In the .success method :
jQuery('#links').html(data.sidebar);

Populate PHP variable with AJAX?

Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).
When a user enters an interest and clicks submit, my AJAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.
Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?
I hope this doesnt sound too confusing, thanks
Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.
The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.
No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.
It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):
$('#mysubmit').click(function() {
$.getJSON(
'form_ajax.php', // This is the php file that will be called
{ formVar1: $('#form-var-1').val() }, // Add all your form data here
function(data) {
// This is the function that is called after the php script is
// done executing. The 'data' variable will contain the $data
// array you see in the following php file.
}
);
});
I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:
<?php
$data = array();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$data['formVar1'] = $_POST['formVar1'];
}
echo json_encode($data);
?>
Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.

what's the best way to post 30 variables from client side to server?

hey,
i have about 30 variables which are created and modified by user (none of which comes from input, so submitting a form is not really an option), once modification finished a JS function process the variables and spouse to post them to the controller which will then send the to the model.
now, as appears in the title, my question is what is the best way for me to send them?
thnx for time and attention,
Ido
I wouldn't use GET for this unless it's something like a complex search form.
You can POST values in JavaScript either by using some form of AJAX or by generating a hidden form and submitting it.
Modern browsers and newer versions of PHP both support JSON, and there are supporting libraries you can use if the browsers you need to support or the PHP version you're stuck with are old. I'd recommend this as a way of getting data back and forth.
Client side JS:
var myobject = {
userparam: "value",
anotherThing: "another value",
something: "etc"
}
var serialized = JSON.stringify(myobject);
// use any AJAX technicque to POST 'serialized' back to the server
Then on the server-side:
<?php
$myobject = json_decode( $_POST['serialized'], true );
$myobject['userparam'] == "value"; // true
Hope this helps!
I would use a POST using an ajax-submitted form. You can simply create a form with hidden inputs and then use your favorite ajax library to submit the form to the server as a POST request.
If the variables are tightly related you can shove them into an array and POST them (use Javascript to construct the array of course). Another alternative would be to name each one of them and POST them separately?
POST array look like this: arr[]=Hello&arr[]=World
in PHP you can access it like
<?php
arr = $_POST['arr'] // ["Hello", "World"]
?>
Hope that helped!
Weigh it up between POST and GET. GET is better if you want to navigate back to the a page with a given set of 'variables'. POST is better if you're submitting a lot of content. However, a POST request is less 'efficient' as a GET request - bear that in mind and only use POST if you really need to.

php ajax and normal page difference

is there difference whether when a page called with ajax when called normally?
I mean how i could figure out a page called with ajax or called directly ?
You can add a parameter to the call, for example:
xmlhttp.open("GET","page.php?request=ajax",false);
And then check for it in php:
if($_GET['request'] == 'ajax'){
//this was called by ajax!
}
To distinguish between a normal page load, and an AJAX load ... some might code into the JS a variable to pass to the PHP page that indicates AJAX. This would let you modify output as JSON or whatever you wish to do.
Others use separate php scripts for AJAX.
But yeah, there are many ways to figure this out. More details if you have questions, but these are probably the easiest.
Edit: If you did not see the URL posted as the main comment as possible duplicate. this should answer your question about identifying ajax requests only.
Most well-known Ajax frameworks like
jQuery and mooTools add a specific
header which you can check with PHP:
if (strcasecmp('XMLHttpRequest', $_SERVER['HTTP_X_REQUESTED_WITH']) === 0)
{
// Ajax Request
}

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