Error JS send post data to controller -CodeIgniter - javascript

I'm developing a web application which is based on CodeIgniter. I'm new to javascript and JS development. I'm sending post data to a method which is located in a controlle r(homepage/questionview). The data I'm sending to the controller doesn't get posted to the controller. Attached you can see the code I am using. Every attempt I made triggers the AJAX error function.
Html code inside the code I'm calling JS method called viewQuestion(id)
<div class="col-md-7 column list-group">
<a href="" id="list" class="list-group-item active" onclick="viewQuestion(<?php echo $question['questionid']; ?>)">
<h4 class="list-group-item-heading"><?php echo $question['questionid'];echo". "; echo $question['questionTitle']; ?></h4>
<p class="list-group-item-text"><?php echo "Vote Count :"; echo $question['votecount']; ?></p>
<p class="list-group-item-text"><?php echo "Asked user :"; echo $question['username']; ?></p>
</a>
</div>
My JS code
I double-checked the URL used and it's accessible.
<script type="text/javascript">
function viewQuestion(id)
{
$.ajax({
url: '<?php echo base_url(); ?>homepage/questionview',
type: 'POST',
data: { listid: id },
success: function () {
alert('suc');
},
error: function (error) {
// alert('error');
console.log(error);
}
});
}
</script>
homepage/questionview (controller)
public function questionview()
{
//echo $listid;
echo $this->input->post('listid');
}

Few options:
-make sure the onclick event is working, add a alert("test") before the ajax call to make sure you are getting there
-on your controller, try echo "test" to make sure you get the response
-use Chrome console to debug your ajax call and make sure its getting to the controller

Put return false; at the end of the ajax code segment and see. Your code will be like this then.
<script type="text/javascript">
function viewQuestion(id)
{
$.ajax({
url: '<?php echo base_url(); ?>homepage/questionview',
type: 'POST',
data: { listid: id },
success: function () {
alert('suc');
},
error: function (error) {
// alert('error');
console.log(error);
}
});
return false;
}
</script>

Related

Ajax request not running used in codeigniter 4 [duplicate]

I am using codeigniter-4 version and trying to auto search in nav bar. I'm trying to send data in post method into controller using ajax. But its not work. And codeigniter 4 don't described details for ajax. below my code sample
input box is -
<input class="form-control mr-sm-2" type="search" placeholder="<?= lang('nav.search'); ?>" aria-label="Search" name='s' id="seachBox">
ajax code is -
$.ajax({
url:<?= base_url('search'); ?>,
headers:{'X-Requested-With':'XMLHttpRequest'},
data:{query:query},
success:function(data){
alert(data);
}
});
and my controller is -
<?php
class Search extends BaseController
{
public function __construct()
{
helper(['common_helper','aws_helper']);
}
public function index(){
echo 'string';
}
}
?>
route is -
<?php
$routes->get('/search', 'Search::index');
?>
Here is the sample code of ajax. (Make sure that you have defined route/controller method for search url)
$.ajax({
url:<?php echo base_url('search'); ?>,
type: 'post',
dataType:'json',
data:{query:query},
success:function(data){
alert(data);
}
});
CI4 Code to get the request data
if ($this->request->isAJAX()) {
$query = service('request')->getPost('query');
var_dump($this->request->getPost('query'));
}
Also, make sure to update csrf token on every request if you are not reloading a page on success. Also, you need to return csrf token in method.
So in that case your method will look like -
if ($this->request->isAJAX()) {
$query = service('request')->getPost('query');
//var_dump($this->request->getPost('query'));
return json_encode(['success'=> 'success', 'csrf' => csrf_hash(), 'query ' => $query ]);
}
So in that case your ajax code will look like -
$.ajax({
url:<?php echo base_url('search'); ?>,
type: 'post',
dataType:'json',
data:{query:query},
success:function(data){
var result = JSON.parse(data);
$("input[name='csrf_test_name']").val(result['csrf']);
}
});

