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.
Related
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.
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.
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.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
I'm trying to include JavaScript variables into PHP code as PHP variables, but I'm having problems doing so. When a button is clicked, the following function is called:
<script type="text/javascript">
function addTraining(leve, name, date)
{
var level_var = document.getElementById(leve);
var training_name_var = document.getElementById(name);
var training_date_var = document.getElementById(date);
<?php
$result = "INSERT INTO training(level, school_name, training_date) VALUES('level_var', 'training_name_var', 'training_date_var')" or die("Query not possible.");
?>
</script>
Is it possible?
PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.
What happens in a nutshell is this:
You click a link in your browser on your computer under your desk
The browser creates an HTTP request and sends it to a server on the Internet
The server checks if he can handle the request
If the request is for a PHP page, the PHP interpreter is started
The PHP interpreter will run all PHP code in the page you requested
The PHP interpreter will NOT run any JS code, because it has no clue about it
The server will send the page assembled by the interpreter back to your browser
Your browser will render the page and show it to you
JavaScript is executed on your computer
In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.
The only way to do what you are looking to do is either:
do a redirect to a PHP script or
do an AJAX call to a PHP script
with the values you want to be insert into the database.
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php $abc = "<script>document.write(jvalue)</script>"?>
</script>
<?php echo 'php_'.$abc;?>
You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data.
-don
PHP runs on the server. It outputs some text (usually). This is then parsed by the client.
During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.
If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).
You can do this by:
Setting location (GET only)
Submitting a form (with the FormElement.submit() method)
Using the XMLHttpRequest object (the technique commonly known as Ajax). Various libraries do some of the heavy lifting for you here, e.g. YUI or jQuery.
Which ever option you choose, the PHP is essentially the same. Read from $_GET or $_POST, run your database code, then return some data to the client.
I had the same problem a few weeks ago like yours; but I invented a brilliant solution for exchanging variables between PHP and JavaScript. It worked for me well:
Create a hidden form on a HTML page
Create a Textbox or Textarea in that hidden form
After all of your code written in the script, store the final value of your variable in that textbox
Use $_REQUEST['textbox name'] line in your PHP to gain access to value of your JavaScript variable.
I hope this trick works for you.
You can take all values like this:
$abc = "<script>document.getElementByID('yourid').value</script>";
You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.
I'm new to JavaScript and AJAX. My experience is mostly in PHP. How can you do a MySQL query from JavaScript without revealing in the View HTML Source of the web browser the connection information for the MySQL database such as the db user's password? Thanks!
You make your JavaScript request the information from a PHP script, which checks the user's login cookie (like any other page would) and queries MySQL, returning the information to the JavaScript in whatever form it needs (JSON, usually).
In this case you don't perform the actual database query from the JavaScript code. The fact that it's using AJAX doesn't move database connectivity to the client, it just allows you to request information from the server without refreshing the page (as well as potentially moving some of the UI logic to the client).
Your AJAX call would simply make a request to a PHP file in your website which could:
Render part of a page, where the JavaScript code from the other page which called it would insert that markup into the open page. Or;
Render data, usually in JSON format, which the JavaScript code from the other page would read and use.
So let's say you have PageA.php which has a bunch of HTML and JavaScript. You want some of that JavaScript to make an AJAX call to the server to get data. You'd create a PageB.php which behaves just like any other PHP code, but instead of using HTML between the PHP code fragments (or in echo statements) it would use JSON syntax to represent the data being returned.
The JavaScript code on PageA.php would make an AJAX call to PageB.php, read the data that's returned, and use it in the HTML of PageA.php entirely client-side without having to refresh PageA.php.