I am trying to test AJAX in CodeIgniter, with no luck so far. Please tell me where I am going wrong.
Here is my test_page.php:
<!DOCTYPE html>
<head>
<script src="<?php echo base_url();?>assets/libs/jquery/jquery-2.2.3.min.js"></script>
<script src="<?php echo base_url();?>assets/libs/jquery/jquery-2.2.3.min.js"></script>
<script src="<?php echo base_url();?>assets/libs/js-cookie/js.cookie.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button id="btn" onclick="gethtml()">ajax Test</button>
<script type="text/javascript">
function gethtml(){
var url = "<?php echo base_url();?>home/ajax_test";
alert(""+url);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function(data){
alert("ajax success");
}
});
}
</script>
</body>
</html>
Here is my function in controller:
public function ajax_test() {
echo "return from ajax";
}
This Type of AJAX Call dataType is not required
Remove
dataType: 'json'
Use like
<script type="text/javascript">
function gethtml(){
var url = "<?php echo base_url();?>home/ajax_test";
alert(""+url);
$.ajax({
url: url,
type: 'POST',
success: function(data){
alert("ajax success");
}
});
}
</script>
You can use below mentioned solution.
<button id="btn">ajax Test</button>
$(document).ready(function(){
$('#btn').Click(function(e){
e.preventDefault();
var url = "<?php echo base_url();?>home/ajax_test";
alert(""+url);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function(data){
alert("ajax success");
}
});
});
});
Let me know if it not works for you.
Error in the above code is the response from the ajax_test() is not encoded into json. So, the error event of json is triggered and the code inside success is not executed.
Always make sure to send json encoded data if you are specifying dataType as json.
Try on view
<button id="btn">ajax Test</button>
<script type="text/javascript">
$('#btn').on('click', function(e) {
// e.preventDefault(); Not sure if you need it.
$.ajax({
url:"<?php echo base_url('home/ajax_test');?>",
type: 'POST',
dataType: 'json',
// data: {
// someinput: $('#someinput').val()
//},
success: function(data){
alert(data['test']);
}
});
});
</script>
On controller you can use the output class also.
public function ajax_test() {
$json['test'] = "return from ajax";
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($json));
}
Related
I have this problem with assigning a certain array variable. When I post it to Codeigniter Controller, It produces this error Click to view Image.
View:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function submit() {
var TableData = {"table1":"sample1","table2":"sample2","table3":"sample3"};
var Data = JSON.stringify(myTableArray);
$.ajax({
type: "POST",
url: "http://janncomputing/tabulation/judges/save_Production",
data: {pTableData : Data},
success: function(result){ //retrieve data
alert('Success');
alert(result); //alert it
}//success
});
</script>
</head>
<body>
<div>
<button type="button" onClick="submit();">SUBMIT</button>
</div>
</body>
</html>
Controller:
public function save_Production()
{
$table = json_decode($_POST['pTableData'],true);
$msg = $table['table1'];
echo $msg;
}
try this
function submit()
{
var TableData = {"table1":"sample1","table2":"sample2","table3":"sample3"};
//var Data = JSON.stringify(TableData);
$.ajax({
type: "POST",
url: "http://janncomputing/tabulation/judges/save_Production",
dataType: 'json',
data: {pTableData : TableData},
success: function(result){ //retrieve data
alert('Success');
alert(result); //alert it
}//success
});
}
i'm new to web and facing issue while using PHP file's constants inside javascript Ajax call.
My PHP code in constants.php file is as:
<?php
$color = 'green';
define ('BASE_URL', 'https://example.com?');
define ('APP_KEY', 'abcde');
define ('USER_KEY', '12345');
?>
My Ajax call in another login.php file is as:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#loginPopup").on('click',function(){
var x = document.forms["login"]["emailId"].value;
var pwd = document.forms["login"]["pwd"].value;
$.ajax({
type: 'GET',
url: 'BaseURL?appkey=abcde&userkey=12345&email='+ x +'&password=' + pwd,
crossDomain: true,
dataType: 'jsonp',
success: function (response) {
showAlert(response);
},
error: function (request, status, error) {
alert("ERROR");
}
});
});
});
</script>
I want to move constants i.e. Base URL, Keys etc to constants file. So i've created constants.php. But now, i don't know how to use that inside ajax call. Please help. Thanks in anticipation.
Like so, assuming the two files are in the same dir:
<?php
require_once('constants.php');
?>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#loginPopup").on('click',function(){
var x = document.forms["login"]["emailId"].value;
var pwd = document.forms["login"]["pwd"].value;
$.ajax({
type: 'GET',
url: '<?php echo BASE_URL ?>?appkey=<?php echo APP_KEY ?>&userkey=<?php echo USER_KEY ?>&email='+ x +'&password=' + pwd,
crossDomain: true,
dataType: 'jsonp',
success: function (response) {
showAlert(response);
},
error: function (request, status, error) {
alert("ERROR");
}
});
});
});
</script>
why it isn't working. Am trying to call a php file when onclick of a button occurs with some parameters. It is getting executed till alert statement in jsfile.js. After that the ajax part is not getting executed.. Help me out.. Thanks in advance..
main.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jsfile.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="cart(0)"> hi </button>
<p id="disp"></p>
</body>
</html>
jsfile.js
function cart(id1)
{
var id=id1;
alert("enterd "+id);
document.getElementById("disp").innerHTML ="hi";
$.ajax({
url:"/add.php ",
type:"POST",
data:{
item_id: id,
},
success:function(response) {
//document.getElementById("total_items").value=response;
document.getElementById("disp").innerHTML =response;
},
error:function(){
alert("error");
}
});
}
add.php
<?php
if(isset($_POST['item_id']) && !empty($_POST['item_id'])){
//if(count($_POST)>0)
echo "success";
exit();
}
?>
In your jsfile.js file, please correct the following points which I have mentioned as comments on the following code.
function cart(id1)
{
var id=id1;
alert("enterd "+id);
document.getElementById("disp").innerHTML ="hi";
$.ajax({
url:"/add.php ",
method:"POST", //First change type to method here
data:{
item_id: id,
},
success:function(response) {
document.getElementById("disp").innerHTML =response;
},
error:function(){
alert("error");
}
});
}
Change it and try
type:"POST" -> method: "POST"
If your jquery version is >= 1.5 use it this way.
$.ajax({
url: "add.php",
method: "POST",
data: { item_id: id},
}).done(function(response) {
......
}).fail(function( jqXHR, textStatus ) {
......
});
Load Jquery Before your JS file.
I tested with some code here, basically the purpose of the html file code is to echo the value from the php file, depending which h3 title the user clicked.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<h3 id="random1" name="random_request1">Click here to get number from php</h3>
<p id="randomnumber">Number here</p>
<h3 id="random2" name="random_request2">Click here to get string from php</h3>
<p id="randomtext">Text here</p>
<script>
$('#random1').click(function()
{
//On click: ask php to get me a random text file
$.ajax({
type: 'POST',
url: "action.php",
success: function(newrandom)
{
$('#randomnumber').replaceWith(newrandom);
}
});
});
$('#random2').click(function()
{
$.ajax({
type: 'POST',
url: "action.php",
success: function(newrandom)
{
$('#randomtext').replaceWith(newrandom);
}
});
});
</script>
</body>
</html>
This is the action.php code:
<?php
if ($_POST['random_request1']) {
$random = rand();
echo $random;
}
else if ($_POST['random_request2']){
echo 'abcd';
}
?>
Unsurprisingly, php doesn't recognize the random_request1 and 2 name in $_POST[]. I think I still hasn't grasped the POST function quite well to answer this problem by myself in this case.
use just one click event
$('h3[id^="random"]').on('click',function()
{
//On click: ask php to get me a random text file
$.ajax({
type: 'POST',
url: "action.php",
data: {id : $(this).attr('id')},
success: function(newrandom)
{
$('#randomnumber').replaceWith(newrandom);
}
});
});
and in your action.php
<?php
$id = $_POST['id'];
?>
You will want to have a way to differentiate between the senders. Maybe pass a parameter:
$('#random2').click(function()
{
$.ajax({
type: 'POST',
url: "action.php?action=random2",
success: function(newrandom)
{
$('#randomtext').replaceWith(newrandom);
}
});
});
Or have them go to different endpoints:
$('#random1').click(function()
{
//On click: ask php to get me a random text file
$.ajax({
type: 'POST',
url: "action.php",
success: function(newrandom)
{
$('#randomnumber').replaceWith(newrandom);
}
});
});
$('#random2').click(function()
{
$.ajax({
type: 'POST',
url: "action2.php",
success: function(newrandom)
{
$('#randomtext').replaceWith(newrandom);
}
});
});
There are of course more methods. This might not fit what you're eventually trying to do, but it's a simple way to get started.
Following is the code iam working
$.ajax({
type: 'GET',
url: '<?php echo site_url(); ?>register',
data: "",
success: function (data) {
$("#ldcontent").html(data);
}
});
I want to call a layer in the above code as following in #ldfgp
$('#ldcontent').load('<?php echo site_url(); ?>register #ldfgp');
My Question is It is possible to call a layer (#ldfgp) from a loading page to my master page through $.ajax().
I cannot use load function in jquery because it excludes the JavaScript embedded in the loading page.
Your suggestions and helps are highly appreciated.
You may load the whole document to some HTML fragment and then fetch relevant content from it
$.ajax({
type: 'GET',
url: '<?php echo site_url(); ?>register',
data: "",
success: function (data) {
var $fragment = $('<div/>').html(data);
$("#ldcontent").html( $fragment.find('#ldfgp').html() );
}
});
due to $.ajax load entire html document include html>body,$(data) is creating a little odd Jquery object.
so you can use $(data).find or $(data).filter to find your element. you can try some like:
$.ajax({
type: 'GET',
url: '<?php echo site_url(); ?>register',
data: "",
success: function (data) {
var $data=$(data);
var $layer=$()
.add($data.find('#ldfgp'))
.add($data.filter('#ldfgp'));
$('#ldcontent').html($layer);
}
});
You can try this -
$.ajax({
type: 'GET',
url: '<?php echo site_url(); ?>register',
data: "",
success: function (data) {
$("#ldcontent").html(data);
$("#ldcontent *").css('display','none');
$("#ldcontent #ldfgp").css('display','block');
$("#ldcontent #ldfgp *").css('display','block');
}
});
So, let's assume we have the register.html document like this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="ldfgp">
<h1>Hello</h1>
</div>
<div>
<h1>Hello 2</h1>
</div>
<div>
<h1>Hello 3</h1>
</div>
</body>
</html>
Using $.ajax() you could grab the element with id #ldfgp this way:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: './register.html',
data: "",
success: function (data) {
var external = $.parseHTML(data);
$.each(external, function(i, e) {
if ($(e).attr("id") == "ldfgp") {
$("#ldcontent").html(e);
return false;
}
});
}
});
});
But personally I'd prefer Vadim's solution, as it is cleaner and doesn't involve explicit .each() iteration.