Trying to activate PHP function using button click with AJAX - javascript

I am trying to call a PHP script/file that will read data off of an HTML table. I want to press a button so that the PHP script/file will activate and read the data off of the HTML table into a database using MySQL.
My AJAX script is not activating the PHP file.
The HTML button code:
<button type="submit" class="btn btn-md btn-primary btn-block" id="save">Save Workout</button>
The AJAX code:
$(document).ready(function(){
$("#save").click(function(){
$.ajax({
type: 'POST',
url: 'addWorkoutTEST.php',
success: function() {
alert("hello");
}
});
});
});
The incomplete PHP code (does not contain DB code) - based off of https://brennanhm.ca/knowledgebase/2015/11/import-html-table-into-mysql-table/
<?php
require_once ('simple_html_dom.php');
$table = file_get_html('addWorkout.php');
$db = mysqli_connect('localhost', 'root', '', 'workoutLogger');
foreach($table ->find('tr') as $tr) {
$exercise = $tr->find('td', 0)->plaintext;
$weight = $tr->find('td', 1)->plaintext;
$sets = $tr->find('td', 2)->plaintext;
$reps = $tr->find('td', 3)->plaintext;
$exercise_c = mysqli_real_escape_string($db, $exercise);
$weight_c = mysqli_real_escape_string($db, $weight);
$sets_c = mysqli_real_escape_string($db, $sets);
$reps_c = mysqli_real_escape_string($db, $reps);
}
?>
I can't get a success message to pop up.

What I ended up doing was keeping the and wrapping the button around a form with the action "addWorkoutTEST.php", that did it perfectly.
<form action="addWorkoutTEST.php">
<button type="submit" class="btn btn-md btn-primary btn-block" name="save">Save Workout</button>
</form>

To prevent the default Form Submit action you just need to add in the event.preventDefault();
Something like this...
$(document).ready(function(){
$("#save").click(function(event){ // must include event here to match the object in the next line. It can be called anything.
event.preventDefault(); // Prevent Default Submit
$.ajax({
type: 'POST',
url: 'addWorkoutTEST.php',
success: function() {
alert("hello");
},
error: function (request, status, error) {
alert("ERROR: " + request.responseText);
}
});
});
});
If javascript is disabled for whatever reason, you need to decide what action to take. With what you have so far in your answer to your form with the added action, that would be the fallback in such a case. It's something you need to think out and decide upon.

Related

html form, submit and stay at same place on page

