Ajax call request in CodeIgniter with CSRF enabled - javascript

I am using an ajax call to save value of a radio button through hidden field in database using ajax call, used an alert to see if its working, and it is.
The URL I mentioned in the ajax call is redirecting it to a controller but I used an alert to see if its working, but its not working. Can't locate what's the issue.
Here is the code of ajax call in view:
<script type="text/javascript">
$('#save').click(function(){
var hint=$('#hidfield').val();
alert('Oops, your response is '+hint);
$.ajax({
url: '<?php echo base_url();?>welcome/save_answer',
type: "post",
dataType: "html",
data:{hint:$hint, <?php echo $this->security->get_csrf_token_name();?>: "<?php echo $this->security->get_csrf_hash();?>"},
success: function(data) {
}
});
});
</script>
Here is the controller:
function save_answer()
{
alert('You Can Do It !!');
$data = array(
'hint'=>$this->input->post('hint')
);
$this->base_model->save_answer($data);
}
Here is the model:
function save_answer($data)
{
$this->db->insert('questions',$data);
}
Please suggest some way out.

You cannot used javascript "alert()" inside controller.
instead of "alert('You Can Do It !!');" use "die('You Can Do It !!');" to debug, and check in to your console.

Related

Yii2 Ajax Submission not working

Iam new to Yii2 and Ajax
I want to add multiple job for a work ,for that I pass id to WorkJobs Controller
This is my code for ajax submission
<?php
$this->registerJs(
'$("body").on("beforeSubmit", "form#w1", function() {
var form = $(this);
if (form.find(".has-error").length) {
return false;
}
$.ajax({
var jobid = "<?php echo $id;?>";
url: form.attr("work-jobs/create&id="+jobid),
type: "post",
data: form.serialize(),
success: function(errors) {
alert("sdfsdf");
// How to update form with error messages?
}
});
return false;
});'
);
?>
But it's not working ,I don't know what's wrong in my code ,please help ...........
change your code like below
<?php
$url=Yii::$app->urlManager->createUrl(['work-jobs/create','id'=>$id]);
$this->registerJs(
'$("body").on("beforeSubmit", "form#w1", function() {
var form = $(this);
if (form.find(".has-error").length) {
return false;
}
$.ajax({
url: "$url",
type: "post",
data: form.serialize(),
success: function(errors) {
alert("sdfsdf");
// How to update form with error messages?
}
});
return false;
});'
);
?>
Building off jithin's answer, make the following changes to your $.ajax() call
Make sure your URL is in quotes. It is a common mistake to forget to quote the URL when interspersing it with PHP. [jithin]
Unlike jithin's answer, you should do the following
instead of responding to the beforeSubmit event, handle the submit event. This would allow the Yii clientsoide validations do their job
the ajax.success callback takes data as the argument; not error, there's the ajax.failure callback for errors
Try using createAbsoluteUrl() in url like this:
url: "<?php echo Yii::app()->createAbsoluteUrl(\"work-jobs/create&id=\")"+jobid

Ajax not calling success function

