Ajax call back: Return variable as input value - ajax

After ajax call back I need to echo out a variable as value of hidden field.
HTML
<form ajax1>
<input name="Place" value="Milan">
<input name=submit onclick="return submitForm1()">
</form>
<form ajax2>
<input type="hidden" value="$place">
<input name="filter">
<input name=submit onclick="return submitForm2()">
</form>
<div id="result"></div>
Ajax Call
function submitForm1() {
var form1 = document.myform1;
var dataString1 = $(form2).serialize();
$.ajax({
type:'GET',
url:'query.php',
cache: false,
data: dataString1,
success: function(data){
$('#results').html(data);
}
});
return false;
}
PHP
<?
$place= $_GET['Place']
//do stuffs
?>
It works perfectly, but now I need to add a function to echo out $place in value=" " of form ajax2
Any help appreciated

Related

How to save the content of a textarea using Ckeditor and CodeIgniter?

I'm using Codeigniter with Ckeditor. My problem is that when I submit the content, the data from the textarea is not stored in the database. But when I tried it again it finally did. So the situation is like I have to double click submit button to save it.
I stored the downloaded Ckeditor on a folder named ./Assests/Ckeditor(Sorry for the wrong spelling.I'll fix this later.)
Here's my form in my view folder:
ask_view.php:
<form id="form" enctype="multipart/data" method="post" onsubmit="createTextSnippet();">
<div class="form-group">
<label for="exampleInputEmail1">Title</label>
<input type="text" name ="title" class="form-control" id="title" placeholder="Title" required >
</div>
<input type="hidden" name="hidden_snippet" id="hidden_snippet" value="" />
<div class="form-group">
<label for="exampleInputEmail1">Editor</label>
<textarea name ="text" class="form-control" id="text" rows="3" placeholder="Textarea" required></textarea>
</div>
<input type="submit" class="btn " name="submit" value ="Submit" style="width: 100%;background: #f4a950;color:#161b21;">
</form>
<script src="<?php echo base_url('assests/js/editor.js')?>"></script>
<script type="text/javascript">
CKEDITOR.replace('text' ,{
filebrowserBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserUploadUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=2&editor=ckeditor&fldr=')?>',
filebrowserImageBrowseUrl : '<?php echo base_url('assests/filemanager/dialog.php?type=1&editor=ckeditor&fldr=')?>'
}
);
</script>
<script type="text/javascript">
//code used to save content in textarea as plain text
function createTextSnippet() {
var html=CKEDITOR.instances.text.getSnapshot();
var dom=document.createElement("DIV");
dom.innerHTML=html;
var plain_text=(dom.textContent || dom.innerText);
var snippet=plain_text.substr(0,500);
document.getElementById("hidden_snippet").value=snippet;
//return true, ok to submit the form
return true;
}
</script>
<script type="text/javascript">
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/knowmore2/index.php/ask_controller/book_add',
data: $('form').serialize(),
success: function (data) {
console.log(JSON.parse(data));
}
});
});
</script>
Ask_model.php:
public function book_add($data)
{
$query=$this->db->insert('article', $data);
return $query;
}
Ask_controller.php:
public function book_add(){
$data = $_POST;
$details = array();
$details['title'] = $data['title'];
$details['content'] = $data['text'];
$details['snippet'] = $data['hidden_snippet'];
$details['createdDate']=date('Y-m-d H:i:s');
$result=$this->ask_model->book_add($details);
echo json_encode($details);
}
The content with html tags should be save in a column named content in the database, but it didn't save in the first click. It only saves on the second one,but the other data are saved in the first like the title, etc. So I get 2 rows of data, one without the content and the other with one.
Database:

Ajax Submitting form Twice

