Ajax request sent fine but i didnt get the response - php

I make an AJAX request like this
$.ajax({ type: "POST",url: "<?php echo site_url('home/view_most'); ?>",async: true,data: "view=most_booked", success: function(data)
{
if(data != 0)
{
$("#view_most").html(data);
}
else
alert("Error");
}
});
In controller i get through
public function view_most()
{
$view_most = $this->input->post("view");
}

The response that ajax request is what server echoes so you must echo some value to get the response and handle the response in your success function. In your case does not echo anything thats why you are not getting any response. For example:
public function view_most()
{
$view_most = $this->input->post("view");
echo '0';
}
Try this and you will get 0 as response.

not too familiar with the php codeigniter platform but I think you are not returning any data and that is why you dont see any data.. I am guessing you need to do something like the following at the end of your action code.
$this->load->view(viewName);
Thus your action code should be
public function view_most()
{
$view_most = $this->input->post("view");
$this->load->view($view_most);
}
Here is a quick introduction of AJAX on codeigniter: http://mrforbes.com/blog/2009/01/a-quick-code-igniter-and-jquery-ajax-tutorial/

Related

Ajax POST, check PHP $_GET and then $_POST

Using the following Ajax POST function on form submit (simplified here):
$form.on("submit", function (i) {
i.preventDefault();
var sendEmail = 1;
ValidateForm(sendEmail, "goSignup");
});
function ValidateForm(sendEmail, action) {
$.ajax({
type: "POST",
url: window.location.pathname,
dataType: "json",
data: {
ajaxRequest: 1,
sendEmail: sendEmail,
}
}
After I post this I want to use a conditional GET parameter that equals 1 (i.e https://www.example.com?test-parameter=1) and then if it's present in the URL use one or another function from there if the ajaxRequest is received from $_POST in my PHP:
public function __construct() {
$testingParameter = $_GET["test-parameter"] ?? '';
if (trim($testingParameter) == '1') { // if has get parameter equal
if (!empty($_POST['ajaxRequest'])) { // if JS postRequest has been posted
$this->handlePostRequests();
}
echo 'has get parameter';
} else { // else use old logic
if (!empty($_POST['ajaxRequest'])) {
$this->handleOtherRequests();
}
echo 'no get parameter';
}
}
Issue:
I get the correct echo from PHP but when I submit the form with Ajax its still using the handleOtherRequests(); instead of the handlePostRequests(); function if I'm using the url www.example.com?test-parameter=1.
Likely getting some basic PHP logic wrong here, would appreciate if anyone could guide me in the right direction with this.
url: window.location.pathname,
Your Ajax is never going to POST the data to a URL with a query string because you explicitly took only the path name.
Maybe you want location.href instead.

Request ajax writes the data and returns ok but brings json and html

I'm trying to make an AJAX request. The update is done in the database, but it does not fall into success, if I remove the dataType, it arrives at success, however of both forms it is returning the JSON and HTML when it should return only the JSON.
I could not see anything out of the ordinary in the code. Why this happens. Would my JSON be invalid in any way?
Javascript
$(document).ready(function () {
$('#depositar').submit(function () {
var form = $(this);
var dados = $(this).serialize();
$.ajax({
url: 'http://localhost/caixamvc/conta/depositar',
method: 'POST',
dataType: 'json',
data: dados,
beforeSend: function () {
$("#retorno").html('Aguarde, validando dados...');
},
success: function (resposta) {
$("#retorno").html(resposta.dados);
}
});
return false;
});
});
Controller
public function depositar() {
if (isset($_POST['valor'])) {
$value = $_POST['valor'];
$json = [];
if ($_SESSION['tipo_conta'] == 1) {
$conta = new ContaCorrente;
} else {
$conta = new ContaPoupanca;
}
$conta->depositar($_SESSION['user'], $value);
if ($conta->getResult()) {
$json['dados'] = "Tudo certo";
}else{
$json['retorno'] = "Nada aqui";
}
echo json_encode($json);
}
$this->loadTemplate('depositar', $this->getData());
}
View
<h4>Depositar</h4>
<form id="depositar" method="POST">
Conta:<br/>
<input type="text" name="valor" /><br/><br/>
<input type="submit" name="depositar" value="Depositar"/>
<div id="retorno"></div>
</form>
Response
In your controller you conditionally return JSON:
if (isset($_POST['valor'])) {
//...
echo json_encode($json);
}
But then always return HTML:
$this->loadTemplate('depositar', $this->getData());
When not returning JSON (the condition is false), this returns valid HTML. But when the condition is true you end up returning both to the client. So the response is neither valid JSON nor valid HTML.
When returning JSON, don't also return HTML. It has to be one or the other:
if (isset($_POST['valor'])) {
//...
echo json_encode($json);
} else {
$this->loadTemplate('depositar', $this->getData());
}
Ideally you would use two different controller actions for this entirely. One which displays the page, another which returns the data. That way you don't have one function which does multiple things and needs if conditions to check which thing it's supposed to do.
Each function should do one thing.
The docs say that dataType is:
The type of data that you're expecting back from the server.
While you are echoing out some JSON, you are actually returning HTML. This is because you’re doing one (or both) of these:
Still rendering the template. So the response is some JSON and then an HTML page, both stuck together.
Just because you’re echoing out JSON, doesn’t mean it’s JSON. See a question like Returning JSON from a PHP Script for how to correctly return JSON as JSON.

Ajax is not working in server but works fine in local host

Ajax call is not working in entire site. But works fine in localhost. I cannot able to debug this issues.
I have used ajax entire website. I totally fed up.
Anyone please help me to fix this bug!!
One of my Sample Ajax Code:
function advanced_addTopic(cid) {
$.ajax({
url: "assets/php/checkSubtopicStatus.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {'cid':cid}, // Data sent to server, a set of key/value pairs (i.e. form fields
success: function(data) // A function to be called if request succeeds
{
if(data==="True"){
$("#subtopicDiv").html($("#subtopicDiv"+cid).html());
$("#advanced_testid").val(cid);
var hiddenCourse=$("#createTest").attr('class');
$("#courseHidden").val(hiddenCourse);
$("#advanced_addquestionModal").modal('show');
$("#subtopic").focus();
$("#question").focus();
var tempVal=$("#getID").text();
$("#advanced_courseHidden").val(cid);
} else {
alert("Create subtopics to insert questions!");
}
}
});
My PHP Code is here:
<?php
class loginValidation {
function validate()
{
ob_start();
session_start();
include "../../connection.php";
$id=$_POST['cid'];
$query = mysql_query("select * from advanced_subtopic where testid='$id'");
if(mysql_num_rows($query)>0) {
echo "True";
}
else {
echo "False";
}
}
}
$loginValidation=new loginValidation;
$loginValidation->validate();?>
My Concosole Log
CONSOLE RESPONSE
Instead of
(data==="True")
we should code like
($.trim(data)=="True")
Should trim the data to avoid unwanted space.
Problem solved.

Calling php function with ajax and passing return value to div

I have a function that adds social buttons to my blog posts , but once i load more posts using ajax I cant figure out how can I call add_social_buttons() and pass the data to div.
I'm not really familiar with ajax , i tried this method :
$.ajax({
type:"POST",
url:"functions.php",
data: "social_sharing_buttons()",
success: function(data){
$('.pp').html(data);
}
but it seems that it tries to invoke some totally other function Fatal error: Call to undefined function add_action().
As far as I am aware, you can't. What you can do is have a handler file for your classes, so for example say we have this PHP class,
<?php
class Car {
function getCarType() {
return "Super Car";
}
}
?>
Then in your handler file,
<?php
require_once 'Car.php';
if(isset($_POST['getCarType'])) {
$car = new Car();
$result = $car->getCarType();
echo $result;
}
?>
You'd post your AJAX request to the handler, you could make specific handlers for each request or you could have a generic AJAX handler, however that file could get quite big and hard to maintain.
In your case you'd have in that data,
"getSocialButtons" : true
Then in your AJAX handler file,
if (isset($_POST['getSocialButtons'])) {
// Echo your function here.
}
Then you'd echo out the function within that if statement and using the success callback in your AJAX request do something like this.
document.getElementById("yourDivId").innerHTML = data
That is assuming you're using an ID. Adjust the JS function to suit you.
Try to call that function social_sharing_buttons() like this in function.php:
$.ajax({
type:"POST",
url:"functions.php",
data: {action: 'add'},
success: function(data){
$('.pp').html(data);
}
in functions.php
if(isset($_POST['action']) && !empty($_POST['action'])) {
if($_POST['action'] == 'add') {
echo social_sharing_buttons();
}
}

Post method not working in Codeigniter

I am using HMVC codeigniter. I am trying to use jquery ajax first time. When i use POST then it gives undefined error while it response me the data while using GET.
$.ajax({
type: "POST",
url: filelink+"cart/add_cart_item",
data: {"product_id":id,"quantity":qty,"ajax":"1"},
dataType: "json",
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + " " + errorThrown);
}
});
What I have tried so far after googling and SO-ing-
my file url location is accessible directly. I checked it. giving response.
Firebug is giving 500 internal server error for the same file.
Using Get is responding me back well
added json in the datatype
controller function
class Cart extends CI_Controller { // Our Cart class extends the Controller class
function __construct()
{
parent::__construct();
$this->template->set('controller', $this);
}
function _remap()
{
$uri2 = $this->uri->segment(2);
if (is_numeric($uri2) OR $uri2 == FALSE) {
$this->index();
} else if ($uri2 == 'add_cart_item') {
$this->add_cart_item();
} else if ($uri2 == 'show_cart') {
$this->show_cart();
}
}
function add_cart_item(){
echo "asdfsadfdsf";
exit;
}
}
can anybody please help me out?
There are possible reasons for your problem
You might be using model which is not loaded.
There might be some code problem in the model.
You may not be returning anything from your model and echo it.
Also if you need the data back use echo json_encode($data)
Sometimes this problem arises when you have loaded the site as https://example.com but the url in your ajax call is http://example.com .
Managed to find the solution. The problem was due to CI_TOKEN which is sent with the FORM. That was absent and due to which POST method was giving 500 Internal server Error. I added following in my view file.
<?php echo form_open_multipart(); ?>
<?php echo form_close(); ?>
and sent ci_token with the ajax post request.
var ci_token = formObj.find('input[name=ci_token]').val();
var qty = 1;
var dataString = 'product_id='+ id + '&quantity=' + qty + '&ajax=' + 1
+'&ci_token=' + ci_token;
This solved the problem. I am not sure but this is called CSRF related some problem
Thanks
you have used _remap function and after getting $uri2 there is an if check which is checking the quantity variable you have passed in your ajax request and it may have integer value as obvious may contain some integer.
there for
$this->uri->segment();
returns you:
product_id=id
quantity=qty
ajax=1
and you take value 2 that is quantity by calling
$uri2 = $this->uri->segment(2);
it will return quantity to you and you have not defined an index() function in your code which gives 500 error
function _remap()
{
$uri2 = $this->uri->segment(2);
if (is_numeric($uri2) OR $uri2 == FALSE) {
$this->index();
} else if ($uri2 == 'add_cart_item') {
$this->add_cart_item();
} else if ($uri2 == 'show_cart') {
$this->show_cart();
}
}

Categories