I'm using ajax to validate a from without reloadind the page.
Script Ajax
function updateResult(tab){
$.ajax({
url:"requeteSpecimen.php",
data:{datas:tab},
dataType: 'text',
async:false,
success: function(data){
document.getElementById('resultat').innerHTML = '<p>'+data+'</p>';
},
error: function(data){
document.getElementById('resultat').innerHTML = '<p>ERROR</p>';
}
});
}
$("#filtre").submit(function(){
<?php $tab=$this->request->data; ?>
updateResult(<?php json_encode($tab);?>);
});
</script>
requeteSpecimen.php
<?php echo "Success"; ?>
My problem is that ajax do not call the sucess function, I always have the "ERROR" text appearing ...
For the moment I don't have yet the code of my requeteSpecimen.php file and I just would like the success function to be called. Don't know if it can help but I'm using cakePHP 3.0.
Many thanks in advance.
You do not call actions like that in Cakephp.
First set up an Action in one of your Controllers call the url from your $.ajax function like this.
function updateResult(tab){
$.ajax({
url:"/controller/request_specimen",
data:{datas:tab},
dataType: 'text',
async:false,
success: function(data){
document.getElementById('resultat').innerHTML = '<p>'+data+'</p>';
},
error: function(data){
document.getElementById('resultat').innerHTML = '<p>ERROR</p>';
}
});
}
You could later on add a route for request_specimen and make it prettier.
In your Controller there should be a method called: public function request_specimen() {} Wich will handle the ajax request like so: if($this->request->is(['ajax']) { /* Handle request */}
The data sent to the function will be in $this->request->data;

Usage of Ajax post

EDIT:
This is what i managed to build...but it still dont work..
$(document).ready(function(){
$("tr").click(function(){
txt=$("input[name=path]").val();
$.ajax({
type: "POST",
url: contract.php, // the same page where i have the table
data: txt, // the variable containing the dynamic id from the clicked row
success: success, // i have no idea what is this parameter for....
dataType: dataType // i have no idea what is this parameter for....
});
});
});
PHP:
$row=mysql_fetch_array($query){
echo '<tr id="'.$row['id'].'">';
echo '<td></td>';
echo '</tr>';
}
What i want,is when the user click on a row , the row id(which is dynamic), must be taken , and returned with ajax post , so i can use it in another query.I have to do this without reloading the page, thats why i try to do it with ajax.
If it's ok to use jQuery i would use something like this to build my table (beside the mysql_*):
<?php
$row=mysql_fetch_array($query){
echo '<tr class="listContractRow" data-path="'.$row['id'].'">';
echo '</tr>';
}
?>
Then catch the click event with a jQuery listener:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).on('click','tr.listContractRow', function(e){
var path = $(this).data('path');
//Use the variable path here in your AJAX call
//Assuming you want a GET request, you can also use $.ajax or $.post here
$.get('YOUR_AJAX_URL_HERE?path='+path, function(){
//Do something after the ajax call
});
});
</script>
EDIT
In your PHP you can do something like:
<?php
if(isset($_GET['path']))
{
//Query here with the variable $_GET['path'];
//Echo the results you want
//Perform an exit here, since it's an AJAX call. You probably don't want to echo the code below (if there is)
exit();
}
?>
jquery ajax get example
$.ajax({
type: "POST",
url: "index.php",
data: "{param: "param"}",
success: function(msg) {
},
error: function(err) {
}
});

Passing Php variable it Ajax

Hi I'm trying to pass a php variable from produto.php to another file descProduto.php it ajax but without success. Please someone can tell me what I'm doing wrong? The ajax is working but I can't get the value on descProduto.php
This is where I click produto.php
<img class="btn-details" src="plus.png" data-idproduto="'.$idproduto.'"/>
My ajax ( diferent file ajax.js)
$(function(){
$(".btn-details").on('click', function(){
var idproduto = $(this).data('idproduto');
$.ajax({
type: "POST",
url: "descProduto.php",
async: false,
dataType: "html",
data: {'idproduto': idproduto},
success: function(result){
console.log("success");
},
error: function(){
console.log("error");
}
});
return false;
});
});
Where I get the variable descProduto.php
if(isset($_POST['idproduto'])){
$idproduto = $_POST['idproduto'];
echo $idproduto;
}
Thanks
Why using AJAX ? .You can't use for this matter.just use session
In page1.php
<?php
session_start();
$_SESSION['var'] = 'foo'
In Page2.php
echo $_SESSION['var']; //foo
First of all check whether your $idproduto actually prints on produto.php (Developer Tools/ FireBug/ View Source).
Then console.log(idproduto) before sending the ajax post to see whether it sets correctly.

Form or jQuery Ajax?

When a form sends variable with GET Method, the URL changes, putting the variables that you are passing in this way
url?variable=....
How can I get the same result with jQuery Ajax? Is it possible? Thank you
set path in your php layout/view file where you include this code
<script>
var path="<?php echo $this->webroot;?>";
</script>
and add following jquery code to post the data through ajax.
$.ajax({
type: 'POST',
url: path+'homes/createEvent',
data: {eventname:eventname,manager:manager},
async: false,
success: function(resulthtml)
{
alert(resulthtml);
},
error: function(message)
{
alert('error');
}
});
and on homes_controller.php, u will get this ajax data in createEvent function,
<?php
function createEvent()
{
$eventName=$_POST['eventname'];
$manager=$_POST['manager'];
}
?>

Categories

Resources