JS file not loading via ajax call - php

So what I'm doing is that when someone clicks on search button it loads carousel's html code via ajax call, which is in another file and places under the <div id="filter_product"></div>. And it's css and js is linked in file's header and footer where I am making ajax call. I am calling only html of carousel. Let me show you my code
ajax call is
function submit() {
$.ajax({
method: "POST",
url: "<?php echo base_url() ?>public_controller/search_product",
dataType:'html',
data: {color:color, year:year, cat:cat, brand:brand, model:model},
success: function(data){
console.log(data);
$('#filter_product').html(data);
}
});
}
$(document).on('click','#serch_btn',function(){
submit();
})
controller code is
public function search_product(){
$data['cat'] = $this->input->post('cat');
$data = $this->load->view('public/result_product',$data,TRUE);
echo $data;}
If i don't call carousel code via ajax call and simply place that in index.php it is working fine. but when i call code via ajax call then it's js file is not working and display is scrambled but html is loading fine. is there any way to solve this.
thanks in advance

Function name submit is reserved. You can't use it. Try to rename it.
Suggestion: in PHP method you don't need to echo and base_url() you can use in the next way
public function search_product(){
$data['cat'] = $this->input->post('cat');
$this->load->view('public/result_product',$data);
}
//////////////////////////////////////////////////////////
url: "<?= base_url('public_controller/search_product') ?>",
Put line $('#filter_product').owlCarousel(); after $('#filter_product').html(data); in your AJAX request success function.

Related

Why do I keep getting codeigniter "is not allowed by Access-Control-Allow-Origin" error with AJAX request

I have the following problem happening consistently on my code.
I have a data model with the following function:
data_model.php
public function testFunc(){
return "string";
}
site.php (controller)
public function get_more_data(){
$this->load->model('data_model');
$data['test']=$this->data_model->testFunc();
return $data;
}
home.php (view)
<html>
<body>
<button class="test">test</button>
</body>
<script>
$('.test').click(function(){
$id=1;
$.ajax
({
url: '<?php echo site_url() ?>index/site/get_more_data',
data: $id,
type: 'post',
success: function(result)
{
alert(result);
}
});
});
</html>
However every time I click the button I always get this error:
XMLHttpRequest cannot load http://[::1]/codeignitor/index.phpindex/site/get_more_data. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
What am I doing wrong or not understanding correctly here?
Thanks,
I use ajax in my CodeIgniter projects using the following procedure :
I send data to controllers using queries (like : xxxx.com?id=5)
I receive data using echo in the controller

how to run php function without reloading the page

I am a newbie to php
<?php
getDBData(){
//log the call
$fetchedData = myDbCode.fetchData();
return
}
?>
<script type="text/javascript">
dbData = <?php echo json_encode(getDBData()); ?>
</script>
As observed in the log that getDBData get called only once during the page loading and later on even with dbData = <?php echo json_encode(getDBData()); ?> this code the call to getDBData() doesn't happen.
Any idea why the call to getDBData() happening only on page load and not thenafter
How to call getDBData() from javascript
You don't actually understand, how it works.
Javascript is a client-side language, which means, that it executes in web browser.
PHP is server-side which mean it executes on server.
While handling request, first PHP is executed, that the response is returned to user, and then Javacript executes.
To communicate between client and server you can use ajax requests, which are basically simple http requests but without reloading whole page.
You should use Ajax for that. I.e. you have a php file which returns the output of the function:
// data.php
<?php
function getDBData(){
//log the call
$fetchedData = myDbCode.fetchData();
return $fetchedData;
}
echo getDBData();
?>
// html file
<script type="text/javascript">
var getDBData = function(callback) {
$.ajax({
url: "data.php"
}).done(callback);
}
var dbData = <?php echo json_encode(getDBData()); ?>
getDBData(function(data) {
dbData = data;
})
</script>
The code above uses jQuery.
you can used AJAX for get server side php vaue into javascript variable read this ajax example and implement it.
// Launch AJAX request.
$.ajax(
{
// The link we are accessing.
url: jLink.attr( "href" ),
// The type of request.
type: "get",
// The type of data that is getting returned.
dataType: "html",
error: function(){
ShowStatus( "AJAX - error()" );
// Load the content in to the page.
jContent.html( "<p>Page Not Found!!</p>" );
},
beforeSend: function(){
ShowStatus( "AJAX - beforeSend()" );
},
complete: function(){
ShowStatus( "AJAX - complete()" );
},
success: function( strData ){
ShowStatus( "AJAX - success()" );
// Load the content in to the page.
jContent.html( strData );
}
}
);
// Prevent default click.
return( false );
}
);
You can do it through ajax.
Here is a link here to do it with jquery : using jquery $.ajax to call a PHP function
use jquery
$.ajax({
url: 'yourpage.php',
type: 'POST',
data:'',
success: function(resp) {
// put your response where you want to
}
});
You can't directly call PHP functions from javascript.
You have to "outsource" the getDBDate to an own .php file where you output the json_encoded string and call this file with ajax and get the output of the page.
The easiest to do AJAX requests in javascript is to use the JQuery Library: http://api.jquery.com/jQuery.ajax/

