Ajax attributes post - php

where do you think I'm making a mistake in the process below? I didn't use Ajax very well I don't know I tried searching but I wasn't successful.
Html
<td>Kontrol Et
</td>
<td><div id="loading">Kontrol Edilmedi</div></td>
Ajax
$('.kontrolet').click(function () {
// add loading image to div
$('#loading').html('<img width="50" src="<?php echo base_url("assets/front/images/yukleniyor.gif"); ?>">');
// run ajax request
$.ajax({
type: "POST",
dataType: "html",
kullanici : $(this).attr('kullanici'),
url: "<?php echo base_url("kullanici-kontrol"); ?>",
success: function (d) {
setTimeout(function () {
$('#loading').html(d);
}, 2000);
}
});
});
Controller
public function kullanicikontrol()
{
echo $_POST['kullanici'];
}

I would recommend you to check your code. From what I see it's not valid code. The attribute "kullanici" is not valid for HTML. And the Ajax variable name should be "data" instead of "kullanici".
Try instead:
data-kullanici="testuser"
And for your Ajax call use:
data : $(this).data('kullanici'),
Hope this helps.

Related

JQuery not anticipating on return value

I'm currently trying to use the return value of a PHP script to do a refresh action with jQuery. My PHP script is doing what it should do, return the value "reload" when a certain requirement is met; jQuery then however displays "reload" briefly and doesn't act on the refresh action that I've required it to do.
$.ajax({
url: '/bidstatus.php',
data: {
sale_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
dataType: 'json',
type: 'get',
success: function(output) {
if (output == "reload") {
location.reload();
}
}
});
The PHP that returns the value, when a requirement has been met, looks like this:
echo json_encode("reload");
Also, to make it even more confusing, it sometimes does what it has to do, but it's not consistent at all.
So, am I missing something?
Since I saw this was still open and I managed to fix it myself, I'll post the code so it can/may help others with similar problems.
This was the code that fixed it.
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function()
{
$.post('/bidstatus.php',
{
auction_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
function(data)
{
if(data == "reload"){
location.reload();
}
else{
$('#shop-balance').html(data);
}
}
);
}, 1000);
});
Well, try this:
function do_ajax(callback)
{
$.ajax({
url: '/bidstatus.php',
data: {
sale_id: '<?php echo $sale['Product']['id']; ?>',
token: '<?php echo md5(session_id().$session->read('Auth.User.id')); ?>'
},
dataType: 'json',
type: 'get',
success: function(data){
callback(data);
},
});
}
Just check it again and if you use any global scope variable then pass it through function's parameters.
And call it like this::
do_ajax(function(data) {
if (data == "reload") {
location.reload();
}
}
);
What I have done is to set a callback for your .success state, rather than direct code execution. Since Javascript executes the code asynchronously, it just passes the .success before the AJAX is finished, and thus, the data will not be "output" and it is "null" probably. You shoul add a callback there and execute it through a callback to allow the Javascript Interpreter to accomplish the task.

How to use ajax to pass a variable to a php file using POST method?

I have modified the code
to POST prodID to ProductsList.php
// its a dynamically generated drop menu
while($rowmnu2=mysql_fetch_assoc($resulmnusub2))
{
echo '<li><a id="'.$rowmnu2['liid'].'" href="#" onclick="passto(this.id)">'.$rowmnu2['title'].'</a></li>
';
}
and here is my ajax function :
function passto(val){
//window.location.href="ProductsList.php?idd=" + val;
$.ajax({
url: 'ProductsList.php',
type: "POST",
data: ({prodID: val}),
success: function(data){
//or if the data is JSON
window.location.href="ProductsList.php";
}
});
}
the passed element to the function is an integer
in the ProductsList.php I have
<?php
if(!$_POST['prodID']) die("There is no such product!");
echo $_POST['prodID'];
?>
and I get There is no such product! while there should be an INT #
why is that ?
any one knows? all the bellow suggestions are not responding correctly
$(document).ready(function() {
$("a").click(function(event) {
myid = $(this).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID: myid},
dataType: "json",
complete:function(){
window.location("ProductsList.php");
}
});
});
});
if you want to POST id , you can change:
...onclick="passto(this)"...
to
...onclick="passto(this.id)"...
That behavior is normal because you are requesting ProductsList.php twice. the first time with an AJAX request using $.ajax. for that time the id is sent correctly. The problem is that you request ProductsList.php again just after AJAX complete using window.location.href="ProductsList.php"; without sending anything. So the result is as expected, a page printing There is no such product!
You can fix the problem by replacing window.location.href="ProductsList.php"; by this one :
$('body').html(data);
or any other instruction to use properly the returned data.
You can either use my edited code or just edit yours :
echo '<li ><a id="'.$rowmnu2['link'].'" href="#">'.$rowmnu2['title'].'</a></li>';
JS part :
$('a').click(function() {
var val = $( this ).attr('id');
$.ajax({
type: "POST",
url: "ProductsList.php",
data: {prodID:val},
complete:function(){
$('body').html(data);
}
});
});