I have a form in a modal window that allows a user to resend a confirmation email. When the form is submitted, the confirmation email is sent twice, instead of once. Everything else is working exactly as it should.
Form is pretty standard:
<form enctype="multipart/form-data" id="ReMailf" name="ReMailf" role="form" data-toggle="validator">
<fieldset>
<div class="row">
<p>You may enter a different email than your original if you wish. However, the original email will remain as the main contact on your application.</p>
<label class="desc" for="prim_email"> Email </label>
<input id="prim_email" name="prim_email" type="email" class="form-control" value="<?php echo $tE['prim_email']; ?>" data-error="Please Enter A Valid Email Address" required/>
<div class="help-block with-errors"></div>
</div>
<div class="row">
<input id="submitForm" name="submitForm" class="btn btn-success" type="submit" value="Resend Conformation "/>
<input name="uniqid" type="hidden" value="<?php echo $tE['unqID']; ?>"/>
<input name="ReMAIL" type="hidden" value="ReMAIL"/>
</div>
</fieldset>
</form>
… and here's the handler:
$(document).ready(function () {
$("#ReMailf").on("submit", function(e) {
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on('click', function() {
$("#ReMailf").submit();
});
});
I've read a number of other post about this, and tried some of the suggestions, but nothing is working. It either doesn't submit at all, or submits twice.
This is the only form on the page...
Suggestions please?
It is because you are using a button or submit to trigger the ajax event. Use this instead:
$(document).ready(function() {
$("#ReMailf").on("submit", function(e) {
e.preventDefault(); //add this line
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
or you can just use a simple form with action and method. It will do the job

Upload image to database in laravel 5 using eloquent ORM?

I have one form which contains one file upload.
Form Id is "upload_form"
<input type="file" id="image" name="image"/>
Using javascript onclick function and ajax to pass the image to the controller.
Ajax fn:
$.ajax({
url: 'UploadImage',
data:new FormData($("#upload_form")[0]),
type: "post",
dataType:"JSON",
async:false,
success: function (data) {
console.log(data);
}
});
}
Routes:
Routes::post('UploadImage','UploadController#Upload');
UploadController:
public function Upload()
{
$file = Input::file('image');
$tmpFilePath = '/temp/uploads/';
$tmpFileName = time() . '-' . $file->getClientOriginalName();
$path = $tmpFilePath.$tmpFileName;
$data_file = $file->move(public_path() . $tmpFilePath, $tmpFileName);
// Error for move() and getClientOriginalName() functions.
}
use this and it should work for you ... :)
<form action="" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" id="image" name="image"/>
<input type="submit" value="Upload" name="submit">
</form>
Thanks #GONG.
Changed my form to this. Worked.
<form enctype="multipart/form-data" id="upload_form" role="form" method="POST" action="" >

Passing checkbox value in ajax

Please, I need help in passing the check box value through ajax to other php file
This is my form :
<form class="form-horizontal" onsubmit="Javascript:return validate();" method="post" id="form">
<b>Jawwal Number</b>
<input name="msisdn" type="text" id="msisdn" class="form-control" required="" autofocus="" style="margin-top: 10px;margin-bottom: 10px" >
<b>Username</b>
<input name="username" type="text" id="username" class="form-control" required="" autofocus="" style="margin-top: 10px;margin-bottom: 10px" >
<b>Add Extra Security (Activation Code)</b>
<input type="checkbox" name="security" id="security">
<input type="submit" value="submit" class="btn btn-primary">
</form>
And this is my Ajax code :
$("#form").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* set all the vars you want to post on here */
var parameters = {
'msisdn': $('input[name="msisdn"]').val(),
'username': $('input[name="username"]').val(),
**'security':$('input[name="security"]').val(),**
'submit': $('input[name="submit"]').val()
};
$.ajax({
url: '/bulk2/admin/process/add_user.php',
method:'POST',
data: parameters,
success: function(msg) {
$('#test').append(msg);
}
})
});
What should I do so that I can pass the checkbox value to the other page ?
You can also use checkbox checked method.
var security = $('input[name="security"]').prop('checked'); /* it will return true or false */
and update your code
var parameters = {
'msisdn': $('input[name="msisdn"]').val(),
'username': $('input[name="username"]').val(),
'security':security,
'submit': $('input[name="submit"]').val()
};
Use the method is() with property :checked.
var parameters = {
'security':$('input[name="security"]').is(':checked'),
};
This works for me.

How to transmit my jquery result for processing in my codeigniter ocntroller?

Have a good day.
I am doing a select all checkbox to delete selected posts. I am able to get the result in the jquery but I am not sure how to use that result to process in my Codeigniter Controller. Maybe someone can enlighten me. Thanks!
View File:
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="1" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="2" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="3" />
<button id="delete_selected" name="delete_selected" class="btn btn-danger btn-small" value="" onClick="return confirm('Delete selected posts?')"><i class="icon-trash icon-white"> </i> Delete Selected</button>
JQuery:
//GET SELECTED POSTS/PAGES FOR DELETION
$("#delete_selected").click(function(event) {
/* stop form from submitting normally */
event.preventDefault();
var values = new Array();
$.each($('input[name="delete_selection[]"]:checked'), function() {
var delete_selection = $(this).val()
console.log(delete_selection);
});
});
Controller:
public function post_delete(){
//HOW TO GRAB THE RESULT FROM THE JQUERY?
//I KNOW IT SHOULD BE IN AJAX BUT NOT QUITE SURE HOW TO DO IT.
$id = $this->input->post('delete_selection');
for( $i=0; $i<sizeof($id); $i++) :
$this->posts_model->delete_post_selection($id[$i]);
endfor;
$data['message_success'] = $this->session->set_flashdata('message_success', 'You have successfully deleted your selected posts.');
redirect('admin/posts/posts_list', $data);
}
Model:
//MULTIPLE DELETE
function delete_post_selection($id) {
$this->db->where_in('post_id', $id)->delete('posts');
return true;
}
Your thinking is wrong, the controller isn't gonna 'grab' the values. But javascript is going to post to the controller
Assuming you put your html inside a form you could do something like this:
view:
<form action="/post_delete">
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="1" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="2" />
<input class="delete_selection" type="checkbox" name="delete_selection[]" value="3" />
<button id="delete_selected" name="delete_selected" class="btn btn-danger btn-small" value=""><i class="icon-trash icon-white"> </i> Delete Selected</button>
</form>
JS:
$('#delete_selection').click(function(e){
if(!confirm('Delete?')) return;//ask user if they're sure
//stop default form submitting from happening because
//we'll use ajax
e.preventDefault();
var form = $(this).closest('form');//get the parent form
$.ajax({
url: form.attr('action'),//get url to send it to
type: "POST",
data: form.serialize(),//get data from the form
success: function(){
//do something with success
}
error: function(){
//do something with error
}
});
And now you can use the data in your controller by accessing $_POST try
var_dump($_POST);
to see what has been posted
I am not sure if this is the correct way as it POST repeatedly but does the work so far.
In my JS:
//GET SELECTED POSTS/PAGES FOR DELETION
$("#delete_selection").click(function(event) {
if(!confirm('Delete selected posts?')) return false;//ask user if they're sure
/* stop form from submitting normally */
event.preventDefault();
$.each($('input[name="delete_selection[]"]:checked'), function() {
$.ajax({
type: "POST",
url: 'post_delete_selection',
data:
{ selected: $(this).val() },
success: function(data){
setTimeout(function () {
window.location.href = window.location.href;
}, 1000);
$('#ajax_message').show().html('Successfully deleted.');
},
});
});
});
My Controller:
public function post_delete_selection(){
$selectedIds = $_POST['selected']; //THIS GRABS THE VALUES FROM THE AJAX
$this->posts_model->delete_post_selection($selectedIds);
}
My Model:
function delete_post_selection($selectedIds) {
$this->db->where_in('post_id', $selectedIds)->delete('posts');
return true;
}

Resources