Pass variable from JavaScript to PHP on new page

I am pretty new to JavaScript and PHP.
I'd like to create a JavaScript function that contains a variable, passes this on to PHP on another page and opens that page.
Here is what I got so far (not working):
My JS:
function test()
{
$.ajax(
{
url: "my-new-page.php",
type: "POST",
data:
{
varJS: "XXX"
},
error:function(err)
{
alert(err.statusText);
},
success: function(data)
{
window.open("my-new-page.php");
}
});
}
My PHP (on the new page):
$varPHP = $_POST['varJS'];
As I understand your question, you just want a simple javascript function that redirects to another page / PHP-script with some params?
my-new-page.php
<?
$varPHP = $_GET['varJS'];
echo $varPHP;
?>
javascript
function reDirect(varJS) {
var page='my-new-page.php?varJS='+varJS;
document.location.href=page;
}
reDirect('test')
To just open a new window passing it a variable, you can do that within a query string.
Simply call
window.open("my-new-page.php?varJS=XXX);
And Handle Query String on my-new-page.php
-Shakir
The entire point of using Ajax is that it doesn't take the user to a new page. Don't use Ajax.
If you need to make a POST request then generate a form and hidden inputs with document.createElement and friends, append it to the current document, and then call its submit() method.

codeigniter view won't show up from passing javascript/ajax parameter

I'm integrating codeigniter with phpgrid, and I'm having a trouble with passing the row values from phpgrid (in VIEW A) to another view (VIEW B) through javascript and codeigniter controllers
I have a virtual column like this in PHPGRID (VIEW A):
$col_formatter = <<<COLFORMATTER
function(cellvalue, options, rowObject, rowid){
var sessid = rowObject[0];
return '<input type="button" value="View" onclick="btnView('+sessid+')">';
}
COLFORMATTER;
and the javascript in VIEW A:
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
}
});
return false;
}
in the Codeigniter CONTROLLERS:
public function tes(){
$data['sessid'] = $_POST['sessid'];
$this->load->view('view_b', $data);
}
I can't seem to load the view. I used Mozilla's Firebug to know the response, it's true that the response is the code of my view_b view, but how can I switch to that view?
//Your are using ajax for some operation and want to reload the view page the you can test these options:
1) take a div in current view page and assing ajax retrun message to that div
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
$("#divid").html(msg);
}
});
return false;
}
//Or 2)just redirect to your view page again
function btnView(sessid){
var dataRow = {
sessid:sessid,
};
$.ajax({
type:"POST",
url: "<?php echo base_url()."index.php/main/tes"; ?>",
data: dataRow,
success: function(msg){
window.location.href=path to your view page;//<?php echo base_url()."index.php/controller/function"; ?>
}
});
return false;
}
If I understand correctly you want to go from VIEW A to VIEW B (meaning an actual change in the window location) and pass a value to VIEW B so it can generate some dynamic content. Well, AJAX is not the solution here since it will not trigger a change of page but instead will return the markup/text of the response as a string.
But there are still a number of ways you can achieve what you want, using Codeigniter the simpler way would be to use an argument for your controller method that you can send as part of the uri in a link:
HTML
View
Since you're using Javascript to generate the markup you would need something like this
return 'View';
*Note that you will now have a link instead of a button but you can use CSS to style it any way you want it.
You would now retrieve the value in your controller like this:
PHP
public function tes($sessid){
$data['sessid'] = $sessid;
$this->load->view('view_b', $data);
}
Pretty simple. A second option will be to use a form instead of your button to send the value using either GET or POST, forms do trigger a change in page whenever they are submitted:
HTML
<form action="http://example.com/index.php/main/tes" method="get">
<input type="submit" value="{ssid}" name="sessid" />
</form>
Again using javascript:
return '<form action="<?php echo site_url('main/tes')?>" method="get">'
+'<input type="submit" value="'+sessid+'" name="sessid" />'
+'</form>';
And to get the value in your controller:
PHP
public function tes(){
$data['sessid'] = $_GET['sessid']; //OR $_POST['sessid']
$this->load->view('view_b', $data);
}
Turns out that passing a variable from javascript to codeigniter controller is just:
function btnView(sessid){
window.location = "printvo/"+sessid;
}
I was using ajax because I don't know how to pass the variable, I always thought that passing variable is using brackets: window.location = "printvo("+sessid+")"; and that didn't work.

