Load php in background with javascript, not passing variables - javascript

I'm working on this function that loads a php file in the background:
<div id="content1"></div>
<script type="text/javascript">
<!--
$("#content1").load("/bm_products_filter.php");
//-->
</script>
The original php code is this:
<?php require('/bm_products_filter.php');
?>
With the original code the page works fine, with the java code it gives errors. This is because the php doesn't use the variables in the current page. I know how to pass variables to the external php but is there a way that it uses all the variables on the current page?

I am not sure if I got you wrong but you cannot load PHP files with JavaScript or JQuery.
JavaScript is client sided and has no access to the server if you want to load some data on a point of time when the template builds / is built without PHP oyu have to use an Ajax request which is also pretty simple with JQuery.
Please check out:
http://api.jquery.com/jquery.ajax/

If you can rewrite the bm_products_filter.php to return a JSON output, you can use a function as below to get values returned from the php.
jsonKey1 I have used below is one of the JSON keys returned from the php.
function getToken() {
var requestStr = "./bm_products_filter.php";
$.ajax({
url: requestStr,
type: "GET",
cache: true,
dataType: 'json',
success: function (data) {
bmProductsData = data.jsonKey1;
}
});
}
Hope this helps.

Related

How to get js variable's value into a PHP variable later used for MySQL without submit or click on any button using JS/Jquery? [duplicate]

I have an php variable like this:
PHP Code:
$php_value = 'Am from PHP';
And I want to be able to change this variable with jQuery and the jQuery is on the same page?
You can't.
By the time the page has been delivered to the browser and the JavaScript has run, the PHP program that generated the page will have finished running and the variable will no longer exist.
JavaScript will allow you to send new data to the server (Ajax), where the server could store the data somewhere (a database is usual), and read the response.
JavaScript will also allow you to modify the page in in the browser (DOM) (including with the data included in the response for an Ajax request).
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it:
$php_value = 'Am from PHP';
if exists($_POST['php_value_from_jquery']) {
$php_value = $_POST['php_value_from_jquery'];
}
If I understand your question correctly, AJAX cannot post data to PHP code on the same page. I've been told that it can, but it is not trivial - still, I cannot imagine how that is possible. At any rate, AJAX is easy if a secondary PHP file is used.
Here is an example of what I mean. If you try this:
<?php
echo 'Hello';
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body>
</body>
</html>
The popup will contain the HTML for the page.
However, if you use two files:
file1.php
<?php
echo 'Hello';
?>
file2.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'file1.php',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body></body>
</html>
The popup will contain only the word "Hello".
To use ajax, you must call an external PHP file.
After considering the above, note that Quentin's answer is important -- even if you use AJAX to set a PHP variable on the server, that variable disappears after the AJAX completes -- just like the PHP variables all disappear after your index.php has finished rendering the DOM and presenting it to the visitor's browser.
So, what's to be done? Two options.
(1) As Quentin points out, you can store values permanently in a database, or
(2) You can use a PHP superglobal, such as a $_SESSION variable. For example:
Client side: file2.php
var storeme = "Hello there";
$.ajax({
type: 'POST',
url: 'file1.php',
data: 'stored_on_server=' +storeme,
success: function(data) {
alert(data);
}
});
file1.php
<?php
session_start();
$SESSION['a_variable_name'] = $_POST['stored_on_server'];
You can later retrieve that variable value thus:
$.ajax({
type: 'POST',
url: 'file3.php',
success: function(data) {
alert(data); //a popup will display Hello There
}
});
file3.php
<?php
session_start();
echo $SESSION['a_variable_name'];
You can't able to change the php value using javascript. i.e Server scripts runs first after that client side script will take effect in that case you cant able to modify the same, since they already rendered in browsers
If jQuery is going to be processing the data, then you can assign the PHP variable to a jQuery variable like this:
<script>
var jquery_value = <?php echo $php_value; ?>
</script>
As far as I know, because jQuery is client-side and php is server side, it's not possible to assign a jQuery variable back to PHP.

Accessing jquery data variable in ajax call in server side script

