Hey I hope someone can help me out,
I have an external js file that resides in the webroot/js folder that I insert into my view using:
echo $this->Html->script('script');
In the js file I have an ajax request to insert data into my database:
var assetData = {
"project_id": $("#projectId").val(),
"asset_id":"??",
"content": "content":$(this).html()
};
$.ajax({
url:'/assets/add',
type:"POST",
data:assetData
});
In my view I created a hidden form field with the project_id so that I can get it in the js file, however the asset items are created dynamically, the are created and saved into the assets table, and now I want to update that asset with the content.
What would be the best way to get the asset? I can't get the id and save it, for example, in the div's id because it was created in the js file.
I would really appreciate any suggestions!
/assets/add should return the ID of the asset it created.
If you're inserting into a mysql database, then one option is to use mysql_insert_id (there are mysqli and pdo equivilents on the manual).
var assetData = {
"project_id": $("#projectId").val(),
"content": "content":$(this).html()
};
$.ajax({
url:'/assets/add',
type:"POST",
data:assetData,
dataType:'text',
success:function (data)
{
assetData['asset_id'] = (int)data;
}
});
And then your /assets/add should echo out the ID after it is created
echo $asset_id; // some INT id
So you may want to consider HTML partials. These are little bits of HTML representing anything from a single tag, to a popup. The important thing is that it does not have the or tag.
$.post('/assets/add', data, function (html) {
$('#assets').append(html);
}, 'html');
After you POST data, your call returns a snippet of HTML. You can then append that HTML to a DIV on the page.
<div id="assets">
<div class="asset" id="asset-1">
<p>Asset content</p>
</div>
</div>
In your controller (I assume it's CakePHP), you have:
if ($this->Asset->save($this->data)) {
$this->autoLayout = false;
$this->render('asset_partial.html');
}
Using the suggestions I received this is how I managed to solve the problem:
javascript file:
$.ajax({
url:'/assets/create',
type:"POST",
data:assetData,
dataType:'text',
success: function (response) {
if (response.success) {
alert("response: "+response);
} else {
//console.log(response.data, response.code);
alert("response: "+response);
}
}
});
Controller:
public function create($id = null) {
if ($this->data != null) {
$this->Asset->save($this->data);
$this->autoRender = false;
echo $this->Asset->id;
}
}
Related
I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)
First, precisions : I'm using MAMP and Brackets, and Chrome to test.
Here's what I have :
<ul>
<li class="brick" data-pseudo="one">Some text or elements</li>
<li class="brick" data-pseudo="two">Some text or elements</li>
<li class="brick" data-pseudo="three">Some text or elements</li>
</ul>
li.bricks are just rectangle articles "linking" to Work1, Work2 and Work3, and generated by a PHP function from an array.
I'm trying to get the "pseudo" data of the clicked .brick to put it in a PHP variable and use it to call another array in another php function, in order to generate the HTML elements of Work1, Work2,...
I found I had to use AJAX and managed to get that code :
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
$('.brick').click(function(){
//some code
pseudo = $(this).data('pseudo');
sendPseudo(pseudo); //calling sendPseudo() function
});
And here's my testing PHP function :
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
... I'm calling in my HTML document :
<section class="site">
<div class="left">
<?php loadWork() ?>
</div>
<div class="right">
//some other content
</div>
</section>
And so I have two problems. Firstly, when a .brick is clicked, the alert pops up but it's empty, absolutely nothing appears in it, but when I console.log the var pseudo, I see "one", "two"... And secondly, the echo in testing PHP function does not generate the paragraph with the pseudo.
Pleeeaaase, help me to find out what I'm doing wrong, it's making me go crazy !
Thank you !
I think there is some confusion in your order. loadWork(), as you say, is part of an html file gets called as soon as the browser reads the html file and it's only called once. If loadWork() hasn't been defined yet (or exists in another file as your AJAX request suggests based on it's call to my_php_function_page.php) then it won't output anything. In other words, loadWork() needs its post data to exist when the browser requests the html.
You can put the php in the same file as the html that is being called on, but it looks like you might be trying to get the results of loadWork() inserted into a div that already exists. Change your ajax function so that if(data!="") changes the inner html of your div to include the data:
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
$('.left').html(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
I think you have missed calling your function loadWork() in my_php_function_page.php, this code may be fix your empty alert issue.
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
data=data.trim(); // to remove the unwanted space around the string
success: function (data) { //testing the success
if(data!="")
{
alert(data);
$(".right").html(data); // This adds your AJAX success data to the class left inside your DIV
}
else
{
alert("You're wrong !");
}
},
});
}
my_php_function_page.php
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
loadWork();
I'm not sure why, but sometimes data function is not working, so I always use attr('data-pseudo') in your case.
so it would be like this:
pseudo = $(this).attr('data-pseudo');
I'm using Laravel 4,
I want to reload a view and change the content (Basically change the langage)
When I arrive on the index :
On my controller :
public function getIndex()
{
$lang = $this->retrieveLang("FR");
$this->layout->content = View::make('cv.cv', array('lang' => $lang));
}
The content extend the layout
#extends('layout.cvlayout')
#section('content')
My ajax function :
<script>
$(".changeLang").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$.ajax({
url: url,
cache: false,
beforeSend: function() {
$(".loaderOverlay").fadeIn();
},
success: function(html) {
$("#container").html(html);
$(".loaderOverlay").fadeOut();
pageCvInit();
initAjaxHeadline();
}
});
});
</script>
the url may be ****/fr so in the controller there is a method like that :
public function getFr() {
$lang = $this->retrieveLang("FR");
return View::make('cv.cv', array('lang' => $lang));
}
I tried to put a condition on the
#extends()
#section()
#stop
part, but every time the ajax function is called, the whole body passes by the ajax method (even the , tags) and I just want to reload the body.
How do I do this?
Many thanks
Not sure how you mean by the whole body passes by ajax and you just want to reload the body.
Try changing your on success to filter out the body of the received html.
success: function(html) {
$("#container").html($(html).filter('body').html());
$(".loaderOverlay").fadeOut();
pageCvInit();
initAjaxHeadline();
}
You only need to reload the div you want that see the changes, in success put this:
$("#mydiv").load(location.href + " #mydiv");
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.
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