I can think of plenty of ways to use ajax to load information from my database. For example: http://www.w3schools.com/php/php_ajax_database.asp
However, I really want to separate my structure (HTML), behavior (JS/AJAX), style (CSS), and data (MySQL + PHP) to keep my website scalable.
The above example shows how to just paste in the HTML via AJAX into the existing HTML doc, but what if I have the HTML already and just want to modify HTML elements via ajax using one MySQL call?
For example
Say I have this structure (HTML)
<body>
<h1 id="first">First name here</h1>
<h2 id="last">Last name here</h2>
<h3 id="email">Email here</h3>
</body>
I currently use PHP to make a MySQL query,
"SELECT * FROM `user` WHERE `id` = ".$id;
And of course I could assign each field to individual PHP vars, $first $last, $email. But then when it comes to using jQuery or plain ol AJAX, how do I use this single MySQL statement and single GET request from AJAX to change <h1>, <h2>, and <h3> in the above example?
I know I can use jQuery selectors
$(document).ready(
$('#first').innerHTML = ?
...
)
But is there an elegant way to load values retrieved from PHP into jQ/js? (Let's assume I'm GETting the php doc via jQ/js).
A nice way might be to use JSON with selectors, so return this from your PHP script:
{
'#first': 'First name updated value',
'#last': 'Last name updated value',
'#email': 'etc.'
}
Then, when retrieving the results (don't forget to use 'json' as your dataType):
for(var x in data) {
if(data.hasOwnProperty(x)) {
$(x).html(data[x]);
}
}
Oh, and jQuery can do that for you too:
$.each(data, function(selector, newContent) {
$(selector).html(newContent);
});
Your PHP can return simple json, like the following:
[{ firstName: "Joe", lastName: "Smith", email: "joe#smith.com" }]
And in your ajax success callback, you can use jsRender to render your html, or in other words, "fill your html with data."
What this looks like...
HTML:
<body>
<div id="personContainer"></div>
</body>
<script id="personTmpl" type="text/x-jquery-tmpl">
<h1>{{=firstName}}</h1>
<h2>{{=lastName}}</2>
<h3>{{=email}}</h3>
</script>
in Ajax success callback:
$.ajax({
...
success: function(data) {
$("#personContainer").html(
$("#personTmpl").render(data);
); // where data is in the json format above
}
});
Similar example here: http://jsbin.com/ihuhep/3/edit
Related
I am a new user of ajax; so...
I am using ajax on a simple html page to access a php script to receive data, calculate results using data in an mysql table, and echo results in a div on the same page. My javascript statement to do this is:
$.post('ajax/phpscript.php', {
postuser:theuser,
postname:uans1
}, function(data) {
$('#outputdiv1').html(data);
}
);
The php echo output goes to a div on the main page called outputdiv1.
I got that part; no problem. Not sure exactly how it works, but it does work.
I would also like to echo output to a different div (which I will call outputdiv2) on the same page, using the php script. In my php script, How do I refer to or echo output this other div?
I guess I could have a second $.post statement in the javascript code, accessing a second php script. But that would force me to access the mysql database a second time. Doesn't seem efficient to me.
Is there a better way to do this?
Thanks.
HTML code is here:
theuser is defined earlier
<table width=400 align=center><tr><td>
There is a question here, with 2 possible answers:<p>
<form>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt1" value="answer 1" onclick="post1()"> answer 1<br>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt2" value="answer 2" onclick="post1()"> answer 2<br>
</form>
<div id="outdiv1">first response from php will go here, beneath the question.<br></div>
<script type="text/javascript">
function post1() {
var uans1 = "none"
if (document.getElementById("opt2").checked) {
uans1 = "answer 2"
}
if (document.getElementById("opt1").checked) {
uans1 = "answer 1"
}
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#ans1div').html(data);});
}
</script>
</td>
<td width=20%>
<div id="outputdiv2">
second response from php will go here, to the right of the question.<p>
</div>
</td>
</tr></table>
first response will not be the same as the second response.
You could use JSON to communicate and return an array. something like this in js
$.ajax({
url: 'ajax/phpscript.php',
method: 'POST',
data: {
postuser: theuser,
postname: uans1
},
dataType: 'JSON'
}).done(function(data) {
if ($.isArray(data)) {
$('#outputdiv1').html(data[0]);
$('#outputdiv2').html(data[1]);
}
});
And your php script should do something look like this
<?php
include('dbconnection.php');
$result = [];
//SELECT data for div1 (part you already have)
$result[] = $mysql_result_as_html_for_outputdiv_1; // In your case this would be a html string
//SELECT other data for div2
$result[] = $mysql_result_as_html_for_outputdiv_2; // In your case this would be a html string
header('Content-Type: application/json');
echo json_encode($result);
?>
An even more clean solution would be to just return the data as objects from php and make some templates in js suitable for your data.
You need to understand this: who write in the div is javascript, not php, cause you are using ajax. Ajax is a way to comunicate with php, and give a response. Now you need to handle this response with javascript.
If you want to put the same content in outputdiv1 and outputdiv2, you not need to post ajax again, only write it in two divs.
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#outputdiv1').html(data);$('#outputdiv2').html(data);});
if you want different data i suggest you think the system to get all result that you need in one post request and return it in a json format (see http://php.net/manual/es/function.json-encode.php), so you can handle better with JSON.parse() in client side.
i have this HTML / PHP code:
$notes.='<div class="note '.$color.'" ';
if($row["xyz"] == '') {
$notes.='style="left:45%; top:10%; z-index:0;"><h3 align="center">New Note</h3>';
} else {
$notes.='style="left:'.$left.'px;top:'.$top.'px;z-index:'.$zindex.'">';
}
$notes.=htmlspecialchars($row['text']).'
<a class="closeMessage">X</a><div class="addedby">'.htmlspecialchars($row['addedby']).'</div>
<span class="data">'.$row['sequence'].'</span>
</div>';
there are multiple containing different data from the database
i would like to use ajax to send data to a PHP page using GET, i currently have this:
$('.closeMessage').live('click',function(){
//alert("close");
alert($('span.data').html());
$.get('/includes/sticky_notes/closeMessage.php',{
sequence : $('span.data').html()
});
alert("close");
});
but its passing the incorrect sequence each time. its passing the sequence number of a different row
As your HTML code for the notes have several elements with the class 'data', when you call for $('span.data').html() you will always get the inner html of the first span with the data class.
You can traverse the dom tree and use something like the siblings function.
$(document).ready( function(){
$('.closeMessage').on('click',function(){
//alert("close");
this_data = $(this).siblings('.data').html();
alert(this_data);
$.get('/includes/sticky_notes/closeMessage.php',{
sequence : this_data
});
alert("close");
});
});
In this example we store the data in a variable this_data = $(this).siblings('.data').html(), so we refer to the element that was clicked - $(this) and then go down in the tree until the next element with the class data.
One last thing - consider to use $('.closeMessage').on instead of live as it has been deprecated - http://api.jquery.com/live/
I am failing hardcore with describing this but here it goes..
I have home.php, pretty much just:
<body>
<div id='leftColumn'>
<?php include ('includes/roomQuery.php')
</div>
</body>
Now,
roomQuery.php echos my sql column 'room_name' from table 'rooms' as follows:
echo "<td>$roomName</td>";
Any of the room links will take me to room.php and populate the page with more queries respective to $roomName via $_GET.
room.php is basically:
$get = $_GET['room'];
$query
while($row = $result->fetch_assoc()){
echo $query
This is working perfectly for what it is.
====================================
however, I am trying to make my site flow better, and have been trying out the jQuery .load function. So far I have changed roomQuery.php to:
echo "<td><button>$roomName</button></td>";
here is my jQuery to replace home.php #page with room.php #page:
$(document).ready(function(){
$("button").click(function(){
$("#page").load("room.php #page",function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("Success");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
});
When I click any of the buttons that roomQuery.php spits out, it replaces #page perfectly but I cannot grasp how/if I can send $_GET['room'] to room.php so that when #page is loaded, the information is still respective to the room I clicked on. If I change jQuery to
$("#page").load("room.php?room=CL%20124 #page"
Then #page is populated with the data specifically respective to room CL 124. Is it possible to post the button text that is output from roomsQuery.php to room.php #page when the button is clicked?
Yes, you can pass data into the .load() call as the second parameter.
Firstly, you need to work out how to get the room ID from the DOM into your jQuery call, maybe you could use a data attribute on the button element like this:
<button data-room-id="123">Click me</button>
Then use jQuery like this:
$("button").click(function(){
// define your room ID here, however you do it
var your_room = $(this).data('room-id');
$("#page").load(
"room.php #page",
{
room: your_room
},
function(responseTxt,statusTxt,xhr){
if(statusTxt=="success")
alert("Success");
if(statusTxt=="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
}
);
});
Edit: just noticed that you might actually be using the button's value as your room ID, if so, use this definition:
var your_room = $(this).val();
If you're expecting spaces or non-alpha numeric characters in this value, you might want to consider URL encoding it before you send it.
Iam adding html for input tag dynamically through enterPerson() and then calling onkeyup=changeOnType(this) which on echoing $results in autoInvit.php should display autocomplete, but WHY does my autocomlete code does not work,infact data shows if I alert it. can any one please help me out ?
Thank you in advance :)
header files for jquery and autocomplete:
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="//code.jquery.com/jquery-1.8.3.js"></script>
<script src="//code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
autocomplete in "main.php" :
<script>
function changeOnType(x){
$.post(
"autoInvit.php",
{
vals: $(x).val()
},
function(data){
$("#"+x.id).autocomplete( {source:"autoInvit.php" } );
//alert(data);
}
);
}
</script>
here's the dynamic html's php code in "invities.php":
<?php
echo '<input class="e" type="email" id="email" onkeyup="changeOnType(this)" autocomplete="on" role="textbox" aria-autocomplete="list" aria-haspopup="true" />';
?>
Here's my php file "autoInvit.php" which echos the result:
<?php
include("includes/connection.php");
$value = strip_tags($_POST['vals']);
$req = "SELECT email as name "
."FROM members "
."WHERE email LIKE '".$value."%' ";
$query = mysql_query($req);
while($row = mysql_fetch_array($query))
{
$results[] = $row['name'];
}
echo json_encode($results);
?>
Please help
There's no need to make the post request. Edit: There's no need to call a separate function or attach a listener to the input, just register the autocomplete plugin. This will need to be called once the DOM is ready, so you will need to wrap it in a ready function. This should be all the javascript you need:
$(function() {
$("#"+x.id).autocomplete( {source:"autoInvit.php" } );
});
What the user has typed will be passed with the request as the parameter term
From the jQuery docs for autocomplete:
String: When a string is used, the Autocomplete plugin expects that
string to point to a URL resource that will return JSON data. It can
be on the same host or on a different one (must provide JSONP). The
Autocomplete plugin does not filter the results, instead a query
string is added with a term field, which the server-side script should
use for filtering the results. For example, if the source option is
set to "http://example.com" and the user types foo, a GET request
would be made to http://example.com?term=foo. The data itself can be
in the same format as the local data described above.
Also, you'll want to be careful when passing content from the user directly to the DB. You can open yourself to SQL injection.
.net developer trying to do a php site for a friend, so far everything is going great but I was wondering if php has something like a textchanged event. Here is what I want to do, I want a drop down box to be appended with data retrieved from a database based on what the user enters in a textbox above(Using the text in the textbox as a parameter to retrieve data from a database and append it to the drop down without reloading the entire page.)
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
//Do stuff
}
The block off code above is in asp.net but i want to implement something similar in php.
That is not how php works. however you can make a ajax call like this with jquery:
<?php
//array, object or db result you use to fill your dropdown
$array = array('pipo', 'kees', 'klaas', 'klaas1', 'jan', 'meneerje', 'poep', 'hessel', 'kaas', 'ietsandersd', 'smit', 'cowoy', 'nog zo iets');
//if we want to search we search and only return the new found options
if(isset($_REQUEST['keyword'])){
$new_array = array();
foreach($array as $value){
if(strpos($value, $_REQUEST['keyword']) !== false){
$new_array[] = $value;
}
}
}
else{
$new_array = $array;
}
$options = '';
foreach($new_array as $key => $option){
$options .= "<option value='$key'>$option</option>";
}
$selectbox = "<select name='selectbox' id='drop_down'>$options</select>";
if(isset($_REQUEST['keyword'])){
echo $options;
}
else{
// with the \ we escape the "
echo "<html>
<head>
<title>ajax selectbox</title>
<script src=\"http://code.jquery.com/jquery-latest.min.js\" type=\"text/javascript\"></script>
<script type=\"text/javascript\">
$(document).ready(function () {
$('body').on('keyup', '.search', function(){
var data = $('.search').serialize();
$.post('ajax_selectbox.php', data, function (data){
$('#drop_down').html(data);
});
});
});
</script>
</head>
<body>
<input type='text' name='keyword' class='search' />
$selectbox
</body>
</html>
";
}
?>
explanation:
java script,
first we include the online jquery library, you can also download the library and include it from your own web server.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
// first we wait unit the html page is loaded
$(document).ready(function () {
//then we wait for a keyup event in the element with class="search" we use the css sector . for classes like .search
$('body').on('keyup', '.search', function(){
//when we type inside the .search textbox we serialize the element like a form would do. this takes the name and the value and puts it in a array.
var data = $('.search').serialize();
// then we post with ajax back to our php file or an other php file. its you own decision. the data variable is the serialized data form .search
$.post('ajax_selectbox.php', data, function (data){
// at least we use a calback for when the ajax event has finnest and we use the jquery html function to put the new options inside the drobbox with id="drop_down". we use the css id selector # to select the select box.
$('#drop_down').html(data);
});
});
});
</script>
note that I use jquery (and a lot of large players on the web use jquery) and if you know a little java-script the syntax can be disturbing.
In jquery we have a large set of methots we can use directly like:
$.post();
if you want to use the returned data from that function we create a calback function like:
$.post( function(param_ returned_by_parent_function){
//do stuf
});
An other way of using jquery and this is actually the idea behind it is query to a html element and then do stuff with it like this.
$('html_element_query').do_something_with_this();
of course this is just a basic basically explanation but maybe you get the idea.
You can use javascript onChange handler and send the current value to php via AJAX
https://developer.mozilla.org/en/docs/DOM/element.onchange
http://www.w3schools.com/ajax/
PHP does not know what happens on the client. If you want some events on the client to trigger actions, you have to code that yourself (usually in JavaScript).
PHP itself has no awareness of events happening on the front end. You can, however, plug the functionality (kind of) by using a mixture of Ajax and PHP. Ajax will watch for the events and PHP will process data sent to it from that Ajax.
I suggest using jQuery and checking out http://api.jquery.com/Ajax_Events/
I made a very simple PHP Event Dispatcher for myself, it is testable and has been used on my websites. If you need it, you can take a look.