I have a long form for our learners to complete. When they click the Save Progress button to submit their work so far, the page automatically jumps back to the top and they have to scroll down to find their last answer submitted.
I'd like them to be able to save their progress at any point and stay at that point on the page.
I've tried the following, the alert appears and the page stays still but the learners work isn't saved.
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(function () {
$('#form1').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Ext1SUp.php',
data: $('#form1').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
Form action:
<form action= "Ext1SUp.php" method="post" id="form1">
Save Progress button:
<button type="Submit" name="Save" class="save-progress" form="form1" value="Submit" >Save Progress</button>
PHP:
<?php
require_once 'login.php';
$connection = new mysqli($hn, $un, $pw, $db);
if ($connection -> connect_error) {
echo "Failed to connect to MySQL: " . $connection -> connect_error;
}
if(isset($_POST['Submit'])) {
$sql = "UPDATE unit1 SET
U1Q1 = '{$_POST['U1Q1']}'
,U1Q2 = '{$_POST['U1Q2']}'
,U1Q3 = '{$_POST['U1Q3']}'
,U1Q4 = '{$_POST['U1Q4']}'
,U1Q5 = '{$_POST['U1Q5']}'
,U1Q6 = '{$_POST['U1Q6']}'
,U1Q7 = '{$_POST['U1Q7']}'
,U1Q8 = '{$_POST['U1Q8']}'
,U1Q9a = '{$_POST['U1Q9a']}',U1Q9b = '{$_POST['U1Q9b']}',U1Q9c = '{$_POST['U1Q9c']}',U1Q9d = '{$_POST['U1Q9d']}'
,U1Q10 = '{$_POST['U1Q10']}'
,U1Q11a = '{$_POST['U1Q11a']}',U1Q11b = '{$_POST['U1Q11b']}',U1Q11c = '{$_POST['U1Q11c']}',U1Q11d = '{$_POST['U1Q11d']}'
,U1Q12 = '{$_POST['U1Q12']}'
,U1Q13 = '{$_POST['U1Q13']}'
,U1Q14 = '{$_POST['U1Q14']}'
,U1Q15a = '{$_POST['U1Q15a']}',U1Q15b = '{$_POST['U1Q15b']}',U1Q15c = '{$_POST['U1Q15c']}',U1Q15d = '{$_POST['U1Q15d']}',U1Q15e = '{$_POST['U1Q15e']}'
,U1Q16a = '{$_POST['U1Q16a']}',U1Q16b = '{$_POST['U1Q16b']}',U1Q16c = '{$_POST['U1Q16c']}',U1Q16d = '{$_POST['U1Q16d']}'
,U1Q17 = '{$_POST['U1Q17']}'
,U1Q18a = '{$_POST['U1Q18a']}',U1Q18b = '{$_POST['U1Q18b']}',U1Q18c = '{$_POST['U1Q18c']}'
,U1Q19 = '{$_POST['U1Q19']}'
,U1Q20a = '{$_POST['U1Q20a']}',U1Q20b = '{$_POST['U1Q20b']}',U1Q20c = '{$_POST['U1Q20c']}',U1Q20d = '{$_POST['U1Q20d']}'
,U1Q21 = '{$_POST['U1Q21']}'
,U1Q22 = '{$_POST['U1Q22']}'
,U1Q23 = '{$_POST['U1Q23']}'
,U1Q24a = '{$_POST['U1Q24a']}',U1Q24b = '{$_POST['U1Q24b']}',U1Q24c = '{$_POST['U1Q24c']}'
,U1Q25 = '{$_POST['U1Q25']}'
,U1Q26 = '{$_POST['U1Q26']}'
,U1Q27 = '{$_POST['U1Q27']}'
WHERE id = '{$_POST['id']}'";
$result = mysqli_query($connection, $sql);
}
header('Location: Ext1S.php');
?>
The process works fine, it only stops saving after adding the script to prevent the page from scrolling.
I hope someone can offer me some advice,
Thank you
Lisa
Change button type to "button" instead of "submit" to prevent executing form. You are storing data using ajax so it's not needed to submitting form using button.
Button Type should be a "button". Remove "form" attribute from button, and change your $().on('submit') to for ex. function submitForm () {}. Then as the button attribute add onclick="submitForm()". And you can remove your preventDefault(); and action attribute from form, because you sending data by Ajax, not with a classic form. Classic forms has to refresh page after submit, but with ajax you even don't need to submit anything. Just send async request in separated function. Something like this:
function submitForm(){
$.ajax({
type: 'post',
url: 'Ext1SUp.php',
data: $('#form1').serialize(),
success: function () {
alert('form was submitted');
}
});
}
<form id="form1">
<!-- Yours form -->
<button type="button" onclick="submitForm();">Submit</button>
</form>
OH! And I almost forget. You have to remove yours if(isset($_POST['Submit'])) {} from PHP in this case. And stop using mysqli for connection :) try out PDO

update status value in backend while click on button in codeigniter

In view_candidates form in my application, I have a button with text REQUEST CONTACT INFO. When I click on the button, the text will be changed automatically to FINISH.
Now what happens: When I refresh the page the button text automatically changes to REQUEST CONTACT INFO.
To overcome this, I gave a status column in my database.
What I want:
Once user click on the button, the status should change from 0 to 1.
With status, I want to display my button text like: if status=0 button should be REQUEST CONTACT INFO, else it should be FINISH.
Button code:
<td>
<button type="button" id="button" class="btn btn-info" onclick="getConfirmation(id);">
<b>REQUEST CONTACT INFO</b>
</button>
</td>
SCRIPT:
<script>
function getConfirmation(id)
{
var retVal = confirm("your request is confiremed ?");
if(retVal)
{
$('#button').text('Finish');
$.ajax({
url: "Candidate/user_view_candidates/change_status",
type: "post",
data: id,
success: function (response)
{
//location.reload();
alert('success');
}
});
}
}
</script>
Controller code:
public function change_status()
{
$id = $this->input->post('candidate_id');
$status = $this->db->query("select status from candidates_details where id = candidate_id")->row()->status;
if($status==0)
{
$status = 1;
}
else
{
$status = 0;
}
$data=array('status'=>$status);
$this->db->where('candidate_id',$id);
$this->db->update('candidates_details',$data);
}
Can someone help me? Thanks in advance.
Check this:
View
<input type="hidden" name="candidate_id" value="<?php echo $candidate_id; ?>"/>//your candidate_id
<button type="button" id="button" class="btn btn-info" >
<b><?php $status == 0? 'REQUEST CONTACT INFO':'FINISHED';?></b>//your status value
</button>
<script src="<?php echo base_url(); ?>assets/plugins/jquery.min.js"></script>
js
$('#button').click(function() {
var candidate_id = $('input[name="candidate_id"]').val();
var url = 'your_cntroller_name/change_status/';
$.ajax({
url: your_base_url + url,
type: 'POST',
data: {'$candidate_id': $candidate_id},
dataType: 'JSON',
success: function(data) {
$('#button').text('FINISHED');
}
});
});
Controller
public function change_status() {
$candidate_id = $this->input->post('candidate_id');
$this->your_model->update_status($candidate_id);
echo true;
exit;
}
Model
public function update_status($candidate_id) {
//your query toupdate status
}
complete step by step solution is
step -1
in your view
<td><button type="button" id="button" class="btn btn-info" onclick="getConfirmation(row id);"><b>REQUEST CONTACT INFO</b></button></td>
getConfirmation(id){
$.ajax({
url: "url_to_your_controller/change_status",
type: "post",
data: id,
success: function (response) {
location.reload();
}
});
}
step -2
in your controller
change_status(){
$id = $this->input->post('id');
$status = $this->db->query("Your query")->row()->status;
if($status==1){
$status = 0;
} else {
$status = 1;
}
$data=array('status'=>$status);
$this->db->where('id','id');
$this->db->update('table_name',$data);
}
from your question I understand that you are displaying your record in a grid/ table and for each record in a row you have a button when you click on button it change the status of the record.
so the solution is simple onclick change the status using ajax call and in DB add a field status against each record which will be 0 by default and after onclick it'll be updated to 1
on page load you've to implement in your view a check
e.g
<?if(status==0){?>
<td><button type="button"><b>Working</b></button></td>
<? } else { ?>
<td><button type="button"><b>Finished</b></button></td>
<? } ?>

run full php-script in ajax/jquery

Sorry for my bad english. I'm trying to run a PHP function through an ajax script. The PHP script should run as a FULL NORMAL php script. My idea is to run a recaptcha by a Submit button WITHOUT refreshing the page. That is working, but I found no way to run a normal php script after that. Here is the part of my script.
php:
if( isset( $_REQUEST['startattack'] )){
$secret="********************";
$response=$_POST["g-recaptcha-response"];
$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo "<script type='text/javascript'>alert('failed!')</script>";
} else if ($captcha_success->success==true) {
echo "<script type='text/javascript'>alert('success!')</script>";
}
}
html:
<form method='post' id="myform">
<center>
<div class="g-recaptcha" data-sitekey="6LfETygTAAAAAMC7bQu5A3ZhlPv2KBrh8zIo_Nwa"></div>
</center>
<button type="submit" id="startattack" name="startattack" onclick="mycall()" class="btn btn-attack">Start Attack</button>
</form>
ajax:
<script>
$(function () {
$('button').bind('click', function (event) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('button').serialize(),
success: function () {
alert('button was submitted');
type: 'post';
url: 'post.php';
}
});
event.preventDefault();// using this page stop being refreshing
});
});
</script>
I want to check the recaptcha here. If correct, it should echo correct in PHP and I want to add feature later. The same with the false captcha.
I think you can simplify things a bit. You don't return the response in the Ajax is your main problem.
PHP:
Just echo the returned json from the recaptcha (although I have no idea where you get the g-recaptcha-response key/value, you are not sending it anywhere).
if(isset( $_POST['startattack'] )){
$secret = "********************";
// I have added a key/value in the ajax called "sitekey",
// this might be what you are trying to retrieve?
$response = $_POST["g-recaptcha-response"];
echo file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
exit;
}
AJAX:
I think since the return from the recaptcha is json anyway, just echo it and pick it up on this side:
$(function () {
$('button').bind('click', function (event) {
var statusBlock = $('#status');
statusBlock.text('button was submitted');
$.ajax({
type: 'POST',
url: 'post.php',
data: {
// Not sure if you are trying to pass this key or not...
"sitekey":$('.g-recaptcha').data('sitekey'),
"startattack":true
},
success: function (response) {
var decode = JSON.parse(response);
var alertMsg = (decode.success)? 'Success' : 'Failed';
statusBlock.text('');
alert(alertMsg);
}
});
// using this page stop being refreshing
event.preventDefault();
});
});
Form:
Leave a spot to post the submit status so it doesn't interfere with the return alert dialog window.
<form method='post' id="myform">
<div id="status"></div>
<center>
<div class="g-recaptcha" data-sitekey="6LfETygTAAAAAMC7bQu5A3ZhlPv2KBrh8zIo_Nwa"></div>
</center>
<button type="submit" id="startattack" name="startattack" onclick="mycall()" class="btn btn-attack">Start Attack</button>
</form>

