I'm developing a parents evening booking system as part of my A level programming project, but I've just gotten stuck.
I'll try explain the project the best I can in this post, so I can give you guys a clear picture of what the application does.
So far:
I have created a sort of language selector function with php, which gets the users language selection before logging in based upon a cookie. Here's the code for the script (Yes, very messy right now, but i'll fix it later on):
function check_language() {
//directory name for the custom defined languages.
$dir = 'languages';
//set a default language
$default = 'english';
//make sure that we have a language selected...
if (!isset($_COOKIE["lang"])){
//if there is no cookie set, set one.
setcookie("lang", "english", time()+3600*24*365);
}else{
$lang = ($_COOKIE["lang"]);
}
//build the path string.
$path = $dir."/".$lang.".php";
if (file_exists($path)) {
//return the selected language pack directory.
return $path;
}else{
//protect the server, by returning the default language path...
return $dir."/".$default.".php";
}
}
Whenever I want my PHP script to access language files, I call the function I have created and then include the language file on the page like so:
$lang = check_language();
include_once($lang);
english.php file...
$txt['languagename'] = "English";
//text for the index page...
$txt['titletext'] = 'Parents evening booking system';
$txt['welcometext1'] = 'Welcome to the parents evening booking system for ';
welsh.php file...
$txt['languagename'] = "Cymraeg";
//text am y tudalen index...
$txt['titletext'] = 'System bwcio noson rhieni';
$txt['welcometext1'] = 'Croeso i system bwcio noson rhieni ';
So for example, if the users cookie contains 'welsh', the file welsh.php would be included, and I would have access to an associative array ($txt), with the supplied translations.
That part of my script works perfectly so far.
Now i'm coding the admin page, and I need an option to be able to add a school year to the database through the admin panel.
This is where i'm a bit confused on what to do, as the string ('year 10' for example) would be 'blwyddyn 10' in welsh. So this means I would need to add another element to the associate array for all language files with a string for the required language so it could be accessed in the script. (if this makes any sense at all).
I have created a table in the database for all languages like so:
languageid name filename
1 English english.php
2 Welsh welsh.php
Then I wrote this code to connect to the database and create an input box for each language in the database, along with a "translation id key" input box.
include'/inc/functions.php');
ConnectToDB();
$query = "SELECT * FROM languages WHERE 1";
$result = mysql_query($query);
$languages = array();
while($row = mysql_fetch_assoc($result)){
$languages[] = $row['name'];
}
echo 'Translation key id: <input type="text" name="languagetermkey"/>';
echo '</br>';
foreach($languages as $item){
echo 'Year name ('.$item. " string):";
echo '<input type="text" name="'.$item.'String'.'"/>'; //e.g "EnglishString"
echo "</br>";
}
Now if I wanted to add the terms above (the text from both input boxes) into my language files ("english.php" and "welsh.php") how would I go about sending an array with an ajax post request?
Previously I have been using this code, but I guess it won't work for what I want to do this time :(
$.ajax({
type: 'post',
url: 'add_class.php',
data: 'classname=' + "test",
error: function(){
alert('There was a problem adding the class !');
},
success: function() {
alert("Class has been added successfuly");
}
});
Is this the right way to go about doing this sort of thing ? If not, can somebody guide me towards the right direction on what to do? i'm just a bit confused and this is my first time using jQuery.
I know this post is long, and I do appreciate people's efforts for reading the whole thing.
Thanks in advance for any replies (Y)
For the bit about sending the array with AJAX, you can serialize a form and pass that, meaning you can access it just as if it was a normal POST from PHP.
$.ajax({
type: 'post',
url: 'add_class.php',
data: $('#formID').serialize(),
error: function(){
alert('There was a problem adding the class !');
},
success: function() {
alert("Class has been added successfuly");
}
});
For the "Year 10", you can use sprintf or vsprintf like this - example showing both sprintf and vsprintf.
$year = 'Year %d';
$yearWelsh = 'Blwyddyn %d';
echo sprintf($year, 10) . ', or in Welsh, we say ' . vsprintf($yearWelsh, array(10));
If I understand correctly, you want to change the language cookie when a new language is selected. You can use jQuery to set this cookie and then load the page. Php can then select the right language file.
Of course there are numerous other ways to do the same thing. Hope this helps though.
$.ajax is a more complicated though valid method to send an ajax request via jquery. You are looking for something like this - jQuery getJSON or jQuery get. Scheme is the same:
$.get('{queryURL}, data, function(response) { /* do something with the response */ });
The data variable may be an array, object or string created by jQuery's form.serialize().
Related
I'm beginning to work with AJAX, and I'm struggling with the next few things.
I'm working in Wordpress, with custom tables.
By the way, that's why the global $wpdb is there.
First, I have a Select, when you choose an option, the ID value will get stored in a variable in jQuery. This is done by the
onchange="selectRequest(this)"
global $wpdb;
$Estado = $wpdb->get_results("SELECT * FROM cor_estado;");
?>
<p>Busqueda por Estado</p>
<select class="select" id="estado" name="estado" value="" type="text" onchange="selectRequest(this);">
<option value="" disabled selected>Seleccione un estado...</option>
<?php
foreach ($Estado as $Estados ) {
echo "<option value='".$Estados->estado_id."' type='text'>".$Estados->nombre_estado."</option>";
}
?>
</select>
The Select will fill up with the id on value and the name.
This is my jQuery, but I'm having a problem here, if I leave everything on the jQuery(document).ready(){CODE HERE}, the Function selectRequest(id), won't work at all, I don't know if that has anything to do with the way that I am getting the id from the select.
Here it changed, now I am trying to receive HTML, I created the complete table on "table.php", and now I am trying to get it back
<script type="text/javascript">
function selectRequest(id){ // id of select
var selectVal = jQuery(id).val(); // currently selected
selectVal = selectVal.toString();
alert(selectVal);
jQuery.ajax({
type:"POST",
url:"<?php echo get_template_directory_uri(); ?>/table.php",
dataType: "html",
data:{selectVal:selectVal},
success:function(resultHtml){
jQuery("#resultado").html(resultHtml);
},
error:function(resultHtml){
alert("What follows is blank: " + data);
}
});
}
</script>
my PHP is like this at the moment, one big change was in the WHERE, since I am using an INNER JOIN, I needed to specify on which table the "estado_id" was going to be, since Wordpress uses table prefix, it was necessary to add it in this place too.
Like I said before, I decided to build the table here, and send it to AJAX with an echo, I created $table, and each time something was created inside the table, I added it with ".=".
Testing this inside the table.php without the "If(isset($_post['selectVal']))", and having an static ID it worked on the table.php document, but if I echo $table, I get nothing on AJAX, it appears as blank.
<?php
//table.php
global $wpdb;
if(isset($_POST["selectVal"])){
$Estado_id = $_POST["selectVal"];
$Estado = $wpdb->get_results("SELECT * FROM cor_municipio INNER JOIN cor_estado ON cor_municipio.estado_id = cor_estado.estado_id WHERE cor_estado.estado_id = $Estado_id;");
$table = "<table>";
$table .="<thead>";
$table .="<tr>";
$table .="<th>Municipio</th>";
$table .="<th>Estado</th>";
$table .="</tr>";
$table .="</thead>";
$table .="<tbody>";
foreach ($Estado as $row) {
$table .="<tr>";
$table .="<td>".$row->nombre_municipio."</td>";
$table .="<td>".$row->nombre_estado."</td>";
$table .="</tr>";
}
$table .="</tbody>";
$table .="</table>";
echo $table;
}
?>
This is the HTML div where I want to display the echo $table content. At the moment if I select an option, the only thing that happens is that the P element disappears.
<div id="resultado">
<p>Estado Seleccionado</p>
</div>
The new problem is receiving this echo $table and displaying it where AJAX receives it.
instead of receiving data in JSON format, use HTML formatted data & replace your data directly in table. Using that your base issue "the amount of information in them will be different on each select option" will be resolved.
There's not a fixed rule... Sometimes is faster to create the html in the php and return it formatted so you can show it directly and sometimes is better to return raw data and handle it in javascript/jquery.
If the data you get from the ajax request is just for showing and you don't need to modify anything that depends of other elements in your current view, I will format the html response directly in the php. If you need to change something, then maybe I will go with JSON.
In your ajax request you establish JSON as the data format, so the response in your PHP has to be JSON. You almost have it. Uncomment the foreach but instead of independent variables ($info1, $info2) create an array with the fields you need for your response, and set key names. For example...
$response = array();
foreach ($Estado as $row) {
$response['municipio'] = $row->nombre_municipio;
$response['estado'] = $row->nombre_estado;
.....
}
Once you have the array created, convert it to JSON and return with...
print_r(json_encode($response));
Then, in your jquery ajax success function you can access each field with...
data.municipio or data['municipio']
data.estado or data['estado']
...
I hope it helps
So, the basic problem here was that I was following the steps to do this using the tools (JS, PHP, HTML and CSS) outside the Wordpress environment, this was the issue. I'm still solving some aspects about my AJAX request, I will try to update this answer as fast as I can.
In this Wordpress Codex entry, they explain it in detail.
Basically Wordpress has it's own way of using AJAX, so no matter if this 'looked' correct to me, the Wordpress site wasn't going to display anything from it.
Here is the solution that I used to solve my problem.
<!-- language: lang-js -->
UPDATED CODE
jQuery(document).ready(function() {
jQuery('#estado').change(function() {
var selectVal = jQuery('option:selected').val();
selectVal = selectVal.toString();
jQuery.ajax({
url:"/cors/wp-admin/admin-ajax.php",
type:"POST",
data:{action:'my_action', selectVal: selectVal},
success:function(data){
jQuery("#municipio_result").hide(500);
jQuery("#municipio_result").removeData();
jQuery("#municipio_result").html(data);
jQuery("#municipio_result").show(500);
},
});
});
});
STEP #1
/wp-admin/admin-ajax.php //will be the URL for all your custom AJAX requests.
This is absolutely necessary, because this document verifies the AJAX 'actions', and points them to your functions.php
STEP #2
data:{action:'your_action_name', val1: 1, val2: 2 ...}
The first variable that you have to send will always be action, the value can be the anything you want.
As I said earlier, admin-ajax.php looks for the variable action when it receives an AJAX request from any file, it will look for action, once it finds it, it will redirect it to the functions.php file located inside your_theme folder.
STEP #3
Inside you functions.php file, you will add the PHP code as a function, like this:
<!-- language: lang-sql -->
function selectEstado(){
global $wpdb;
if(isset($_POST["selectVal"])){
$Estado_id = $_POST["selectVal"];
$Estado = $wpdb->get_results("SELECT * FROM cor_municipio INNER JOIN cor_estado ON cor_municipio.estado_id = cor_estado.estado_id WHERE cor_estado.estado_id = $Estado_id;");
$table = "<table>";
$table .="<thead>";
$table .="<tr>";
$table .="<th>Municipio</th>";
$table .="<th>Estado</th>";
$table .="</tr>";
$table .="</thead>";
$table .="<tbody>";
foreach ($Estado as $row) {
$table .="<tr>";
$table .="<td>".$row->nombre_municipio."</td>";
$table .="<td>".$row->nombre_estado."</td>";
$table .="</tr>";
}
$table .="</tbody>";
$table .="</table>";
echo $table;
wp_die();
}
}
add_action('wp_ajax_my_action', 'selectEstado');
add_action('wp_ajax_nopriv_my_action', 'selectEstado');
STEP #4
Inside your functions.php file you will create a function, can be called whatever you want, for example 'your_function_name'.
To access easily to the database, Wordpress uses the variable $wpdb, by including the line like this global $wpdb; now you can use it to access the database without any problems.
Now you have to check if the values after action got there, the if(isset($_POST)) will take care of it. To check the Database, you use the $wpdb->get_result("");
Basically what I am doing with the INNER JOIN, is checking a column name, and checking where the two tables match, and then pulling the rest of the columns that the element on the table has in "cor_municipio" and "cor_estado".
(In this code I am using JOINS, if you want to know more about them, I'll leave a link below)
Here they explain JOINS with Venn diagrams
Then I created a variable that each time a part of the table was created, it was being added to it.
You echo your data, and don't forget "wp_die();"
STEP #5
This is the last part to have your AJAX request working on Wordpress.
The next two lines are very important for it to work, this is the action that admin-ajax.php is looking for, and it's here that it references it's value, these lines look like this for every new AJAX request you need to make:
add_action('wp_ajax_', '');
add_action('wp_ajax_nopriv_', '');
this is the "default" way the lines are written, but you will need to complete them with two things.
The action value you used in the AJAX request, in my case is 'my_action', or in this example 'your_action_name'.
The second value is the name of the function created inside your functions.php file.
It will end up looking like this for me:
add_action('wp_ajax_my_action', 'selectEstado');
add_action('wp_ajax_nopriv_my_action', 'selectEstado');
Using the value of 'your_action_name' and 'your_function_name':
add_action('wp_ajax_your_action_name', 'your_function_name');
add_action('wp_ajax_nopriv_your_action_name', 'your_function_name');
The first line is for logged in users, and the second one is for visitors, if you want to display something different for logged in users and another one for visitors, you will need to create a function for each of them, and just use one attribute.
add_action('wp_ajax_your_action_name', 'your_function_name1'); // for registered users
add_action('wp_ajax_nopriv_your_action_name', 'your_function_name2'); // for visitors
Again, this is PHP code written in admin-ajax.php, if you want to look deeper into it.
I already found out my problem, when I was sending the data on the first time I was using:
data:{action:'my_action', selectVal: 'selectVal'},
Basically what I was sending to Wordpress on selectVal, was the string
selectVal
So when my function tried to find the id based on the receiving data, it wasn't going to find anything, because it was a string with those letter.
SOLUTION
jQuery(document).ready(function() {
jQuery('#estado').change(function() {
var selectVal = jQuery('option:selected').val();
selectVal = selectVal.toString();
jQuery.ajax({
url:"/cors/wp-admin/admin-ajax.php",
type:"POST",
data:{action:'my_action', selectVal: selectVal}, // The right way to send it
success:function(data){
jQuery("#municipio_result").hide(500);
jQuery("#municipio_result").removeData();
jQuery("#municipio_result").html(data);
jQuery("#municipio_result").show(500);
},
});
});
});
What I am sending now is the value, and now my AJAX success:function, receives the complete table, I also changed the jQuery code, because in the first example, when adding ".hide() or .show()", it was sending multiple errors.
To add conditions by user role you can edit the admin-ajax.php to make it simpler for all the AJAX requests.
I know is way too long, but if you were having some trouble, I wanted to explain all the different elements that are used, to make it easier to understand what is happening with AJAX in Wordpress.
NOTE - This is a edited snippet. This is testing at the moment and will be improved after.
I'm aiming to learn oop PHP now I got a good understanding of procedural. I'm stuck on sending this Ajax request to my php file.
Html File
<script>
$("#Question").click(function() {
flag = 1;
uid = "<?php echo $uid ?>";
var dataQuestion = {
uid,
flag,
ImageOne: $("#Image1").val()
};
//Post with AJAX
$.ajax({
type: "POST",
url: "../View/class.user.php",
data: dataQuestion,
perform: "QuestionsFunctions",
success: function(Returned){
$(".NotBoxSmall").text("Updated");
$(".NotBox").text("Updated");
flag = 0;
console.log(Returned);
},
error: function(){
$('.NotBox').text("Issue With Site");
$('.NotBoxSmall').text("Issue With Site");
}
});
});
</script>
Php file
<?php
public function QAsk(){
if($_POST['flag'] == 1){
$Image1 = $_POST['ImageOne'];
$uid = $_POST['uid'];
$insertsqlQ = "UPDATE UsersData
SET Image1 = '$Image1'
WHERE uid = $uid";
$resultquestion = mysqli_query($this->db,$insertsqlQ) or die(mysqli_connect_errno().json_encode("Data cannot inserted"));
return $resultquestion;
echo json_encode("Question Updated");
}else{
echo json_encode("Question NOPE");
return false;
}
}
?>
The id sends and iv'e tested this not within the public function and it appears to be fine. The request send back is blank, outside of the function it's the error log.
The issue is it says questions have been updated but no data has been added to the database.
jQuery must be initialized after the DOM ( document object model ).
How should I initialize jQuery?
I'd suggest some tips:
1 - Make the id names lower case #name_of_element
2 - Grab a OO PHP book and try to practice just this, run tests using curl for instance and make your database rules work before going into the client (html, js, css)
3 - Grab a jQuery book and run tests with mock data just printing a array from PHP. At the beginning is easier study stuff separated.
4 - '$Image1' is a varchar rather than the variable $Image1. Remove the quotes
I'm very new to php and SQL so i'm really sorry if this is very trivial.
My site has multiple divs with table names inside it. The HTML is of the form:<p class="listname">(table name)</p>
I am trying to write a function so that when a user clicks on a div, the function gets the text using innerHTML and the contents of that particular table are shown.
The jquery function i wrote is:
$(document).ready(function(){
$(".listname").click(function(){
var x=($(this).html()).toLowerCase(); //this assigns the text in the class listname to the variable x
console.log(x);
$.ajax({
url: 'http://localhost/fullcalendar/events.php',
data: {name:x},
type: "GET",
success: function(json) {
}
});
});
});
And my PHP code is:
<?php
include 'ChromePhp.php';
ChromePhp::log('php running');
$json = array();
if($_POST['name']!=null)//check if any value is passed else use default value
{
$table=$_GET['name'];
ChromePhp::log($table);
}
else
{
$table= 'event';
ChromePhp::log($table);
}
$requete = "SELECT * FROM `$table` ORDER BY id";
try {
$bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($requete) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
When i first load the website, the default value for $table is used in the query, and data is retrieved. However, when i try clicking on a div, the correct value is passed to php and assigned to $table (i checked in the console) but the data displayed is of the default table i.e 'event' table.
How can i fix this?
PS: all my tables are in the same database.
You're checking the POST data:
if($_POST['name']!=null)
But using GET data:
type: "GET"
So the $_POST array will always be empty and your if condition will always be false. You probably meant to check the GET data:
if($_GET['name']!=null)
Also of note are a couple of other problems in this code:
Your success callback is empty, so this AJAX call isn't going to actually do anything client-side. Whatever you want to do with the returned data needs to be done in that success function.
This code is wide open to SQL injection. It's... very unorthodox to dynamically use table names like that. And this is probably an indication that the design is wrong. But if you must get schema object names from user input then you should at least be taking a white-list approach to validate that the user input is exactly one of the expected values. Never blindly execute user input as code.
Ok so, some context. My college started doing some "learning on the job" type classes, and it's becoming a pain because it's like an internship without any sort of capacitation. Just my luck I was assigned a project I'm barely prepared for.
Right now I've been asked to join together an old Jamit Job Board with the login system of the place. Basically verify first if the user exist in the test database, then check if they exist in the local jobboard database. The problem is I don't have any ajax experience since it's not a topic we have touched in my classes. Sad, I know.
I was trying using cURL but was told by the supervisor it wouldn't work.
public function validar_request($Username,$Password) {
$Username = ($_REQUEST['username']);
$Password = md5(stripslashes($_REQUEST['password']));
function httpGet($url,p){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
$respuesta1 = httpGet("http://www01pruebasweb.fod.ac.cr/upe/templates/interfaces/ConexionFramework.php?procedimiento=nombreUsuarioExiste&username=".$Username);
The URL will return a 1 is the user exists in the testing database, 0 if not. I was thinking on doing a series of If else that if response = 1, then proceed to login, else donĀ“t since its like a 3 step verification process. First if the user exists, then if the password exists, and lastly if both tables in both databases match.
Response I get in the browser looks like this.
If the user usuario_01 exists then I should get a one. The idea me and a teammate had was to use curl to store the 1 into a variable in php and compare it but it's not working. Specially with the mess that is, for me, the other code for logging of Jamit. I mainly have experience with Java, not web development so as you can understand I'm very overwelmed.
I was trying to contact support from Jamit to see if they had any help, but they aren't active since 2013. Though not sure how much help they would be.
Not sure if necessary but part of the code for logging of Jamit is this
function validate_candidate_login($login_page='') {
global $login_output;
if ($login_output) { echo $login_output; return; } // this function was buffered
if ($login_page=='') {
$login_page = JB_BASE_HTTP_PATH.JB_CANDIDATE_FOLDER."index.php";
}
global $label;
$Username = ($_REQUEST['username']);
$Password = md5(stripslashes($_REQUEST['password']));
$sql = "Select * From users Where Username='".jb_escape_sql($Username)."'";
$result = JB_mysql_query($sql);
// init $row
if (mysql_num_rows($result)==0) {
$row = array();
} else {
$row = mysql_fetch_array($result, MYSQL_ASSOC);
}
JBPLUG_do_callback('val_can_set_pass', $Password); // Note for Plugin authors: Password is passed by refrence. Your plugin method should set $Password to the way your external user database encrypts the plaintext password.. eg $Password = md5($_REQUEST['password']); for phpBB
JBPLUG_do_callback('val_can_login', $row); // Note for Plugin authors: $row argument is passed by reference, which is the row of your users table. The row is populated if username/pass are valid, $row['Username'] and $row['Password'] are set for the code below and should come from your external database. You may also set $row['Validated'] too
if ((!$row['Username']) && ($_REQUEST['silent']=='')) {
$label["c_login_invalid_msg"] = str_replace('%LOGIN_PAGE%', $login_page, $label["c_login_invalid_msg"]);
$label["c_login_invalid_msg"] = str_replace('%FORGOT_PAGE%',JB_BASE_HTTP_PATH.JB_CANDIDATE_FOLDER."forgot.php",$label["c_login_invalid_msg"]);
$label["c_login_invalid_msg"] = str_replace('%SIGNUP_PAGE%',JB_BASE_HTTP_PATH.JB_CANDIDATE_FOLDER."signup.php",$label["c_login_invalid_msg"]);
echo '<p style="text-align:center; ">'.$label["c_login_invalid_msg"]."</p>";
} else {
if ($row['Validated']=="0") {
$label["c_login_notvalidated"] = str_replace('%BASE_HTTP_PATH%', JB_BASE_HTTP_PATH, $label["c_login_notvalidated"]);
echo '<p style="text-align:center; ">'.$label["c_login_notvalidated"].'</p>';
} else {
if (($Password === $row['Password']) || ((JB_ALLOW_ADMIN_LOGIN=='YES')&&(JB_ADMIN_PASSWORD===$_REQUEST['password']))) {
JBPLUG_do_callback('val_can_login_sync', $row); // Note for Plugin authors: Initialize $row with a Jamit user row. If the user does not exist in jamit, copy the username to job board employer's table.
JBPLUG_do_callback('val_can_login_set_session', $row); // Note for Plugin authors: set session variables for your external database (successful login)
JB_set_candidate_session($row); // set session for the candidate
$label['c_login_welcome'] = str_replace ("%FNAME%", JB_escape_html($_SESSION['JB_FirstName']), ($label['c_login_welcome']));
$label['c_login_welcome'] = str_replace ("%LNAME%", JB_escape_html($_SESSION['JB_LastName']), ($label['c_login_welcome']));
$label['c_login_welcome'] = str_replace ("%USERNAME%", JB_escape_html($_SESSION['JB_Username']), ($label['c_login_welcome']));
if (isset($_REQUEST['page'])) {
$label['c_login_welcome'] = preg_replace('/index\.php/i', htmlentities($_REQUEST['page']), $label['c_login_welcome']);
}
if ($_REQUEST['silent']=='') {
echo '<p style="text-align:center; ">'.$label["c_login_welcome"].'</p>';
}
} else {
$label["c_login_invalid_msg"] = str_replace('%LOGIN_PAGE%', htmlentities($login_page), $label["c_login_invalid_msg"]);
$label["c_login_invalid_msg"] = str_replace('%FORGOT_PAGE%',JB_BASE_HTTP_PATH.JB_CANDIDATE_FOLDER."forgot.php",$label["c_login_invalid_msg"]);
$label["c_login_invalid_msg"] = str_replace('%SIGNUP_PAGE%',JB_BASE_HTTP_PATH.JB_CANDIDATE_FOLDER."signup.php",$label["c_login_invalid_msg"]);
if (strpos($login_page, 'apply_iframe.php')!==false) {
$label["c_login_invalid_msg"] = str_replace('_parent', '_self', $label["c_login_invalid_msg"]);
}
echo '<div style="text-align:center;">'.$label["c_login_invalid_msg"].'</div>';
}
}
}
}
Ok cool - per the comments you're looking to get started with AJAX (Asynchronous Javascript And XML). I would highly recommend linking jQuery to your html page to get started - it will make AJAX calls MUCH easier.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Awesome, now we have jQuery loaded, which allows you to make an ajax call with a simple function.
So now we need to get values from the browser to the server. How do we do that? There are 2 approaches I would recommend:
1 - Use JSON (Javascript Object Notation) to send data to the server with key/value pairs. PHP is great for working with JSON.
2 - Serialize a form using jQueries $(formElement).serialize() function. This turns forms into key/value pairs and you can then receive the data using PHPs $_POST['keyOfFormField']
So I'm going to assume you're going with the JSON approach, which is always preferable in my opinion.
If you're unfamiliar with javascript, JSON format looks like this:
var jsonExample = {'Im a key': 'and im its value'};
This is how you represent an object literal in javascript, and we can send these to the server and store them in an associative array in PHP.
So, on to the ajax call. I will leave it up to you to research ways of getting your data into JSON format. It should be really simple.
In jQuery, an AJAX call looks like this:
$.ajax({
url: 'urlOfServerFile.php',
async: true,
data: JSON.stringify({'Im a key': 'Im its value'}),
type: "POST",
datatype: 'json',
success: function (json) {
json = JSON.parse(json);
//The server sent you back some data, do something with it!
},
error: function () {
alert("Please check your internet connection and try again");
}
});
So what is this doing?
$.ajax() is a function. In jQuery, you basically get access to this really awesome object, which is the jQuery object (it's also represented by the $ sign). So, $.ajax() is the same thing as saying jQuery.ajax()
The $.ajax() function takes an object as an argument. Remember that the {} is how we encapsulate an object in javascript.
The documentation for this object can be found here: http://api.jquery.com/jquery.ajax/
Basically, we need to tell the $.ajax() function a few things:
url - where are we sending this request?
async - will this request be sent asynchronously?
data - what data are we sending to the server?
type - what type of HTTP request are we sending this data in (POST, PUT, GET, etc)
datatype - what type of data are we sending?
success - what do we do if the request is successful?
error - what do we do if the request fails?
Well, at this point we've successfully sent data from browser to server asynchronously. How do we handle this in PHP? Here's how:
$input = json_decode(file_get_contents('php://input'), true);
This variable, $input is now an associative array with all of the JSON key/value pairs that we sent over. So, now we can store some of those values in variables like this:
$randomVariable = $input['im a key'];
I hope this post will get you started with AJAX. Once you get the hang of it, it's a really intuitive technology that will make your applications WAY better.
What I'm trying to do is create a slideshow by grabbing database information and putting it into a javascript array. I am currently using the jquery ajax function to call information from a separate php file. Here is my php code:
mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$i = 0;
$sql = mysql_query("SELECT comicname FROM comics ORDER BY upldate ASC");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
echo "comics[" .$i. "]='comics/" .$row['comicname']. "';";
$i++;
}
What I want is to create the array in php from the mysql query and then be able to reference it with javascript in order to build a simple slideshow script. Please let me know if you have any questions or suggestions.
Ok have your .php echo json_encode('name of your php array');
Then on the javascript side your ajax should look something like this:
$.ajax({
data: "query string to send to your php file if you need it",
url: "youphpfile.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
for (i=0; i<data.length; i++) {
alert(data[i]); //this should tell you if your pulling the right information in
}
});
maybe replace data.length by 3 or something if you have alot of data...if your getting the right data use a yourJSArray.push(data[i]); I'm sure there's a more direct way actually...
You may want to fetch all rows into a large array and then encode it as a JSON:
$ret = array();
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
$ret[] = $row
echo json_encode($ret);
Then, on the client side, call something like this:
function mycallback(data)
{
console.log(data[0].comicname); // outputs the first returned comicname
}
$.ajax
(
{
url: 'myscript.php',
dataType: 'json',
success: mycallback
}
);
Upon successful request completion, mycallback will be called and passed an array of maps, each map representing a record from your resultset.
It's a little hard to tell from your question, but it sounds like:
You are making an AJAX call to your server in JS
Your server (using PHP) responds with the results
When the results come back jQuery invokes the callback you passed to it ...
And you're lost at this point? ie. the point of putting those AJAX results in to an array so that your slideshow can use them?
If so, the solution is very simple: inside your AJAX callback, put the results in to a global variable (eg. window.myResults = resultsFromAjax;) and then reference that variable when you want to start the slideshow.
However, since timing will probably be an issue, what might make more sense is to actually start your slideshow from within your callback instead. As an added bonus, that approach doesn't require a global variable.
If this isn't where you are stuck, please post more info.