AJAX POST PHP NOT ACCEPTING?

I understand this has been asked multiple times but I am unsure why this isn't working!
<?php
if(isset($_POST['testingajax'])) {
echo "Received";
} else {
echo "Not received";
}
?>
<button onclick = 'sendAjax()'>click me</button>
<script>
function sendAjax() {
$.ajax({
type: 'POST',
url: 'test.php',
data: {
testingajax: 2
},
success: function(data) {
console.log("AJAX POST SENT");
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
This is what shows after clicking the button, it should say Received
I have tried changing the URL to http://localhost/TESTINGPLANNER/src/test.php and ./test.php but no luck. Also, I have changed testingajax: 2 to 'testingajax': 2. From the network screenshot it seems like AJAX it is working so I am not sure where the issue is.

getting the value of a array from controller to view with ajax in codeigniter

I am creating a status update system where i need to upload a image as well as show it when it uploads all using ajax but when i send the image it goes to the database but i cannot access the image in the ajax return
here is the code
<div class="tab-pane fade" id="tabs-2">
<?php echo form_open_multipart('',["id"=>"formupload","name"=>"formupload"]); ?>
<p class="formUnit"> <i class="active_pic"></i>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<button class="uibutton" type="button" id="upload_pic" style="width: 230px; height: 150px;">Upload Picture</button><span id="status"></span>
<?php echo form_upload(["name"=>"imagefile","id"=>"upload_pic" ]); ?>
<ol class="controls clearfix">
<?php echo form_submit(['name'=>'submit','value'=>'Submit',"class"=>"btn btn-primary"]); ?>
</ol>
</p>
<p id="files"></p>
<?php echo form_close(); ?>
</div>
now ajax
jQuery('#formupload').submit(function(e){
e.preventDefault();
var formData = new FormData(this);
var url= '<?php echo base_url("user/postData_image"); ?>';
formData.value
jQuery.ajax({
type: "POST",
url:url,
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data)
{
console.log(data);
$('#output_post').attr('src',data);
},
error: function(data){
//error function
}
});
});
now controller
public function postData_image()
{
$config = [
'upload_path' => './uploads/',
'allowed_types' => 'jpg|gif|png|jpeg',
'max_size' => 10000000000000,
'max_width' => 1024000000,
'max_height' => 7680000000,
];
$this->load->library('upload', $config);
$this->upload->initialize($config);
$imagefile="imagefile";
if(!$this->upload->do_upload($imagefile))
{
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/profile',compact('upload_error'));
}
else
{
$post = $this->input->post();
//print_r($post);
unset($post['submit']);
$upload_data = $this->upload->data();
$file_name=$_FILES['imagefile'];
$this->load->model('Pmodel');
$post_data=$this->Pmodel->post_data_image($post,$file_name);
$post['data']=$post_data;
echo $image_path= base_url("uploads/".$upload_data['raw_name'].$upload_data['file_ext']);
return $post;
}
}
model
public function post_data_image($arr,$arra)
{
$id=$arr['id'];
$image=$arra['name'];
$data=array('image'=>$image);
$query=$this->db->insert('post_status',['user_id'=>$id,'image'=>$image]);
return $query;
}
but how to return the value that is generated after insert in the database using ajax
You want to output your post as json so jquery can interpret it.
echo json_encode($post);
To your ajax function add:
dataType: 'json'
And then data will be an array you can use.
Thanx to #Callombert i got the answer for what i was looking i wanted to return the value and 'echo json_encode('$image_path) or $post would return the value in the json form thus you cacn access it in your view
for someone else looking for an answer just add echo json_encode($image_path);
To your ajax function add:
dataType: 'json'
this would get you working.

Ajax + Controller Action in Yii2

I'm new to programming, and I'm trying to call a function when the user inputs data and clicks submit button. I'm using Yii2 and I'm not familiar with Ajax. I tried developing a function, but my controller action isn't called.
Here is the example code I'm trying:
views/index.php:
<script>
function myFunction()
{
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {searchname: $("#searchname").val() , searchby:$("#searchby").val()},
success: function (data) {
alert(data);
}
});
}
</script>
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Supermarkets</h1>
<ul>
<select id="searchby">
<option value="" disabled="disabled" selected="selected">Search by</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input type="text" value ="" name="searchname", id="searchname">
<button onclick="myFunction()">Search</button>
<h3> </h3>
Controller:
public function actionSample(){
echo "ok";
}
My problem is that when I click on the Search button nothing happens, and when I try to debug it, the debugger runs no code!
This is sample you can modify according your need
public function actionSample()
{
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
$searchname= explode(":", $data['searchname']);
$searchby= explode(":", $data['searchby']);
$searchname= $searchname[0];
$searchby= $searchby[0];
$search = // your logic;
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'search' => $search,
'code' => 100,
];
}
}
If this will success you will get data in Ajax success block. See browser console.
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {
searchname: $("#searchname").val() ,
searchby:$("#searchby").val() ,
_csrf : '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function (data) {
console.log(data.search);
}
});
you have to pass _csrf tokin as a parameter
_csrf: yii.getCsrfToken()
or you can disable csrf valdation
The correct way to get the CSRF param is this:
data[yii.getCsrfParam()] = yii.getCsrfToken()

