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
Related
I am trying to send js variables from my js file to another php file when the user hits "FINISH" on the main php page. Here is my code so far:
map.php
<form action="./finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
map.js
function sendData() {
$.ajax({
method: "POST",
url: "../finalmap.php",
data: {
selectedLoc: selectionArray,
startLoc: start,
endLoc: end,
dist: distance,
locTypes: allLocations
},
beforeSend : function(http) { },
success : function(response,status,http) {
alert(response);
},
error : function(http,status,error) {
$('.response').html("<span class='error'>Something went wrong</span>");
$(".response").slideDown();
}
});
}
finalmap.php
<?php
$data = $_POST['data'];
echo $data;
?>
Post is successful and I'm able to see the contents(my code) in my finalmap.php from the alert command. When I try to console.log $data in finalmap.php, it is empty/null.
My goal is to send the data to finalmap.php and redirect to it.
To solve this problem, you must reduce what you're testing to one thing at a time. Your code has errors and is incomplete. So let's start with the errors first: If you're using AJAX, you don't want HTML to submit the form in the regular way. If you get a page refresh, your AJAX didn't work.
<button type="button" id="submit-button">FINISH</button>
Note, no <form> is needed; you're submitting through AJAX.
Next, you need to be sure that your ajax function is being executed (since you're using $.ajax, I presume you have JQuery loaded):
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
// this is the same idea as your onclick="sendData();
// but this separates the javascript from the html
$('#submit-button').on('click', function() {
console.log('hello world');
});
});
</script>
You use your web console to see the console.log message.
Now, try out the ajax command with a simple post:
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
$('#submit-button').on('click', function() {
$.ajax({
method: "POST",
// "./finalmap.php" or "../finalmap.php"?
url: "../finalmap.php",
data: {foo: 'bar'},
success: function(response){
console.log('response is: ');
console.log(response);
}
});
});
});
</script>
finalmap.php
<?php echo 'This is finalmap.php';
If you see This is finalmap.php in the web console after pressing the button, then you can try sending data.
finalmap.php
<?php
echo 'You sent the following data: ';
print_r($_POST);
See where we're going with this? The way to eat an elephant is one bite at a time.
./finalmap.php is not a thing.
Instead the code must look like this:
<form action="/finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
Try using this instead.
EDIT: OOPS SORRY, I JUST CPED AND PASTED.
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 am trying to pass a variable from js to a backoffice page.
So far I've tried using a form and submitting it from javascript (but that refreshes the page, which I don't want)
I ditched the form and when for an iframe (so the page doesn't reload everytime the data is submitted). The function is run every few seconds (so the form should be submitting):
<iframe style="visibility:hidden;display:none" action="location.php" method="post" name="location" id="location">
<script>
/*Some other stuff*/
var posSend = document.getElementById("location");
posSend.value = pos;
posSend.form.submit();
</script>
However my php page does not display the value posted (im not quite sure how to actually get the $_POST variable):
<?php
$postion = $_POST['location'];
echo $_POST['posSend'];
echo "this is the";
echo $position;
?>
I also tried $.post as suggested here Using $.post to send JS variables but that didn't work either.
How do I get the $_POST variable value? I cannot use $_SESSION - as the backoffice is a different session. What is the best method to do this?
EDIT I'd rather avoid ajax and jquery
And i think you no need to use form or iframe for this purpose . You just want to know the user onf without refreshing then use the following method with ajax.
index.html the code in this will
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
navigator.geolocation.getCurrentPosition(function(position)
{
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
$.ajax(
{
url:'location.php',
type: 'POST',
datatype: 'json',
data: {'pos':pos}, // post to location.php
success: function(data) {
aler(data);
// success
},
error: function(data) {
alert("There may an error on uploading. Try again later");
},
});
});
</script>
location.php
echo "position :=".$_POST['pos'];
Instead of using iframe to submit your form with out reloading you submit form using ajax call.
$.ajax({
type: "POST",
url: url,
data: $("#formId").serialize(), // This will hold the form data
success: success, // Action to perform on success
dataType: "JSON" or "HTML" or "TEXT" // return type of function
});
There are various alternative to submit the form without reloading the page check here
Thanks
You can use plugin ajaxForm. On action and method you can form options
$(function() {
$('#form_f').ajaxForm({
beforeSubmit: ShowRequest, //show request
success:SubmitSuccesful, //success
error: AjaxError //error
});
});
Lakhan is right, you should try to use ajax instead of an iframe as they cause a lot of issues. If you absolutely need to use an iframe add a target attribute to your form (target the iframe not the main page) and only the iframe will reload.
<form action="action" method="post" target="target_frame">
<!-- input elements here -->
</form>
<iframe name="target_frame" src="" id="target_frame" width="XX" height="YY">
</iframe>
Here's a fully worked example that makes use of a <form>, the FormData object and AJAX to do the submission. It will update the page every 5 seconds. Do note that in PHP, the use of single quotes ( ' ) and double quotes ( " ) is not always interchangeable. If you use single quotes, the contents are printed literally. If you use double-quotes, the content is interpretted if the string contains a variable name. Since I wanted to print the variable name along with the preceding dollar sign ($) I've used single quotes in the php file.
First, the PHP
location.php
<?php
$location = $_POST['location'];
$posSend = $_POST['posSend'];
echo '$location: ' . $location . '<br>';
echo '$posSend: ' . $posSend;
?>
Next, the HTML
index.html
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
var formData = new FormData(formElem);
ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
var submitIntervalHandle = setInterval( doAjaxFormSubmit, 5000 ); // call the function to submit the form every 5 seconds
}
function doAjaxFormSubmit()
{
myAjaxPostForm('location.php', byId('myForm'), onSubmitSuccess, onSubmitError);
function onSubmitSuccess(ajax)
{
byId('ajaxResultTarget').innerHTML = ajax.responseText;
}
function onSubmitError(ajax)
{
byId('ajaxResultTarget').innerHTML = "Sorry, there was an error submitting your request";
}
}
</script>
<style>
</style>
</head>
<body>
<form id='myForm'>
<input name='location'/><br>
<input name='posSend'/><br>
</form>
<hr>
<div id='ajaxResultTarget'>
</div>
</body>
</html>
When I click on "Register Now" Button, I want to execute 'input.php' in which I have code to insert my data to the database and show a success message. I don't want to leave current page.
<input type="button" id="confirm" value="Register Now" class="button">
<script type="text/javascript">
$(document).ready(function() {
$("#confirm").click(function() {
<?php
include 'input.php';
?>
alert ("data Added successfully.");
});
});
</script>
My code is giving me "data Added successfully" message but PHP file hasn't executed and no data is added to the database. All necessary data is in session variables.
Suggest you try something like the below. You shouldn't be trying to execute PHP inside of a jQuery script. Do an AJAX call and pass the data through and process it in the PHP rather than relying on the session variables. For example:
<script type="text/javascript">
$(document).ready(function () {
$("#confirm").click(function () {
$.ajax({
type: "POST",
url: "index.php",
data: {
firstname: "Bob",
lastname: "Jones"
}
})
.done(function (msg) {
alert("Data Saved: " + msg);
});
});
});
</script>
Where firstname, lastname would be your normal session data.
You can learn more about the jQuery.ajax() function in the jQuery API Documentation.
To execute a Php script from javascript, you have to use Ajax.
the following code :
$("#confirm").click(function() {
<?php
include 'input.php';
?>
alert ("data Added successfully.");
});
will not work
http://api.jquery.com/jquery.ajax/
You need to use AJAX. Ajax is the concept of calling php files from javascript from inside the page. You then get the php page output in a variable and you can choose wether you will display it or not. An example of this technology is the show more posts of Facebook. This can be easily done with jQuery.
$.post( PHP_FILE, { field1: 'value', field2: 'value'}).done(function( data )
{alert("this function will be run when the request is over and the variable data
will have the output : " + data);});
you can do this by ajax post method..
$.ready(function(){
$("#confirm").click(function() {
$.ajax({
type: "POST",
url: "give url to the input.php file ",
data:,
success:function(data)
{
alert('data');// data is the return value from input.php
}
});
});
});
Try this:
<input type="button" id="confirm" value="Register Now" class="button">
<script type="text/javascript">
$(document).ready(function() {
$("#confirm").click(function() {
$.get('input.php').
success(function(){
alert ("data Added successfully.");
});
});
});
</script>
I'm not quite sure what you've tried to do there. Anyway here's a snippet of js that should do for you (I'm pretty sure in the new jQuery release there's a better way to do this though):
$.ajax({
url: "input.php",
success:
function(data)
{
// here, for example, you load the data received from input.php into
// an html element with id #content and show an alert message
$("#content").html(data);
alert("Success")
}
});
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!