I'm trying to figure out how to call a PHP function with a html button as i understand so far i can't use javascript since it client side but would it work with jquery and how so?
Here my button
<button type="button" class="btn btn-default" data-dismiss="modal">Yes</button>
And here is my function in php
function confirmCloseTicket($conn) {
if (isset($_GET['deleteticketid'])) {
$id = $_GET['deleteticketid'];
$statuschange = "Closed Ticket";
$sql = "INSERT INTO closedtickets SELECT * FROM ticket WHERE ticketID = $id;";
$sql .= "DELETE FROM ticket WHERE ticketID = $id;";
$sql .= "UPDATE closedtickets SET status = '$statuschange' WHERE closedtickets.ticketID = $id;";
$result = mysqli_multi_query($conn, $sql);
if($result) {
header("location: http://localhost/ticketSystem/viewticket.php");
exit();
}else {
echo "failed";
}
}
}
I figure it out with this method:
Starting of to create a button using <a> tag and give it AN ID "Verify-Email" you can call it what ever you want just remember it!
HTML:
Verify Now!
In jquery or inside a <script></script> tag i call ID "#verify-email". also using # it tells is a ID and not a class, if you were using a class it would look like this.
".verify-email"
Then i'm using a .click(function(e){ a bassic click do function.
then i'm using e.preventDefault(); to prevent the page to refresh while we doing this click function by pressing the button from the page.
then i'm using a $.ajax({ }); reuqest to call it to POST Method.
as you can see inside my Ajax i have URL, method and DATA, what i have done i have called an action : 'verify-email' see step 6. how i GET that POST inside php.
jquery:
$("#verify-email").click(function(e) {
e.preventDefault();
$(this).text('Please Wait...');
$.ajax({
url: 'assets/php/process.php',
method: 'POST',
data: { action: 'verify-email' },
success:function(response){
$("#verifyEmailAlert").html(response);
$("#verify-email").text('Verify Now');
}
});
});
inside here i have a isset function by verify super global variable $_POST['action] and also checking it again with 'verify-email' both of those values need to be same as $.ajax method
process.php:
if (isset($_POST['action']) && $_POST['action'] == 'verify-email') {
// need to create a varible for "verify-email"
$Getemail = $_POST['verify-email'];
then call the function
}
Related
I'm new into php and I am trying to call code from another file.
I try to use ajax to so, because later I would like to add parameters. But unfortunattely for me nothing appen when I click on my button.
I have a button in my file admin.php that is written like this:
<button onclick="clickMe()"> Click </button>
And in the same file I have my ajax code in script balise:
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: test() {
alert('ok');
}
error : test(){
alert("error");
}
});
}
</script>
And here is the code that I'm trying to call in my ajax, the function test in the file delete.php:
<?php
function test() {
echo "Hello the World! ";
}
?>
I wondering if I maybe need to put the code in delete.php in a function ?
Do you think I need to post the entirety of my admin.php file, even thought a lot of the code is not related to the question ?
EDIT: I forgot to mention; i have require delete file in my admin one:
require 'delete.php';
I don't know jQuery, but I think your code should look something like this:
<?php
// delete.php
// make somthing
return 'Helo Word';
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: response => {
alert(reponse);
},
error: error => {
alert(error);
}
});
}
</script>
let's assume that your js code is working(i'm bad with JQuery). The JS code and the PHP code are living in different worlds but can connect by HTTP requests(XML-AJAX) and some others.
You can do a request to a PHP page like my-domain.com/the-page.php?get_param_1=value(GET method), and you can pass the same params(and a little more) by POST method. GET and POST params are looking like :
param_name=param_value¶m_name=param_value¶m_name=param_value
You can't call directly PHP function(like var_dump('123);), but you can do this request with JS my-domain.com/the-page.php?call_func=myFunc123&printIt=HelloMate
to php page
<?php
function myFunc123($printText) { echo $printText; }
if (array_key_exists('call_func', $_GET)) {
$param_callFunc = $_GET['call_func'];
if ($param_callFunc == 'myFunc123') { myFunc123($_GET['printIt']); }
}
?>
Yes, you can pass any existing function name and call it, but it's not safe in future usage. Above, i use "page" word because you should do a request, not php file read or access.
Here is how I finally did it :
I gived an id to my button:
<button id="<?php echo $rows['id']; ?>" onclick ="deletedata(this.id)">Delete</button>
I give in deletedata the parameter this.id, it's a way to give the id of the button as parameter, then I use Ajax to call delete:
<script type="text/javascript">
// Function
function deletedata(id){
$.ajax({
// Action
url: 'admin',
// Method
type: 'POST',
data: {
// Get value
id: id,
action: "delete"
},
success:function(response){
}
});
};
</script>
Here is the tricky thing, I didn't use a fonction as I thought I needed. Instead I did this :
if (isset($_POST["action"])) {
echo "Hello the World! ";
// Choose a function depends on value of $_POST["action"]
if($_POST["action"] == "delete"){
mysqli_query($conn, "DELETE FROM bdd_sites WHERE id = " . $_POST['id'].";");
}
header('Location: '.$_SERVER['REQUEST_URI']);
}
?>
I have a navigation bar that is created from a MySQL table. I want to click on the link and only change the contents of two divs on the page. However, I cannot figure out the proper way to write the jQuery code.
I've attempted to include a single class for all the links and use
$(".class").click(function(){
//the code to change the div
}
But it doesn't seem to be working.
PHP code
<?php
require(__DIR__.'/dbconf.php');
require(__DIR__.'/db_functions.php');
$db_con = mysqli_connect($host, $username, $pass, $dbname);
$column = "playerName";
$table = "Players";
$condition = "";
$key = "";
$query = selectData($db_con, $column, $table, $condition, $key);
while($row=mysqli_fetch_assoc($query)){
$res[] = $row[$column];
echo "<a href = # class = 'player' name ='".$row[$column]."'>".$row[$column]."</a>";
}
mysqli_close($db_con);
?>
JQuery code
$(".player").click(function(){
var player = $(this).val()
var dataString = 'playerName'+ player;
$.ajax({
type: "POST",
url: "coin_amount.php",
data: dataString,
cache: false,
success: function(postresult){
$(".coins").html(postresult);}
});
return false;
});
It seems like this should work. That when any link with the class "players" is clicked, it should change the value of the player variable and call the coin_amount.php file. But it doesn't. What am I not understanding? I do know the ajax function is correct because I call that function on page load and it works. So it has to be something in the click function.
If player is created after the DOM has loaded, you will have to attach the click listener to the document, like so:
$(document).on('click', '.player', () => {
// execution code here
}
ADD It in the <script></script> tag in the head of page after have loaded the jquery library
Jquery code:
$(document).ready(function() {
$("#cercaButton").click(function () {
$(".divClass").load("./action/loadDdtGiornalieri.php");
});
});
In your case add the id at the link tag generated from the php code that print the menu.
I suggest you to add different ID at every link of the menu in order of load different contenent
From php you have to generate a string as
<a id="cercaButton">Cerca</a>
This is a complete example of load, including also the parameter post at the php web page
If you have to post data at the page loaded from jquery simplest code is
$(document).ready(function() {
$("#cercaButton").click(function () {
$(".divClass").load("./action/loadDdtGiornalieri.php", {
dateIn: $("#dateIn").val(),
tipoInterrogazione: $("#tipoInterrogazione").val()
});
});
});
I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});
here is the problem.
i have HTML Form and it has a button submit with an onclick=validationFunction(). When i click this button, values from form goes to this function.
Now, in this function, the values of the form are cheenter code herecked ifenter code here they are correct or not. In addition, it has 1 input Field who has to be checked for validation, and also checked again from database to see it that value exists there. This part is done via ajax. Below the ajax call, there is a return value(boolen) for the function validationFucntion().
Now, what i want. i want either of the two things.
1) ajax should return true or false within its success
2) or ajax should send the value just below where the ajax call ends. By now, i m failing big times to do either of the things.
Here is a sample pseudo code.
function validationFunction()
{
validations checks in progress
$.ajax({
url:'checkIfNumberExists.php',
data : {
'number : num //this num is coming from above
},
method:'GET',
success: function(data)
{
console.log("Return Value = "+this.toReturn);
if( (this.toReturn) > 0 )
{
either return validationFunction from here or set a flag.
}
else
{
either return validationFunction from here or set a flag.
}
});
}
checkIfNumberExists.php
<?php
$num = $_GET['number'];
$toReturn = 0 ;
$queryCheckNo = mysql_query('SELECT * FROM `TABLE` WHERE `number_from_table`="'.$num.'" ');
while($row = mysql_fetch_assoc($queryCheckNo)){
$toReturn++;
}
echo ($toReturn);
?>
try this plug in
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing spinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
and keep this inside your form
<form id="tempForm" enctype="multipart/form-data">
<input type="file" name="" id="" />
</form>
and you can find the plug in here
I'm on my first CI project and I'm trying to do basically an AJAX "edit in place".
I have a user profile page with a number of fields. Basically the user is looking at his own data, and I would like to give him the option to edit his info on a field by field basis. I have about 20 fields like so..
<div id="desc_short">
<div class="old_info"><p><?php echo $the_user->desc_short; ?></p></div>
<div class="edit_buttons">
<button type="button" class="btn_edit">Edit Field</button>
<button type="button" class="btn_submit">Submit Change</button>
<button type="button" class="btn_cancel">Cancel</button>
</div>
The submit and cancel buttons start off with display:none. A click on the 'edit' button appends a form to the div with some hidden field info and "shows it in" along with 'submit' and 'cancel' buttons. SO now the user has a text field under the original info, and two new buttons.
$('.btn_edit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var form_HTML = "<form action='edit_profile' method='post'><input type='text' class='new_info' name='new_info'/><input type='hidden' class='edit_field' name='edit_field' value='"+this_field_id+"'/></form>";
$("#"+this_field_id).append(form_HTML).hide().show(500);
$(this).siblings().fadeIn(1000);
});
So I am dynamically adding the form to the appropriate div, and giving it a hidden field with the name of the datafield that is being edited. I'm also showing the "submit" and "cancel" buttons (although notice that the submit button is not in the form element).
I'll leave out the "cancel button" function, but here is the submit button jquery. As you can see I am trying to submit the form by "remote control", triggering a submit event on the form long distance from the submit button. And then on the submit event, I preventDefault and then try to $.post the info to an AJAX controller..
$('.btn_submit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var new_info = $("#"+this_field_id+" .new_info").val();
alert(this_button);
$("#"+this_field_id+" form").trigger('submit');
$("#"+this_field_id+" form").submit(function(e){
e.preventDefault();
alert(this_field_id); // alerting correctly
$.post('../ajax/profileEdit', { edit_field: this_field_id , new_info: new_info },
function(data){
if(data = 'true')
{
alert(data); // <<<< alerts "true"
}
else
{
alert("bad");
}
}
);
});
});
Here is the ajax controller
public function profileEdit()
{
$ID = $this->the_user->ID;
$field = $this->input->post('edit_field');
$new_info = $this->input->post('new_info');
$this->load->model('Member_model');
$result = $this->Member_model->edit_profile( $ID, $field, $new_info );
echo $result;
}
And the model..
public function edit_profile($ID, $field, $new_info)
{
$statement = "UPDATE users SET $field=$new_info WHERE UID=$ID"
$query = $this->db->query($statement);
return $query;
}
I am actually getting back "TRUE" back to Jquery to alert out .. but nothing is being edited. No change to the information. Frankly, I am surprised I'm even getting 'true' back (the whole remote submit thing .. I thought "no way this works").. but that makes it tough to see what is going wrong.
Ideas?
Apart from the if(data = 'true) error, i don't see where the other error could be.
When you alert data, what does it show you?
Try this in the model;
public function edit_profile($ID, $field, $new_info)
{
$data = array('field_table' => $field, 'new_info_table' => $new_info);
return ($this->db->where('UID',$ID)->update('tabel_name',$data)) ? TRUE : FALSE;
}
AND in
public function profileEdit()
{
$ID = $this->the_user->ID;
$field = $this->input->post('edit_field');
$new_info = $this->input->post('new_info');
$this->load->model('Member_model');
if($this->Member_model->edit_profile( $ID, $field, $new_info )){
echo 'success';
}else{
echo 'error';
}
}
Then
$('.btn_submit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var new_info = $("#"+this_field_id+" .new_info").val();
alert(this_button);
$("#"+this_field_id+" form").trigger('submit');
$("#"+this_field_id+" form").submit(function(e){
e.preventDefault();
alert(this_field_id); // alerting correctly
$.post('../ajax/profileEdit', { edit_field: this_field_id , new_info: new_info },
function(data){
if(data == 'success')
{
alert(data); // <<<< alerts "true"
}
else if(data == 'error')
{
alert('Database error');
}
else{
alert('');
}
}
);
});
});
Just wrote it on here, so i haven't tested it. But give it a try, at least you might be able to know where the error is coming from. If you still get the same error, try alert data before the if(data == 'sucess'), to see what the profile edit func is returning.