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")
}
});
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.
I have two php files. abc.php and def.php
I want to execute only abc.php in browser and only abc.php should be visible in the browser URL bar.
When submit button is clicked on my html page then abc.php should execute and pass the data of form to def.php in background using POST and def.php should not be visible in URL. is that possible?
abc.php
<script>
$.post( "def.php",{parameter: 'value'}, function( data ) {
if (data == 'success'){
alert( 'succeeded' );
}else{
alert( 'failed' );
}
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
def.php
<?php
// Do your functions here
function this(){
// do stuff
} or die('fail');
?>
success
Let me see if I understoond your issue. You have a form in abc.php.
When user submits the form PHP should send data to def.php and back to abc.php without use notices that?
If that's the case, you can do it using AJAX.
In your abc.php put an Id into your form and do the code below with jQuery:
<form method="post" action="" id="ajax_form"> ...
jQuery('#ajax_form').submit(function(){
var formData= jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "def.php",
data: formData,
success: function(data) {
alert(data);
}
});
return false;
});
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 form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)
$(document).ready(function(){
$('.clickthetext').click(function(){
$.post("submit.php", $("#formbox").serialize(), function(response) {
$('#content').html(response);
});
return false;
});
});
My target to pass content from the form and edit the data and show response at current page.
.clickthetext button content:
<div class="clickthetext">Click here to see the result</div>
content inside id #formbox:
Part of the form inside this id. rest of the form is out side this id will be processed later. only content/input inside of id "formbox" will be processed.
Whatever response we will get, we will show inside of "#content" id.
What i am doing wrong here?
----edit----
i didn't add anything on submit.php
only to show response, i wrote there:
<?php
echo 'somthing blah blah blah something';
?>
Maybe there is a problem with the result of submit.php
You can try calling
$(document).ready(function(){
$('.clickthetext').click(function(){
$.ajax({
type: "POST",
url: "submit.php",
data: $("#formbox").serialize(),
success: function(response) { $('#content').html(response); },
error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); },
dataType: dataType
});
return false;
});
});
instead and get more detail of the result of the ajax call.
Here's the API for the ajax object in jQuery
Recreating your set up,
JS/HTML
<form action="" id="formbox">
<input type="text" name="firstName" value="First Name">
</form>
<button class="clickthetext">Button</button>
<div id="content"></div>
<script>
jQuery(document).ready(function ($) {
$('.clickthetext').click(function() {
$.post("submit.php", $("#formbox").serialize(), function (response) {
$('#content').html(response);
})
})
});
</script>
PHP: submit.php
<?php echo 'this is the response'; ?>
Everything works perfectly.
Debugging tips:
1) Most likely - Check your javascript console for any errors. You probably have errors elsewhere in the page.
2) Ensure you're accessing the HTML page with the javascript via localhost, not a filepath
3) Unlikely, but check your PHP log.