I have a few ajax calls in my app they all go to the same file server side. i want to know if I can use a variable... I want to have a way to distinguish the call from other calls and of course, use the variable to select which script in the file to send back to the client. I do not need to use the variable after the script has run in any way. Or am i going about this the wrong way?
for example this is one of my ajax calls
var variable1 = 'currentuser1var';
return $.ajax({
type: 'GET',
url: '/users/index',
data: {currentuser1var: variable1},
dataType: 'script',
});
then the script in my server side file would be
if (currentuser1var) { script here }
else if (currentuser2var) { script here }
...
I am not sure how to access the string, inside the object call. Do i need to access the object first then the string? Or just reference the variable some how.
EDIT Tried
if(typeof(currentuser1var) != "undefined") { script here }
to no avail.
If you were using PHP, your server side script would be:
if(isset($_GET['currentuser1var'])) {
... script to process the currentuser1var variable ...
} else if (isset($_GET['currentuser2var'])) {
... script to process the currentuser2var variable ...
}
Aj was right here I guess for php as I did not list what server side code I was using, but simply put, I changed my ajax call to
return $.ajax({
type: 'GET',
url: '/users/show',
data: { currentuser1var: 'variable1'},
});
where the key is currentuser1var and the value variable1 is a string and leave out defining the variable else where in the code. That way the url comes through correctly to the server being /users/show?currentuser1var=variable1. And in my destination file add my ruby code there to use the variables.

Ajax Call, how to access $_POST var