AJAX update MYSQL database using function called from HTML generated from PHP

I have a php page generating and displaying a table. for the last row in the table i want to display an image with an 'onclick' function attached. this will send the username for the selected row to a script that will use AJAX to update a database. The table displays fine but the AJAX is not working. my php to display the image is:
echo "<td> <img id='tblimg'
onclick='like('" . $row['Username'] . "')'
src='like.jpg' alt='like/dislike image'
width='80px' height='30px'></td>";
The javascript function is:
<script type="text/javascript" >
function like(user)
{
$.ajax(
url: "update.php",
type: "POST",
data: { 'username': user, 'liked': '1' },
success: function()
{
alert("ok");
}
);
}
</script>
And here is update.php:
<?php
$con=mysqli_connect("","sam74","********","sam74");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Username = $_POST['username'];
$Liked = $_POST['liked'];
$sql = "UPDATE 'followers' SET 'Liked' = '$Liked' WHERE 'Username' = '$Username'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
There are some mistakes in this code, let me help you line by line.
echo "<td> <img id='tblimg'
onclick=\'like('" . $row['Username'] . "');\'
src='like.jpg' alt='like/dislike image'
width='80px' height='30px'></td>";
The javascript function is:
Escape your quotes for the onclick event first
function like(user)
{
$.ajax({
url: "update.php",
type: "POST",
data: { 'username': user, 'liked': '1' },
success: function()
{
alert("ok");
}
});
}
add { and } to the ajax call
Remove the quotes from table name and fields
$sql = "UPDATE followers SET Liked = '$Liked' WHERE Username = '$Username'";
in ajax success and after the function begins, you can always print a message to see if your function is being called, and if php script is returning some error, use an alert for that
UPDATE
success: function(data){
alert(data); // this will print you any php / mysql error as an alert
}
UPDATE 2
Write your onclick option like this.
echo "<img onclick=\"like('" . $row['Username']. "');\"
src='like.jpg' alt='like/dislike image'
width='80px' height='30px' />";
The jQuery.ajax() function expects an object to be passed; you need to use { and } to begin and end your object literal. What you currently have is invalid JavaScript syntax, if you checked your browser's developer tools you'd see an error indicating that. So:
$.ajax(
url: "update.php",
type: "POST",
data: {
'username': user,
'liked': '1'
},
success: function () {
alert("ok");
}
);
should be
$.ajax({ // added {
url: "update.php",
type: "POST",
data: {
'username': user,
'liked': '1'
},
success: function () {
alert("ok");
}
}); // added }

Categories

Resources