I am working on this project in edge animate for a school assignment.
I have a database on my school webspace and I need to import some data from that database into my edge animate project.
I've been looking on the internet how to do this and these pictures show what I have so far. It still has a javascript error, but I can't figure out what. If I could just get that javascript error sorted, I can add code do some things with the array.
I collect the data from the database in a php-array and I want to save it in an array in javascript so I can display anything from inside that array on different places I want to.
thats because $.ajax is a jquery function, therefore you have to import this libary.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function Load()
{
console.log('start ajax query...');
var delivery;
$.ajax({
method: "POST",
url: "test.php",
data: { foo: "bar" }
})
.done(function( data ) {
delivery=data;
console.log(data);
console.log('...all fine');
});
}
$( document ).ready(function() {
console.log( "firing load function..." );
Load();
});
</script>
PHP Script
dont modify the header, simply echo the return of json_encode().
<?php
/**
* FILE test.php
*/
echo json_encode(array('foo'=>'bar'));
?>
Related
I want to do the following:
<html>
<div id="first"><?php echo time(); ?></div>
<div id="second">My dropdown menu goes here</div>
<div id="third"><?php echo time(); ?></div>
</html>
I have this "example.php" and what I want is that refreshing first and third divs and PHP codes inside them every 1 second without reloading page and changing the state of the second div which will hold a selection from dropdown menu.
So the selection of the dropdown menu should be exact and when I click and open the dropdown menu, the menu must not be closed when a refresh occurs at first and third div.
Also, refresh method of the first and third div must be simultaneous and completely separate processes. Time printing is just for feeding a time changing value to my problem. I will read and print MySQL database data inside these PHP codes.
How can I do that using javascript? Thanks...
To achieve your desired result, You need to utilize Ajax and JSON.
Your PHP script will return fresh data as json which will be fetched via Ajax and then replaced in the target divs.
But before we begin let's learn a bit about Ajax and JSON
What is Ajax?
Ajax is a client-side script that communicates to and from a server/database without the need for a post back or a complete page refresh. Essentially, Ajax is “the method of exchanging data with a server, and updating parts of a web page – without reloading the entire page.”
What is JSON?
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
How to integrate it with your script?
We will first define a javascript function named update_data() which fetches the values from the server and then updates the divs with their fetched values.
To do all this, we'll use jQuery as a dependency and will utilize it's jQuery.ajax() method
NOTE - To automatically call the function every second we will also need setInterval method
function update_data() {
$.ajax({
url: 'test.php', // Your PHP script location
type: "GET",
async: true, // refer to reference [1] in my answer
success: function (data) {
// Update the values
$('#first').text(data.time1); // get the value of `time1` key from returned data
// #first targets the element with id="first"
$('#third').text(data.time2);
}
});
}
setInterval("update_data();", 1000);
// calls the function `update_data()` every second
Sample PHP script- (test.php)
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$data = Array('time1' => time(), 'time2' => time());
// returns the data with mime type `json` instead of `html`
header("Content-Type: application/json; charset=UTF-8");
echo json_encode($data); // converts array into json
}
?>
The above PHP script will return the follwoing JSON structure:
{
"time1": 'value returned by first call to time()',
"time2": 'value returned by repeated call to time()'
}
Full html example (calls external php)-
<html>
<div id="first">Print some value on page load, will be replaced by Ajax</div>
<div id="second">My dropdown menu goes here</div>
<div id="third">Print some value on page load, will be replaced by Ajax</div>
<!-- Include jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function update_data() {
$.ajax({
url: '/test.php', // Your PHP script location
type: "GET",
async: true, // refer to reference [1] in my answer
success: function(data) {
// Update the values
$('#first').text(data.time1); // get the value of `time1` key from returned data
// #first targets the element with id="first"
$('#third').text(data.time2);
}
});
}
setInterval("update_data();", 1000);
// calls the function `update_data()` every second
</script>
</html>
Reference -
1. What does "async: false" do in jQuery.ajax()?
Use http://api.jquery.com/jquery.ajax/
Example:
<script>
$(function(){
$.ajax({
url: "first.php",
})
.done(function( data ) {
if ( data ) {
$('#first').html(data);
}
});
});
</script>
Now, if you are really swimming off the pond, I'll make it easier:
<script>
var t=0;
function fetchFirst()
{
$.ajax({
url: "first.php",
})
.done(function( data ) {
if ( data ) {
$('#first').html(data);
clearTimeout(t);
}
});
}
$(function(){
t=setTimeout(fetchFirst, 1000)
});
</script>
Now you can get the rest from this quick start. Remember to embed jquery before this stuff with
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
and do not make too many requests simultaneously.
Good luck.
I have a wordpress website en would like to create users with a button (to start with)
It works in pieces, but i can't get this two pieces to work together
i have this piece of code (works on functions.php , but not in my createaccount.php file)
$userid = new WP_User(wp_create_user( 'My_new_name' , '123458' , 'me#mail.com'));
$userid->set_role('client'); //custom role 'client' already set
this on jquery //php file works when echo 'test';
$(document).ready( function() {
$('#newbtnaccount').click( function() {
$.post('php/createaccount.php', { } ,
function(data) {
alert(data);
});
});
});
i already tried a lot of options but nothings seems to work yet.
Anyone who can Help?
Thanks!
In wordpress you can make an AJAX request to admin-ajax.php and attach functions in your functions.php file with wp_ajax_my_action (for logged users) and wp_ajax_nopriv_my_action (for non logged users).
1. Set the admin-ajax.php url available as JS variable
In header.php add this in the head part:
<script type="text/javascript">
var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
2. Request the function through ajax
You need to add an action parameter to your request reflecting the function that you need to call in functions.php - let's call it create_user.
$.post(ajax_url, {action: 'create_user'} , function(data) {
alert(data);
});
3. Create the function in functions.php
Inside functions.php, add the following:
function ajax_create_user() {
$userid = new WP_User(wp_create_user( 'My_new_name' , '123458' , 'me#mail.com'));
$userid->set_role('client');
// echo whatever you need to return
}
add_action( 'wp_ajax_create_user', 'ajax_create_user' );
add_action( 'wp_ajax_nopriv_create_user', 'ajax_create_user' );
Read more about AJAX in Wordpress
I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>
I have a editor embeded in the html page
<div id="editor">
Problem Statement goes here…
</div>
I basically want to store the contents written in editor to a file(preferably in rich text format). I used a script (given below) for storing the contents in a string.(This I used by referring to HTML div text to save and display )
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
var StoreEditorContent; //declare a variable to save Content
document.getElementById('save').addEventListener("click", SaveText); // adding event listner for onclick for Saving text
function SaveText(){
StoreEditorContent = document.getElementById('editor').innerHTML; // Save the Content into
document.getElementById('editor').innerHTML = ""; // to blank the editor Content
window.onload = function(){
$.ajax({
url: "submit_request.php",
type: "GET",
success: function writeMsg(StoreEditorContent){
//Not sure if this part is right.
}
});
}
}
</script>
This of course is storing in the contents in a string StoreEditorContent. I now want to pass this string to a php function which will write this(StoreEditorContent) to a file.The php file that contains function to write is given below
<?php
function writeMsg($msg){
$file = "myfile.txt";
file_put_contents($file, $msg);
}
?>
I know I need to use ajax here, but cannot figure out how? Any help appreciated.
You need to provide a data: option to $.ajax():
$.ajax({
url: "submit_request.php",
type: "POST",
data: { content: StoreEditorContent },
success: function (response) {
// Do something with the response sent from PHP
}
});
Then your PHP can do:
writeMsg($_POST['content']);
You should use POST rather than GET for large requests because the limit on GET parameters is relatively small.
I have a problem with ajax and rewrite engin. I made a site, where I use this load more script:
http://www.9lessons.info/2009/12/twitter-style-load-more-results-with.html
Everything works fine on users profile page (I am getting posts from users feedback), when the url looks like this: example.com/user.php?u=ExampleUser
but I have this in .htaccess:
RewriteRule ^u/(.*) user.php?u=$1 [L]
So if I type something like example.com/u/ExampleUser I get the username like:
$username = $_GET['u'];
But in this way when I click on the load more it doesn't load more posts from the user, it just starts to lead the site itself to the div box (like it is an iframe...).
Please help me, it is necessary.
Here is my script, which should load more info from MySQL database($id is userid from DB):
$(function() {
// More Button
$('.more').live("click",function() {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: 'lastmsg='+ID+'&user='+<? echo $id; ?>,
cache: false,
success: function(html) {
$("#container").append(html);
$("#more"+ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
Not knowing the entire context of your code, it looks like when the ajax call is made, the final url is something along the lines of domain.tld/u/ajax_more.php.
I get around this issue by maintaining a list of constants in the javascript object.
For example, I have a paths.php file that contains this:
<?php
header("Content-Type: text/javascript");
echo "
myNamespace.paths = {
RELATIVE_FOLDER: '<?=RELATIVE_FOLDER?>',
// add more as required...
}
";
?>
This is included in the page just like a regular script (with script tags), and from that point forward, myNamespace.paths will contain your constants, as returned by the server.
In my case, if the URL was "http://www.example.org/path/to/my/dev/env", I would have RELATIVE_FOLDER set to /path/to/my/dev/env/ on the server-side, which would then be included into the paths object.
Later, in your ajax calls:
$.ajax({
type: "POST",
url: myNamespace.paths.RELATIVE_FOLDER + "ajax_more.php",
// ... everything else
});
I notice you have no problem with directly injecting PHP into your scripts. This is not necessarily a bad thing, but it does make it harder for you to minify your js. This is the reason why I went with a separate file to store the constants, instead of directly injecting it into the javascript itself with <?= ... ?> tags.