This question already has answers here:
using jquery $.ajax to call a PHP function
(6 answers)
Closed 7 years ago.
This seems straightforward, but I can't get it to work. I have a button, when it's clicked I'd like to execute a php function which is defined in the same file as the button. My code is below, I get the "clicked" alert when the button is clicked, but no alert on response from the function.
//this is in myfile.php
<?php
echo '<button type="button" name="save_button" onclick="save()">Save</button>';
?>
<script type="text/javascript">
function save()
{
alert("clicked");
$.ajax({
url: 'myfile.php',
type: 'post',
data: { "set_description": ""},
success: function(response) { alert(response); }
});
}
</script>
<?php
function set_description() {
return "a string";
}
?>
Change the type of the jquery Ajax code from post to get since you want to use the response, else I can't see something wrong there
Related
This question already has answers here:
How to put php inside JavaScript?
(7 answers)
Closed 3 years ago.
Here I have an < a ... onclick='show(); / a >. I want to add my php code to to js function, I mean to get action after click.
include($_SERVER['DOCUMENT_ROOT'] . '/model/action.php');
?>
I'm going to put php code in this script
<script>
document.getElementById("show").onclick = function() {show()};
function show() {
document.getElementById("numb").style.display="block";
<<<HERE>>>
}
</script>
With the addition of jQuery you can use ajax function to call a php script
<script>
$.ajax(
'request_ajax_data.php',
{
success: function(data) {
alert('AJAX call was successful!');
alert('Data from the server' + data);
},
error: function() {
alert('There was some error performing the AJAX call!');
}
}
);
</script>
This question already has answers here:
How to prevent buttons from submitting forms
(20 answers)
Closed 5 years ago.
Im experiencing a weird error in an ajax request. upon calling an alert in both error and succes, the alerts arent displayed. This implies that the ajax request isn't processed. But I have no clue whatsoever why this is the case. Code is below.
var bool;
function set(n, thread_id) {
bool = n;
// update_upvotes(thread_id);
}
function vote(thread_id) {
if (bool == 1) {
alert("begin ajax");
$.ajax({
type: "POST",
url: "../includes/thread_upvotes.inc.php",
data: {
thread_id: thread_id
},
succes: function(data) {
alert("data:"+data);
},
error: function() {
alert("hi, im broken");
}
});
} else {
$.ajax({
type: "POST",
url: "../includes/thread_downvotes.inc.php",
data: {
thread_id: thread_id
}
});
}
}
Here the form which calls the function
<iframe class="foo" name="foo" id="foo"></iframe>
<form class="voteform" target="foo" onsubmit="vote('.$thread_id.') & update_upvotes('.$thread_id.');">
<button onclick="set(1);" id="'.$thread_id.'1" name="upvote" type= "submit" class="vote right up" value="'.$thread_id.'"> '.$num_upvotes.' </button>
<button onclick="set(0);" id="'.$thread_id.'0" name="downvote" type= "submit" class="vote left down" value="'.$thread_id.'"> '.$num_downvotes.' </button>
</form>
Thanks in advance.
EDIT: This post has been marked as a duplicate, the answer provided by the person who marked this as a duplicate is not satisfactory. We removed the form out of our code and the ajax request is still not being processed...
It seems this url "../includes/thread_upvotes.inc.php", is wrong. Remove the dots
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 years ago.
I inserted an onclick to my button but don't know where I'm going wrong here but it seems like the function is fired each time the page is loaded.
How can I call the function ONLY when clicking on the button itself
<button type="submit" class="btn btn-primary" onclick="<? $query = DB::update('ads')->set(array('sale_agreed' => '999'))->where('id_ad', '=', $msg_thread->ad->id_ad)->execute(); ?>"><?=_e('ACCEPT This Offer')?></button>
Any take on this? Thanks ;-)
You can make use of jQuery Ajax to perform this operation.
Add a button with some id.
<button id="click-button"></button>
Inside your script tag.
$(document).read(function(){
$("#click-button").click(function(){
$.ajax({
url: "remote-file.php",
method:"POST",
data:"token=buttonclick",
success: function(result){
if(result != "fail"){
//Perform actions with the results...
}
}});
});
});
In you PHP remote-file.php
<?php
if(isSet($_POST['token']) && $_POST['token'] == 'buttonclick'){
$result = myFunction();
echo $result;
}else{
echo "fail";
}
function myFunction(){
// Perform your DB actions...
return true; //Return your data
}
?>
You can't use php functions from client side. The attribute "onclick" fires a javascript funciont, not a php one.
In order to execute a php function with onclick, you have to make an Ajax request to the server.
$('.button').click(function() {
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.success(function( msg ) {
alert( "Data Saved: " + msg );
});
});
In the "url" variable you have to put the url to your php script, and the data object contains all the PHP $_REQUEST parameter to be send to the script. The success function executes once the script is complete.
Button click is client side whereas PHP is server side, but you can achieve this by using AJAX.
$('.button').click(function() {
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
In your PHP file:
<?php
function abc($name){
//your code here
}
?>
You cant add php functions to client side button clicks.
You should get your PHP to check if the page has been submitted and then run your function
This question already has answers here:
processing $_POST in codeigniter
(3 answers)
Closed 6 years ago.
View:
<table>
<tr>
<td id="percentage">Percentage: <?php echo $percentage; ?> %</td>
</tr>
</table>
<div class="box-footer" style="float: right">
Submit
</div>
<script>
$(document).ready(function () {
var percentage = $("#percentage").text();
console.log(percentage); //Percentage: 28.57 %
$("#submit").click(function () {
$.ajax({
type: 'POST',
url: base_url + "student/Examinations",
data: {percentage: percentage},
success: function () {
}
});
});
});
</script>
Controller:
class Examinations extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index() {
$percentage = $_POST["percentage"];
var_dump($percentage); // var_dump null
}
}
MY Question: javascript variable(percentage) to pass controller , and var_dump is null why?please help me.....................................
Not a user of code igniter myself, but using other frameworks, you better use the request object.
I quickly perused code igniter documentation, and apparently you should do something like that :
$percentage = $this->input->post('percentage');
you have not prevented execution of anchor tag, you have to prvent event of a tag
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: base_url + "student/Examinations", // or you can take $("#submit").attr('href');
data: {percentage: $("#percentage").text()},
success: function(data) {
console.log(data);
}
});
return false;
});
});
It behaves like that because You are doing 2 things here. It looks like that:
You click on link with id="submit"
$(#submit).click() is executed:
ajax call with parameter percentage is executed
ajax call with no handled response ends (empty function in success, so You don't even see result of Your click event)
Web browser continues to act normally - it follows clicked link and goes to url: "<?php echo base_url(); ?>student/Examinations" with no percentage parameter
If You want to send param just modify Your href like that: "<?php echo base_url(); ?>student/Examinations?percentage=sample_value" and check in target script $_GET['percentage']
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
My code doesn't show errors, but also doesn't work as it should. The output from the ajax call is working fine but I just can't get anything out of the onClick, no errors message, nothing.
The HTML
<div id="serials"></div>
<div id="accounts_info_key" style="text-align:left"></div>
The Ajax call
$(document).ready(function() {
$('.tab2').click(function(){
var account_id = $('#account_id').val();
$.ajax({
url: 'ajax/account_info_serials_ajax.php',
type:'POST',
dataType: 'json',
data: 'account_id='+account_id,
success: function(response){
$('#serials').html(response.table),
$('#accounts_info_key').html(response.key),
$('.drop_down').hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
} // End of success function of ajax form
}); //end of ajax
});//close trigger
});//close whole function
The PHP
$response = '';
$response .='<div class="question">';
$response .='plop';
$response .='</div>';
$response .='<div class="drop_down">';
$response .='bob';
$response .='</div>';
$output_array = array(
'table' => $response,
'key' => $key,
'count' => $count
);
echo json_encode($output_array);
The jquery onclick
$(document).ready(function() {
$('#serials').on("click", ".question", function(e){
alert('smeg');
});
});
Please note, I am not asking how to do it, I am asking why my version is not working, it is NOT a duplicate question
I have created a fiddle that shows how it should be done in my opinion http://jsfiddle.net/6VtA8/.
$(document).ready(function () {
$('.tab2').click(function () {
var account_id = $('#account_id').val();
$.ajax({
url: '/echo/json/',
type: 'POST',
dataType: 'json',
data: {'something':'else'}
}).done( function (response) { $('#serials').html('<div class="question ">abcd</div>'); });
});
}); //close whole function
$(document).ready(function () {
$('#serials').on("click", ".question", function (e) {
alert('smeg');
});
});
There are multiple reasons that could cause your code to not work. It could even be the fact that your div (from some css rule) would end up having a height of 0 and therefore the event wouldn't trigger. So instead of debugging I chose to do a little rewriting.
You have to subscribe to the event click on #serials once it's in the dom. So when your ajax callback is over and that .question is in the dom, you subscribe to the click on #serials.