jquery- ajax post to php a null variable [duplicate] - javascript

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']

Related

Calling PHP function when clicking <button type="submit"> [duplicate]

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

Jquery Ajax is not working with Codeigniter

I am a ajax beginner, Here I am trying to show a text box value in same page using Ajax.
My Controller code:
<?php
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
$this->load->view('ajaxtest');
$fullname = $this->input->post("fullname");
echo $fullname;
}
}
?>
Here is my view code:
<head>
<script src="<?php echo base_url();?>assets/js/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post">
<input type="text" id="fullname"/>
<input type="button" value="getinfo" id="getinfo"/>
<span id="mytext"></span>
</form>
</body>
When I click on the button getinfo, I want to show the text inside the text box as span text. But now it shows nothing..
Updated:
After experts' opinion, I edited some text(see my edit note), Now When i click on the button, it shows again a textbox and a button.. !!
Did you set the base_url variable with a link on the Javascript?
Because your post url contains this variable and you need set this to make it work. So initialize the variable with the base_url link.
See the corrected example below . Set your domain instead of the yourbaseurl.com
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function()
{
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
cache:false,
success:
function(data){
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Your base_url variable seems to be undefined in your JavaScript.
One simple approach to get the base URL is to echo it out in a hidden input, and then grab the value of that input in your JS code:
HTML
<input type='hidden' id="baseUrl" value="<?php echo base_url(); ?>" />
JS
var base_url = $('#baseUrl').val();
$.ajax({
type: "POST",
url: base_url + "/merchant/ajaxtest",
data: {textbox: $("#fullname").val()},
dataType: "text",
// ...
you are passing in textbox as parameter from your ajax to controller and trying to get POST data with name fullname. That wont work, since you passed in the name of parameter as textbox, access that in your post, as :
class Merchant extends CI_Controller
{
public function ajaxtest()
{
$this->load->helper('url');
//you dont need to load view so comment it
//$this->load->view('ajaxtest');
$fullname = $this->input->post("textbox"); //not fullname
echo $fullname;
}
}
js
<script type="text/javascript">
$(document).ready(function(){
var base_url='http://yourbaseurl.com/index.php/';
$("#getinfo").click(function() {
var fullname = $("#fullname").val();
alert("Fullname:" + fullname); //do you get this alert
$.ajax({
type: "POST",
url: base_url + "merchant/ajaxtest",
data: {textbox: fullname},
cache:false,
success:function(data){
alert("Response:" + data); //do you get this alert
$('#mytext').html(data);
}
});
return false;
});
});
</script>
Try using this:
<base href="<?=base_url();?>">
<script src="assets/js/jquery-latest.min.js"></script>
And this in ajaxtest:
$this->load->helper('url');
And also Comment out this:
// $this->load->view('ajaxtest');
Might be a little late with this response - but someone might find this while searching for a solution.
I was having the same issues with Codeigniter and JQuery ajax/post response. I could not get this to work no matter what I tried.
In the end, it turned out to be php_error that was causing the problem. Once I removed it, everything worked fine with my post/response.

Wordpress get current page name or id within ajax request callback

I need to get current page id or name from ajax request callback. Initially at loading a page i made an ajax request. In its callback method i need to get the current page id or name. I used following code for ajax request.
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "notes_select_page"
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
I took the request from action hook.
add_action('wp_ajax_nopriv_notes_select_page', 'Notes::select_page');add_action('wp_ajax_optimal_notes_select_page', 'Notes::select_page');
And the callback i used several code but doesn't work. Try 1.
public static function select_page(){
global $pagename;
die($pagename);
}
Try 2
public static function select_page(){
global $wp_query;
$pagename = get_query_var( 'pagename' );
if ( !$pagename) {
$post = $wp_query->get_queried_object();
$pagename = $post->post_name;
}
die($pagename);
}
Try 3
public static function select_page(){
global $post;
die($post->ID);
}
But unfortunately any of them doesn't work to get current page ID or name. Callback is working fine with other values.
Thanks in advance.
function get_current_page_id() {
var page_body = $('body.page');
var id = 0;
if(page_body) {
var classList = page_body.attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item.indexOf('page-id') >= 0) {
var item_arr = item.split('-');
id = item_arr[item_arr.length -1];
return false;
}
});
}
return id;
}
You don't need ajax for this.
Add this function to your code.
You can now get the page id by using:
var id = get_current_page_id();
To retrieve the post details you have to send the data yourself
data:{
action: "notes_select_page",
post_id: current_post_id, //current_post_id should either parsed from DOM or you can write your ajax in PHP file
}
You can either use a hidden box for current post id and get in the Js file using class or id or write the ajax in you php file itself.
Then you can retrieve via POST
public static function select_page(){
$post_id = $_POST['post_id'];
}
I'm getting post ID from the default WordPress post editing form, like so :
var post_ID = jQuery('[name="post_ID"]').val()*1;
Tje *1 converts the ID into an integer, otherwise it's interpreted as a string.
First take page id by this function
either
<div id="current_page_id"> <?php get_the_ID(); ?> </div>
or
<body page-id="<?php get_the_ID(); ?>">
Now In jquery ajax take following
var page_id = $('current_page_id').html();
OR
var page_id = $('body').attr("page-id");
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "pageid="+page_id,
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
There is a solution to solve the issue in Wordpress. Adding ajax code in wp_footer hook, where using php code current page id can be retrieved and pass as ajax value.
You can obtain alternatively by the hidden field the post/page id in the following manner. This code is inserted in the template file (and then the value will be send to your ajax action hook as indicated above):
<?php
echo '<input type="hidden" name="activepost" id="activepost"
value="'.get_the_ID().'" />'
;?>
Check out this for reference: https://developer.wordpress.org/reference/functions/get_the_id/

How to call PHP function using jquery? [duplicate]

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

onClick not working on ajax generated content [duplicate]

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.

Categories

Resources