So I have a page which, when requested, updates my database. For example when I go to database_update.php it just updates the database and doesn't show anything.
Index.php shows user database content.
So I have function in JavaScript called update which must use AJAX to run this page and after the page loads (after all queries run successfully) it must load index.php and show updated page to the user (reload the page without refresh effect).
My code is like:
$.get('ajax_update_table.php', {
// The following is important because page saves to another table
// users nick which call update:
update: UserLogin
}, function (output) {
// The following is unimportant:
$(myDiv).html(output).show();
});
Two suggestions:
Return a "success" or "error" code from your database_update script. Returning a JSON string is very easy. For example:
echo '{"success":"success"}';
Use the $.ajax function. Then add the success, error, and complete parameters. You can call any javascript function(s) when the AJAX request is complete.
$.ajax({
url: 'update_database.php',
dataType: 'json',
success: function (data) {successFunction(data)},
error: function () { error(); },
complete: function () { complete(); }
});
function successFunction(data) {
if ('success' in data) {
// Do success stuff here.
} else {
// Show errors here
}
}
// .... etc
I might be missing something, but I'll try to answer your question.
I would setup a blank page that on loading it sends the index.php to a div on that page. For example, make a page titled blank.php.
blank.php would have the following:
function Index(){
$.ajax({
url:"index.php",
type: "GET",
success:function(result){
$("#web-content").html(result);
}
});
}
<script type="text/javascript">Index();</script>
<div id="web-content"></div>
You would then have your index execute the Index function to update the web-content div with the index.php data without reloading the blank.php page.
Got it to work!
my index.php
<html>
<head>
<script type="text/javascript" language="Javascript" SRC="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script type="text/javascript" language="Javascript">
function update_and_replace()
{
$.ajax({
url: 'ajax_update_table.php',
dataType: 'json',
success: function (data) {successFunction(data)},
error: function () { error(); },
complete: function () { complete(); }
});
}
function successFunction(data) {
if ('success' in data) {
$("#content").load("index.php");
}
}
</script>
</head>
<body>
<div id='content'>
Now is: <?php echo date("Y-m-d, H:i:s");?>
<br/><br/><br/><br/>
Aktualizuj
</div>
</body>
</html>
Ajax_update_table.php
<?php echo '{"success":"success"}'; ?>
Thank You all for your help.
I know that my English is bad but with your help I made it!
Related
On my website I am trying to basically generate a random code (which I will set up later) and then pass that code into a PHP file to later retrieve it when the client needs it. But my code just isn't working.
Here is the code:
Javascript/HTML:
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
PHP:
<?php
$code = $_POST['code'];
echo $code
?>
So what I understand that is supposed to happen is that the code is uploaded or 'posted' to the php file and then the #result is the echo $code. None of that happens and I have no idea.
Your code working perfect with some basic changes.
You need a html element with id 'result'.
And then you need to call your init() as per requirement.
<div id="result"></div>
<script>
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
init();
</script>
I tried this on my server in the head of my document, and it worked :)
I used on complete instead of on success.
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>
<script>
function init() {
$.ajax({
type: "POST",
url: "codes.php",
data: {
'code': '12345'
},
complete: function(data){
document.getElementById("result").innerHTML = data.responseText
},
});
}
init();
</script>
with codes.php the same as you have :)
just a few notes:
Make sure you point your url to the correct file. You can check it by using the console network. Or you can simply print anything out, not just the $_POST data. e.g:
echo 'Test info';
Open browser developer panel, to see if is there any client code issue. For example, document with id 'result' existed, or you have not included jquery in. The developer console will tell you everything on the client side. For Chrome, check it out here https://developer.chrome.com/devtools
Have you actually called init() ?
I'm using an Ajax for partial loading my website. Content of GET data has images but these images appear after few seconds on page. Image size is about 20kB, so this is not a bottleneck.
I'm using php page which returns some content. This page loads in a while with images immediately but with ajax it loads text, but images after few seconds. How can I achieve quick load?
I'm using this function:
function loadMainEvents(resultDiv, cat, limit){
var spinner = new Spinner().spin(mainPageEvents);
$.ajax({
url: "/getMainPageEvents.php?category=" + cat + "&limit=" + limit,
type: "GET",
success: function(data){
resultDiv.innerHTML = data;
spinner.stop();
}
});
};
EDIT:
I created a test.php which is doing same thing
<html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js' type="text/javascript"></script>
</head>
<body>
<div id="div" style="float:left;">wait</div>
<div id="div2">wait</div>
<script>
$(function () {
$.ajax({
url: "/getMainPageEvents.php?category=&limit=10&from=29.11.2015&to=29.11.2015&pno=1",
type: "GET",
success: function (data) {
$("#div").html(data).on('load', function () {
$(this).fadeIn(250);
});
}
});
$.ajax({
url: "/getMainPageEvents.php?category=&limit=10&from=29.11.2015&to=29.11.2015&pno=1",
type: "GET",
success: function (data) {
$("#div2").html(data).on('load', function () {
$(this).fadeIn(250);
});
}
});
});
</script>
</body>
getMainPageEvents.php returns only web content.
Network from developer tools:
You may want to try something like this in the success function. Hide the result div first and foremost, then after the data is loaded, show the div.
$(resultDiv).html(data).promise().done(function(){
spinner.stop();
$(this).fadeIn(250);
});
Possible second solution
$(resultDiv).html(data).on('load', function(){
spinner.stop();
$(this).fadeIn(250);
});
I am trying to replace page reloading PHP scripts in a web page with AJAX calls.
I am using JQuery to run the AJAX scripts but it doesn't seem to be doing anything so I attempted to write an incredibly basic script just to test it.
My directory is as follows
public_html/index.php
/scripts/phpfunctions.php
/jqueryfunctions.js
index.php contains
<!DOCTYPE html>
<html>
<head>
<!-- jquery functions -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts/jqueryfunctions.js"></script>
<!-- php functions -->
<?php include 'scripts/phpfunctions.php' ?>
</head>
<body>
<button type="button" id="testButt">TEST</button>
</body>
</html>
Then the phpfunctions.php page which I am trying to call contains just an echo if an argument is set
<?php
if(isset($_GET["action"])) {
echo "test has been run";
}
?>
The jqueryfunctions.js script I am trying to run is
$(document).read(function () {
$('#testButt').on('click', function () {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test',
type: 'GET',
success: function (data) {
$('#ajaxdata').html(data);
},
error: function (log) {
console.log(log.message);
}
});
});
});
I see that the jqueryfunctions.js function is being called by the first console.log but it doesn't seem to be calling my phpfunctions.php function.
I was expecting to see the php echo "test has been run" but this doesn't happen.
Did I miss something?
You should use isset() method:
<?php
if(isset($_GET["action"])) {
if($_GET["action"] == "run_test") {
echo "test has been run";
}
}
?>
and if you are using ajax then why do you need to include it on index page:
<?php include 'scripts/phpfunctions.php' ?>
and i can't find this element $('#ajaxdata') on your index page.
Also you can check the network tab of your inspector tool to see the xhr request to the phpfunctions.php and see if this gets successfull or there is any error.
I think problem is here:
$(document).read(function() {
$('#testButt').on('click', function() {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php',
type: 'GET',
data: {action:'run_test'}, // <------ Here
success: function(data) {
$('#ajaxdata').html(data);
},
error: function(log) {
console.log(log.message);
}
});
});
});
jQuery says:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.
So you should set data: {key:'value'}
Most things look fine, but your data attribute is designed for "POST" requests, try to add the data to the url as follows:
$( document ).read( function ()
{
$( '#testButt' ).on( 'click', function ()
{
console.log( "jquery call worked" ); // this bit does run when button is clicked
$.ajax( { // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test', // Add the GET request to the end of the URL
type: 'GET',
//data: 'action=run_test', Unrequired noise :P (this is for post requests...)
success: function ( data )
{
$( '#ajaxdata' ).html( data );
},
error: function ( log )
{
console.log( log.message );
}
} );
} );
} );
And also (as mentioned in my comments), you need to finish your bodys closing tag:
</body> <!-- Add the closing > in :P -->
</html>
I hope this helps :)
Where do you load ajaxfunctions.js? It look like in your code you never load the resource
And change
<button id="xxx">
In
<button type="button" id="xxx">
So the page isn't reloaded
I have a problem that my Js file is not recognizing a php variable built by ajax.
Here is an example:
index.php:
<script src="js.js">
</script>
<?
include('build.php');
<div id="brand">
<?
echo $brandinput;
?>
</div>
//....more code
?>
build.php:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function(data){
$("#result").html(data);
}
});
</script>
<?php $brandinput='<div id="result"></div>';
?>
js.js:
$(document).ready(function(){
//dosomething with div's in index.php
}
So, I'll try to explain this in the easiest way. My index.php includes a build.php which as you can see calls ajax to retrieve data from another server. This data is located in a php variable ($brandinput) which will contain many <div>,<input>,... etc. Then index.php echo $brandinput, showing all the content of the variable. But I have a js.js which change appearances in div's, input's, etc.. and is this js which is not recognizing the content of the variable $brandinput.
I'd like to know if you have more ideas or what am I doing wrong...
All the code is working well, I tested many times (except for what I said before)
The ajax call work well and Index.php displays $braninput correctly.
p.s. $brandinput is something like this:
<div id='BlackBerry'><img src='..\/images\/supporteddevices\/blackberry-logo.jpg' alt='blackberry-logo' width='75'><br><input class='adjustRadio' type='radio'
and yeah it works well too.
Actually this is how it supposed to be working, what you need to do is to wait for the ajax request to finish first before executing the functions in js.js
try this way
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
//dosomething with div's in index.php
}
});
});
or (assuming js.js is loaded after the script within build.php, or js.js has to be loaded after it)
// in build.php
$(document).ready(function () {
var promise = $.ajax({
crossOrigin: true,
dataType: "jsonp",
type: "GET",
url: "getBrand.php",
data: info,
success: function (data) {
$("#result").html(data);
}
});
});
// in js.js
$(document).ready(function () {
promise.then(function (data) {
//dosomething with div's in index.php
});
});
P.S
$brandinput just hold the string whatever assigned to, and will never be changed with ajax request, where ajax success handler just manipulate the rendered DOM directly in the client side.
You can try moving your <script> tag to after your php codes like this:
<? include('build.php'); ?>
<div id="brand">
<? echo $brandinput; ?>
</div>
<script src="js.js"></script>
//....more code
On a slightly different note, you should consider avoid embedding/intermixing PHP codes with HTML and Javascript. Take a look at this post for better ways way "passing data from PHP to Javascript".
I had a json file results.json Which shown below. And I had a html file contain some script. This is for retrieve data data. When I am enter into the html page which call a script function get_machFollow(que_script) this function is for receive json file data. The function is works fine and which alert correct output, But after this function return some data to my HTML page.
My JSON file
{"mach_fol_4": {"match_l":
["7","8","99"],"attempts":"0","feedback_true":"You are right!",
"feedback_false":"Sorry! wrong answer."}}
This is my script function. This function is works fine but I can't alert the return value from HTML page. That shows undefined.
function get_machFollow(que_script)
{
var return_var;
$.getJSON('results.json', function(data) {
return_var=data[que_script].match_r;
alert(return_var);//Working alert show correct output
return return_var;
});
}
This is my html file
<html>
<head>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script>
$(document).ready(function(){
var mach_follow_js;
mach_follow_js=get_machFollow('mach_fol_4');
alert(mach_follow_js);//Wrong output
});
</head>
<body>
<p>Hello world</p>
</body>
</html>
are you intending return return_var; to be inside the get_machFollow scope, because right now its inside the jquery function scope and will not return value to the main page
Here below JSON data fetched by AJAX. It passing JSON Data Object in Alert.
You can use it as you want. also can Iterate data using for loop or $.each function.
$(document).ready(function(){
var mach_follow_js;
// mach_follow_js=get_machFollow('mach_fol_4');
//JSON Data Fetched by AJAX
$.ajax('results.json',{
type:'GET',
dataType: "json",
jsonCallback: 'successCallback',
async: true,
beforeSend: function () {
//if you want to show loader
},
complete: function () {
//hide loader after download data
},
success: function (resultJSON) {
mach_follow_js = resultJSON; // assigning to Global variable ProductResult
alert(mach_follow_js);
console.log(mach_follow_js);
},
error: function (request, error) {
alert('Network error has occurred please try again!');//error
}
})
});
There are multiple ways by which you can do it. One of them is pass a callback handler to your method which will be called when you get the response. Try this:
function get_machFollow(que_script, sCallback)
{
var return_var;
$.getJSON('results.json', function(data) {
return_var=data[que_script].match_r;
alert(return_var);//Working alert show correct output
sCallback.call(null /* context */, return_var);
});
}
$(document).ready(function(){
var mach_follow_js;
get_machFollow('mach_fol_4', function(output) {
alert(output);
match_follow_js = output;
});
});
Use ajax callback function $.getJSON() is actually an ajax function. So you need to apply callback to perform this action.