Trying to upload a file through jQuery .post() - file input not showing up on back end (using codeigniter)

First of all I'd like to ask that you don't suggest I turn to a jQuery plugin to solve my issue. I'm just not willing to make my app work with a plugin (and it prevents me from learning!)
I have a form with a bunch of fields that I'm passing to my backend via the use of jQuery's $.post() This is what I have as my jQuery function:
$.post(
"/item/edit",
$("#form").serialize(),
function(responseJSON) {
console.log(responseJSON);
},
"html"
);
This is how I opened my form:
<form action="http://localhost/item/edit" method="post" accept-charset="utf-8" class="form-horizontal" enctype="multipart/form-data">
This was auto generated by codeigniter's form_open() method (hence why action="" has a value. Though this shouldn't matter because I don't have a submit button at the end of the form)
Within my #form I have this as my file input: <input type="file" name="pImage" />
When the appropriate button is hit and the $.post() method is called, I have my backend just print the variables like so: print_r($_POST) and within the printed variables the 'pImage' element is missing. I thought that maybe files wouldn't come up as an element in the array so I went ahead and just tried to upload the file using this codeigniter function: $this->upload->do_upload('pImage'); and I get an error: "You did not select a file to upload."
Any idea as to how I can overcome this problem?
You cannot post an image using AJAX, i had to find out here as well PHP jQuery .ajax() file upload server side understanding
Your best bet is to mimic an ajax call using a hidden iframe, the form has to have enctype set to multipart/formdata
Files wont be sent to server side using AJAX
One of the best and simplest JQuery Ajax uploaders from PHP LETTER
all you need is include js in your header normally and Jquery code will be like below
$.ajaxFileUpload({
url:'http://localhost/speedncruise/index.php/snc/upload/do_upload',
secureuri:false,
fileElementId:'file_upload',
dataType: 'json',
data : {
'user_email' : $('#email').val()
},
success: function (data, status) {
// alert(status);
// $('#avatar_img').attr('src','data');
}
,
error: function (data, status, e) {
console.log(e);
}
});
wish this can help you
I can't do this with codeigniter and Ajax, I pass the image to base64 and in the controller I convert into a file again
//the input file type
<input id="imagen" name="imagen" class="tooltip" type="file" value="<?php if(isset($imagen)) echo $imagen; ?>">
//the js
$(document).on('change', '#imagen', function(event) {
readImage(this);
});
function readImage(input) {
var resultado='';
if ( input.files && input.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
//console.log(e.target.result);
subirImagen(e.target.result);
};
FR.readAsDataURL( input.files[0] );
}
}
function subirImagen(base64){
console.log('inicia subir imagen');
$.ajax({
url: 'controller/sube_imagen',
type: 'POST',
data: {
imagen: base64,
}
})
.done(function(d) {
console.log(d);
})
.fail(function(f) {
console.log(f);
})
.always(function(a) {
console.log("complete");
});
}
//and the part of de controller
public function sube_imagen(){
$imagen=$this->input->post('imagen');
list($extension,$imagen)=explode(';',$imagen);
list(,$extension)=explode('/', $extension);
list(,$imagen)=explode(',', $imagen);
$imagen = base64_decode($imagen);
$archivo='archivo.'.$extension;
file_put_contents('imagenes/'.$archivo, $imagen);
chmod('imagenes/'.$archivo, 0777); //I use Linux and the permissions are another theme
echo $archivo; //or you can make another thing
}
ps.: sorry for my english n_nU

Categories