Sorry if this is a silly question but I'm completely new to AJAX and I'm wondering why my code is not working like I want..
I have the following:
an Ajax Call looking like that:
$.ajax({
type: "POST",
url: "/newnote.php",
data: {
content: content
},
success: function() {
}
});
and on the beginning of the page newnote.php (which is exactly the one, where the ajax-call is on, I have the following PHP:
if(!empty($_POST)){
header("Location:index.php");
}
But the php on the beginning of the page is not executed, of course, because the site seems not to be reloaded, but, when looking in developer tools under "network", i see that there is a post request on newnote.php with the values I want. But the question is: How can I access them? So for example, if I post the following data: content: "test", that I can write in PHP sth. like <?=$_POST['content'];?>... So how can I access the $_POST-Data from AJAX? Do I need to refresh the page or how does this work?
Thanks for your help
after exchanging I now got the question:
to access to your code you must use the callback of your ajax call
success: function(result){
$("#div1").html(result); // here you put the content that echoes your php inside your div1 on the actual page without reload
}
On the php side where the content is posted you must echo something that will be caught by this ajax call

How to display a json data from a existing url using ajax call

I Am new in working with json and jquery. I am trying to study the basics of json and jquery by working on some example. So I use existing json data in http://api.androidhive.info/contacts for my example. I want to display this data in my HTML page. My code is:
<html>
<head>
<title>jQuery Ajax Example with JSON Response</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked.");
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php
type: "GET",
dataType: 'json', // Choosing a JSON datatype
success: function (msg) {
alert("ajax worked.");
JsonpCallback(msg);
},
})
function JsonpCallback(json)
{
for (var i in json.contacts) {
$('#wines').append('contacts: ' + json.contacts[i] + '<br/>');
}
}
return false; // keeps the page from not refreshing
});
});
</script>
</head>
<body>
<form method="post" action="">
<button value="all" type="submit">Get!</button>
</form>
<div id="wines">
<!-- Javascript will print data in here when we have finished the page -->
</div>
</body>
</html>
can any one please give me some brief introduction to JSON and how it's working ?
Thanks in advance.
You are iterating the JSON wrong, in your case since you are using jQuery (as mentioned) you can use the $.each(json, callback); helper fron jQuery, you can see the documentation here Jquery $.each documentation
For an example implementation I've created this JSFIDDLE LINK
for you. Have a great day ahead. Don't forget that JSON means
Javascript Object Notation
It's an object.
$.each(jsonData.contacts, function(k, v)
{
console.log(v.name);
$('#name').append('<li>'+v.name+'</li>');
});
jQuery
Am try to study the basics of json and jquery
Is a Javascript library with lots of very usefull methods. If you want to create a dynamic website it is very recommended to look into jQuery. There are many site with great explanation on what jQuery can do. As far as your example is concerned: There is an issue when passing variables/data from one framework to another or even when simply storing data. Here comes JSON.
JSON
Or JavaScript Object Notation (JSON) is used to solve exactly that problem. What is basically does is take all the desired data (array, variable, object, string etc.) and writes it in a human readable and for other frameworks readable fashion. I use JSON to store data in files when no database is available or when passing data from one framework to another (like JS <-> PHP).
Your example code
What happens here:
$(':submit').on('click', function() { // This event fires when a button is clicked
alert("submitt worked."); // not yet
$.ajax({ // ajax call starts
url: 'http://api.androidhive.info/contacts/', // JQuery loads serverside.php --> this I don't know
type: "GET", // communication type
dataType: 'json', // Choosing a JSON datatype
success: function (msg) { // here, the whole content of the url is read, idealy it is in JSON format ofc
alert("ajax worked."); // hoorray
JsonpCallback(msg);
},
})
There is the serverside.php file that receives a GET command and returns HTML. All the HTML content is in JSON type (so no <stuff>, i.e. no actual HTML) and your success function returns that content in the msg variable. Typically you use something like
var obj = JSON.parse(text);
to convert the JSON data to Javascript variables. Read this here JSON in Javascript
JSONP
Now what if you want to do some domain crossing (as you suggested), then I strongly recommend to read this here What is JSONP all about? . It explains what JSONP is all about

Javascript Variable passing to PHP with Ajax

I've started working with ajax a little lately, but I'm having trouble with something I feel is incredibly simple: storing a JS variable in PHP.
Say I want to store a zip code (assigned with Javascript) and pass that to a PHP variable via AJAX: Why doesn't this work?
Keeping it simple for demonstration purposes, but this is the functionality I desire..
zipCode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});
});
zip.php:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
<?php
echo $_POST['zip_code'];
?>
</body>
</html>
An error: "Notice: Undefined index: zip_code" is all that is returned. Shouldn't "123456" be echo'd out?
You are supposed to put this:
<?php
// query database before echoing an associative array of `json_encode()`ed data if a response is needed
echo json_encode(array('zip_code' => $_POST['zip_code']);
?>
on a separate page, that is not an HTML page. AJAX just sends to that page, so you can use it and echo it out, making database queries before that, or what have you. Upon success you will see the result of your echo as the argument passed to the success method in this case if you used data as the argument the result for zip_code would be held in data.zip_code. Also, set your dataType:'JSON' in $.ajax({/*here*/}).
Here:
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST',
dataType: 'JSON',
success: function(data){
// in here is where you do stuff to your page
console.log(data.zip_code);
}
});
When you load the page, a call is being made to the server for zip.php, however that request is in no way linked to the page you're currently viewing.
If you look at the response to your ajax request - you'll see a copy of the page with the correct zip code echo'd
The actual answer then depends on what exactly you're trying to do (and a less simplified version of the code) to give you the best option.
The current setup you have doesn't make sense in practice
That is not how AJAX works. Thake a look at the example below. It will make an AJAX post to handle_zip.php and alert the results (Received ZIP code 123456)
start_page.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
This is just a static page.
</body>
</html>
zipcode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'handle_post.php',
data: {zip_code:zip},
type: 'POST',
success: handleData
});
});
}
function handleData(data) {
alert(data);
}
handle_post.php:
<?php
die ('Received ZIP code ' . $_POST['zip_code']);
As others have mentioned, it sounds like you're expecting the two bits of code to run at the same time. The reality is that:
zip.php will be parsed on the server (and resulting in the error)
Server will then serve up the HTML to the browser (which will have a blank body due to the $_POST not existing when the PHP was parsed)
browser will see the javascript .ready() and run that code
server will handle the POST request to zip.php, and generate the HTML you're expecting. It'll be returned in the AJAX response, but as you're not handling the response, nothing is shown in the current session. (you can see the POST response using any of the common web developer tools)
Remember, PHP runs on the server, then any javascript runs on the client. You're also missing the step of handling the response from the request you made in your javascript.
try this to give you better idea of what's happening.
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});.done(function(data ) {
console.log(data)
});
In your code, the server is creating the page first, so no javascript is run yet, therefore it creates an error because $_POST['zip_code'] doesn't exist. Then it sends this page to your browser and you can see that. At this point is when your browser executes the javascript, it sends the request again, now with POST data, the server should return the response of the request and you should be able to see it in the console.
You could make this 2 separate pages, one for viewing the page, and anotherone for processing the ajax request, or if for your application you want to do it in the same page, you would need an if statement to get rid of that error, something like
if(isset($_POST['zip_code'])){
echo $_POST['zip_code];
}

Categories

Resources