Passing session variable from PHP using AJAX - javascript

I am currently using PhoneGap to make an app.
As we know, PhoneGap only allow HTML, CSS and JS to be used. Therefore, PHP cannot be used.
I have researched a bit and I found out that I can just put the PHP file in a remote server and use AJAX to call for the PHP file using the URL of the remote server.
But I cannot find a way to pass a session variable from the PHP to HTML. Passing session variable from PHP to PHP is easy.
However as there will not be PHP to PHP communication allowed in PhoneGap, I have to use PHP to HTML and then to PHP again.
Passing the session variable using AJAX back to the HTML might be complicated. This leads me into a dead-end.
Any clues on how to solve this problem? If my explanation about my situation is not that comprehensible, please feel free to comment. Thanks.

You should be able to echo data back from an ajax call.
Ajax call:
$.ajax({
url: "url_to_file",
type: "get",
success: function(data){
// do stuff with the data
},
error:function(){
alert("ajax call error");
}
});
PHP file:
<?php
echo $_SESSION['varible'];
?>
I would probably use JSON instead of echoing plain text.

Related

Passing Variables References to PHP from Javascript via AJAX

I have an idea for "using", or "referencing" PHP variables in Javascript. This would apply to a webpage that will send an email. A simplified example is shown below. Note: this is called via AJAX, so it is not the case that I am trying to call a PHP variable from a script that has already been executed.
The javascript will include a "$midSection" string in the body of the email to be sent, and then send the entire body to a PHP script. The PHP script will store this String, create and assign a value to $fmidSection, and send the body string in an email. If it works, the resulting email would include the main body sent from the client side, with an inserted "midSection" in the middle of the email (perhaps, depending on the person's name and info stored in a database).
It seems to me that this should work, given my understanding of PHP. However, it also seems to me that this will open a window for attack similar to an SQL injection (where' perhaps, we can trick the script to assign a different value to $midSection, for example). Has anyone taken this approach, and if so, can you validate whether this will work, and open up any security holes?
Thank you.
EDIT: The application is for a mailing list, not a contact form. I have an admin panel which allows me to send emails to the mailing list, and I am thinking that this is a good way to include variables from the PHP in a similar way that I would on the PHP script, by putting the $var in the string itself. I understand how passing variables from JS to PHP works, I want JS to reference a PHP variable, essentially. I am not using this for validation purposes, I am using this for an easy way to insert information, rather than doing string parsing manually. The variable will be created and stored server side on a script that I have created.
Also, the JAVASCRIPT will be performing an AJAX call on the PHP script. Therefore, the Javascript will be executed first. I'm essentially sending an email template to the PHP, where the PHP will loop through the email list and add information dynamically, such as first name, last name, etc. Instead of doing string processing, I'm thinking of sending "Hello, $firstName $lastName....." essentially, in the hopes that the PHP script will insert the variable information.
From the comments above I can see what you're trying to do, but it won't work.
Consider the following code:
$(document).ready(function() {
$.ajax({
url: 'ajax.php',
data: {'name' : 'andy'},
method: "POST",
}).done(function (data) {
console.log(data);
});
});
This is ajax.php:
<?php
echo $_POST['name'];
?>
All you're doing in the javascript is making a POST request to ajax.php. It's able to give you the output "andy" in your console because you're passing this data string - not a reference to anything. So far, so simple.
Now imagine if you change data: in the jquery to the following:
data: {'name' : '$var'}
In your console you would get a string "$var".
Even if you had this in ajax.php:
<?php
$var = 'foo';
echo $_POST['name'];
?>
You will never get the output "foo".
This is because PHP and javascript are completely separate. So if you pass $var, it's just going to treat it as a string. There's no way of asking javascript to mean a PHP variable or some reference. You have to pass the data itself.
In the case of your application, what you'd typically do is pass something in the ajax request that PHP can refer to (like the primary key ID for a particular record). PHP would then generate all of the required content and send it back to the browser. If you need to do things with a template, str_replace is your friend.
I want JS to reference a PHP variable
Impossible.
They are different programs running on different computers. By the time the JS starts running, the PHP program will have finished and its variables will no longer exist.
The closest you could come would be to store the data somewhere (e.g. a database) with an identifier. Then send that identifier to JS. Then, if you want to get the data in JS, use Ajax to request it.

Save file to source directory with Javascript or jQuery without PHP?

I'm just a front-end developer and I have no knowledge in PHP. Is there a way in JavaScript or jQuery that I can save data (something like a string) to the source directory?
Javascript is a client side programming language so it can't actually make changes to the server alone. The easiest way to achieve this would be using PHP.
What exactly are you trying to save and in what format do you want to save it? If you are saving a string to a text file for example, use AJAX to send it to a php file:
$.post( "saver.php", { string: myString})
.done(function( data ) {
//Code to be executed when complete
});
Then in a php file called saver.php
<?php
if($_POST['string']){
echo file_put_contents("myfile.txt",$_POST['string']);
} ?>
as a very basic example.

Connecting DB and Ajax (no php)

I have to do a project as exam and I'm getting really troubled with this topic. My project is about a photoblog like Instagram. As in Instagram I want to get values from my DB and posting after the page has been loaded. So I've understood I need help from AJAX but every example I've found is about using PHP and I can't for my projects. Tools I can use are: HTML, CSS, XML, JQuery, AJAX, Servlet/JSP, DOM and JSON. I've found examples in PHP and I've tried to "translate" into Servlet/JSP but it (obviously) didn't work. This is my idea:
$.ajax({ type: "GET",
url: "Jspfile",
success : function()
{
// Here I would like to use the return value from db that I got by a servlet/jsp file
}
});
I'm using MySQL aS DB
You'll have to connect your Java applet to the database, then serialize the data from whatever object type your DB driver uses to JSON.
You then have to render the JSON in your "Jspfile" URL. Then, you just have to parse the JSON in your success / complete function in the jQuery request.

JS and PHP - Load php data after signal from js without sending a postback

Alright so basically I have a flash login, which I handled to work with JS using ExternalInterface. I want the php to load only when the user has logged in, how is it possible to do this without sending a new postback (reloading the page)?
What I basically want is: the JS already appears once the user has logged in. I want it once clicked to execute a MySql query, get the data and show the user without reloading the page.
I know that's AJAX but I really don't know how to do it - I'm not familiar with php, I also don't know how I can run the php when a function is called in JS.
Best regards,
iMix
You can use jquery, it would be a quick and practical solution.
function login(){
$.ajax({
type: "POST",
url: "your_login_script.php",
data: { username: "thatuser", password: "thatpwd" }
}).done(function( result ) {
alert(result);
});
}
You'll want to make an XMLHttpRequest to another php file which returns the data. Then, with JS, parse the data from whatever format you returned it in (I recommend JSON), and update the HTML.
Since you'll want the data only to be returned if the user is logged in, you probably want to send the username/password over an encrypted connection, in the body of a post request, then check in the php file if they're valid.
Yes, you need to use AJAX.
Here is an outline of the simplest procedure:
Send a request to the server to run the PHP script in the background, without reloading the current web page.
The PHP script will do the required query and format the result as HTML. It should not generate a whole page ... just a DIV or a TABLE tag with the data you want.
Your Javascript will receive the HTML fragment and insert it into the current page.
Here is the barest, most essential code to get the job done.
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("targetDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "somescript.php", true);
xmlhttp.send();
You should read up some on AJAX if you're going to put anything into public production. I also highly recommend using jQuery or one of the other Javascript libraries. They have much better abstractions for this kind of thing than anything you're likely to cook up yourself.

how to use mysql query inside the javascript, php

I have a JavaScript function onLoad a PHP page. Inside this JavaScript function, How can I use mysql query? Please Help me..
You can't really do that. JavaScript code runs in the browser, which (presumably) doesn't have access to your database server, and it doesn't have facilities for talking to remote databases anyway.
What you'd typically do is perform the SQL query from your PHP code, running on the server, and put the results into the page that it sends to the browser. If you want to use the results in JavaScript, you can make your PHP code generate a JSON string in a <script> tag so that the JavaScript code can just access a global variable that contains the data.
Or, you can use AJAX to load the data separately. This involves another HTTP request to a PHP page on the server, which runs the SQL query and sends back the results.
$(window).load(function() {
$.ajax({
method:'POST',
url:"ajax_page.php?branchcode="+branchcode,
success:function(data){
},
error: function (error) {
alert("Failed to load.. Kindly try again!!");
}
});
});
I have solved by using this AJAX, jQuery code.

Categories