CodeIgniter, Ajax call does not get into Controller

After looking at a solution on ci-ajax-csrf-problem I added the following line into the script and it works fine.
var post_data = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
}
inserted into
$.ajax({
url: '<?php echo base_url()."ajax/test";?>',
type:'POST',
dataType: 'json',
data: post_data,
Thank you for the help everyone :)
I am new to Ajax/Jquery and was following a guide on Ajax for CodeIgniter from jorge torres to implement a simple ajax call on my website and ran into problems.
I created a Controller Ajax and this is the code snippet.
class Ajax extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function test() {
$output_string = 'This is a test';
echo json_encode($output_string);
}
public function test2(){
$this->load->view('test.php');
}
}
And this is the view for that controller, its identical to the one from the tutorial except I added loaded the url helper $this->load->helper('url'); on the first line
Here is the snippet for the script code.
The #getdata is a button type and #result_table is a div
$('#getdata').click(function(){
$.ajax({
url: '<?php echo base_url().'ajax/test';?>',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
I can successfully access localhost.com/codeigniter/ajax/test2 but when I clicked the button, nothing happen.
I tried looking at the page source info and the url is correct
$.ajax({
url: 'http://localhost/codeigniter/ajax/test',
type:'POST'
....
Accessing localhost/codeigniter/ajax/test directly is also possible and it display the output message.
I am using CodeIgniter 2.1.3 and my localhost is running on XAMPP 1.7.3
Thank you in advance :)
After looking at a solution on ci-ajax-csrf-problem I added the following line into the script and it works fine.
var post_data = {
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
}
inserted into
$.ajax({
url: '<?php echo base_url()."ajax/test";?>',
type:'POST',
dataType: 'json',
data: post_data,
Thank you for the help everyone :)
Did your .click() event handler works as expected?
$('#getdata').click(function(){
alert('clicked');
........
if no, try to wrapped the jquery code in $(document).ready(function() { ... }); as #Sudhir suggested:
$(document).ready( function() {
$('#getdata').click(function(){
alert('clicked');
........
});
if yes, in case you don't know it yet, there's a tool called firebug to check your AJAX request.
I thinks there's no problem with your AJAX url.
So far, this is my answer. Hope this helps too.
Do you have output compression enabled(gzip) in your config.php? If you compress your output it will fail when you use echo and return the 500 server errors.
I think there is an issue with your ajax call . Should be like this I think :
$(document).ready (function () {
$('#getdata').click(function(){
$.ajax({
url: '<?php echo base_url()."ajax/test";?>',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
If the firebug console says that The action you require is not allowed, then it may be a CSRF token issue, turn it off in the codeigniter config.
Add this in config file.
$config['csrf_protection'] = FALSE;
Hope this helps :)
Have you tried
$(document).ready (function () {
$('#getdata').click(function(){
$.ajax({
url: '/ajax/test',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
as apposed to <?php base_url; ?>
Have you entered your site url into the CI config?

Calling PHP function using ajax not working

I am calling a php function using ajax call but its not working. I have a table with some rows when I click on any column of a row it becomes editable with its value but when I edit the value and click on another column or enter the changed value is not displayed again. Actually I am doing an ajax call where I change the data of the column in my table but its not calling that php function.
My script is as follows
<script type="text/javascript" >
$(document).ready(function()
{
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#span_"+ID).hide();
$("#input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var input=$("#input_"+ID).val();
var dataString = 'id='+ ID +'&data='+input;
$("#span_"+ID).html('<img src="load.gif" />'); // Loading image
if(input.length>0)
{
$.ajax({
type: "POST",
url: "worker_app::edit_ajax()",
data: dataString,
cache: false,
success: function(html)
{
$("#span_"+ID).html(span);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
The HTML table looks like this
<tbody>
<tr id="{IDWORKERS}" class="edit_tr">
<td class="edit_td">
<span id="span_{IDWORKERS}" class="text">{FIRM}</span>
<input type="text" value="{FIRM}" class="editbox" id="input_{IDWORKERS}" />
</td>
</tr>
</tbody>
And the php function is inside apps folder in a file called wroker_app.php
public function edit_ajax(){
///echo "<pre>";
///print_r($_POST);
//echo "</pre>";
// sql to update the database goes here
echo 'I am here';
}
Any ideas?
Thanks in advance
You can not call specific functions using the request alone. You need to tell your script that edit_ajax is supposed to be executed.
So change your url to worker_app.php, listen for the request using a (e.g) get variable like ?[function].
if (isset($_GET['edit_ajax']) && function_exists($_GET['edit_ajax']))
edit_ajax();
You cant call a php function like this. You can only call a php file where you can decide which function should be executed.
A simple example:
$.ajax({
type: "POST",
url: "/apps/worker_app.php",
data: dataString,
cache: false,
success: function(html) {
$("#span_"+ID).html(span);
}
});
And in your apps/worker_app.php:
<?php
function edit_ajax(){
echo 'I am here';
}
// You can put some logic before this line to decide which function to call based on the request
edit_ajax();
url: "worker_app::edit_ajax.php"
Where is this url referrs to.
check this reference
jquery .ajax
If you want to call function use try to post any specific post field to that file.
After use below in that file
if($_POST['field']!="") {
requredfunction () {
// your code run here
}
}

Calling javascript function inside jquery ajax response file code

I am trying to call date_cal() javascript function inside ajax response (wall_list.php).Every thing is fine am getting correct response. But its not calling date_cal() function.
main file:
$.ajax({
url: 'wall_list.php',
data:"dt_from="+dt_from+"&dt_to="+dt_to+"&week="+week+"&month="+month+"&dt_filter="+dt_filter+"&fan="+fan+"&gender="+gender+"&pageNumber="+pagenumber,
type: 'POST',
success: function (resp) {
if(resp)
{
//alert(resp);
document.getElementById('wall_listdiv').innerHTML=resp;
}
Wall_list.php
Some code...................
> <td id="<?php print $key; ?>" class="tm_td" valign="top" colspan=2>
>
<script language="JavaScript">
date_cal('<?php print $commentcreatetimearr[$key]; ?>','<?php print $key; ?>');
</script>
> </td>
Some code......................
it's not calling javascript there.
Can anyone explain how to all this function in response.
here you go
$.ajax({
url: 'wall_list.php',
data: "dt_from="+dt_from+"&dt_to="+dt_to+"&week="+week+"&month="+month+"&dt_filter="+dt_filter+"&fan="+fan+"&gender="+gender+"&pageNumber="+pagenumber,
type: 'POST',
success: function (resp){
if(resp){
$("#wall_listdiv").html(resp);
}
},
dataType: 'html'
});
What you want to do is, specify the return dataType as html.
From jQuery API
If html is specified, any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string. Similarly, script will execute the JavaScript that is pulled back from the server, then return the script itself as textual data.
More information here: jQuery.ajax() - jQuery API
for example
php:
<?php echo $commentcreatetimearr[$key]; ?>
js:
$.ajax({
url: 'wall_list.php',
data:"dt_from="+dt_from+"&dt_to="+dt_to+"&week="+week+"&month="+month+"&dt_filter="+dt_filter+"&fan="+fan+"&gender="+gender+"&pageNumber="+pagenumber,
type: 'POST',
success: function (resp) {
if(resp){
$('#wall_listdiv').html(date_cal(resp));
}

Categories