Enter ID in html form and load related data from MySQL database in same page

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 :-)

How to use jQuery AJAX with PHP to submit a form into a mySQL database with using an <a> tag?

What I am trying to do is create a "save" button for my website which saves specific posts and comments, exactly like the "save" button on Reddit. For now I am trying to self teach jQuery AJAX and attempting to figure out how to submit data to the database without having to reload the whole page. What I am attempting to do here is save a string by submitting it to a table called "Saved" when I click on "save".
HTML
<div id="message1">
<div id="pmessage"><p><?php echo $myComment;?></p></div>
Save
Edit
Hide
</div>
<form action="ajaxexample.php" method="post" style="display: none" id="1234">
<input type="hidden" name="message" id="message" value="<?php echo $myComment; ?>">
</form>
jQuery
$('a.Save').click(function () {
if ($(this).text() == "Save") {
$("#1234").ajax({ url: 'ajaxexample.php', type: 'post', data: 'message' });
$("a.Save").text("Unsave");
} else {
$("a.Save").text("Save");
}
});
PHP5.3
$message = $_POST['message'];
$query = "INSERT INTO saved (comment) VALUES (?)";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('s', $message);
$statement->execute();
$statement->store_result();
$submissionWasSuccessful = $statement->affected_rows == 1 ? true : false;
if ($submissionWasSuccessful)
{
header ("Location: index.php");
}
$myComment = "This is my message!";
As of now all I am trying to do is submit the message "This is my message!" into the database table "Saved". What is wrong with my code? Why can I not submit the data to the table and how can I fix it? Thanks in advance!
Submit form when someone clicks on a.Save
$('a.Save').click(function (e) {
e.preventDefault();
$("#1234").submit();
});
submit handler on form#1234
$("#1234").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'ajaxexample.php',
data: $("#1234").serialize(),
success: function(data)
{
// data stores the response from ajaxexample.php
// Change the html of save by using $("a.Save").html("Unsave");
}
});
});
Serialize automatically makes a query string.
$(".save").bind("click",function(e){e.preventDefault();
$.ajax({
url : $("#1234").attr("action"),
type : "POST",
data : $("#1234").serialize(),
success : function(data){},
fail : function(data){},
});
});

Categories