issue with ajax event - ajax

i am using an ajax event which is triggered when i hit the submit button to add data to the database but since when i orignally created this page they were all in seprate files for testing purposes so now when i have put all the code together i have notice that 4 submit buttons i was using to refresh the page and then change the data being seen by filtering it are triggering the ajax query i have placed the code bellow.. i am quite stumped in what is the only way to go about this...
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function()
{
$("input[type='checkbox']").on('click', function() {
var $this = $(this);
var isChecked = $this.prop('checked');
var checkVal = isChecked ? $this.attr('id') : $this.attr("value");
var process= $this.attr("value");
var userid = $this.attr('name');
$.ajax({
type: "GET",
url: 'request.php',
data: {
'uname': checkVal,
'id': userid
},
success: function(data) {
if(data == 1){//Success
alert('Sucess');
}
if(data == 0){//Failure
alert('Data was NOT saved in db!');
}
}
});
});
$('form').bind('submit', function(){ // it is triggering this peice of code when the submit buttons are clicked ???
$.ajax({
type: 'POST',
url: "requestadd.php",
data: $("form").serialize(),
success: function(data) {
if(data == 1){//Success
alert('Sucess');
}
if(data == 0){//Failure
alert('Data was NOT saved in db!');
}
}
});
return false;
});
$("#claim").change(function(){
$("#area").find(".field").remove();
//or
$('#area').remove('.field');
if( $(this).val()=="Insurance")
{
$("#area").append("<input class='field' name='cost' type='text' placeholder='Cost' />");
}
});
});
</script>
</head>
<body>
<div id="add">
<form name="form1aa" method="post" id="form1a" >
<div id="area">
<input type=text name="cases" placeholder="Cases ID">
<select id="claim" name="claim">
<option value="">Select a Claim</option>
<option value="Insurance">Insurance</option>
<option value="Warranty">Warranty</option>
</select>
</div>
<select name="type" onChange=" fill_damage (document.form1aa.type.selectedIndex); ">
<option value="">Select One</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
</select>
<select name="damage">
</select>
<br />
<input type=text name="comment" placeholder="Comments Box">
<input type="submit" value="Submit" name="Submit">
</form>
</div>
<?
$sql="SELECT * FROM $tbl_name ORDER BY cases ASC";
if(isset($_POST['tpc'])){
$sql="select * from $tbl_name WHERE class LIKE '1%' ORDER BY cases ASC";
}
if(isset($_POST['drc'])){
$sql="select * from $tbl_name WHERE class LIKE 'D%' ORDER BY cases ASC";
}
if(isset($_POST['bsc'])){
$sql="select * from $tbl_name WHERE class LIKE 'B%' ORDER BY cases ASC";
}
$result=mysql_query($sql);
?>
<!-- Filter p1 (Start of) !-->
<form action="ajax-with-php.php" target="_self">
<input type="submit" name="all" value="All" /> // the issue is mainly occuring here when i click any of thesse meant to refesh the page and change the query with the if statements but is trigger the other code i commented
<input type="submit" name="tpc" value="TPC" />
<input type="submit" name="drc" value="DRC" />
<input type="submit" name="bsc" value="BSC" />
</form>

$('form').bind('submit', function(){ ...
will bind to all forms. Change it to
$('form#form1a').bind('submit', function(){ ...
and it will only bind to the first form, not the second.

$('form').bind('submit', function(event){
event.preventDefault();
$.ajax({...
Try making the changes above 1) adding the event argument to your callback 2) executing the .preventDefault() method. When using AJAX with the submit event this is neccessary to stop the page from reloading and interrupting your async request.
There may be more issues than that, but hopefully that will get you on the right track.

Related

How to send Array from Select List to ajax

I'm new to Ajax and I can't find any way to pass my data Properly, my Sub-Category is dependent on categories output, my problem now is that when I select 2 or more item in category, the output of Sub-Category don't pile up on each other.
I know I have to put my category on array but I don't know how it will work if the data come on select list.
My Filter
<div class="col-lg-3 col-md-3 col-sm-3">
<select id="assignedCategory" class="form-control selectpicker" title="Category" value="#ViewBag.AssignedCategory" asp-items="#ApplicationCategory" multiple asp-for="#category" onchange="GetSubCat();">
</select>
</div>
<div class="col-lg-3 col-md-3 col-sm-3">
<select id="assignedSubCategory" class="form-control selectpicker" title="Sub-Catergory" multiple>
</select>
</div>
Ajax
function GetSubCat() {
$('#assignedSubCategory').html('');
$.ajax({
url: '#Url.Action("GetSubCat")',
type: 'post',
dataType: 'json',
data: {
CatId: $('#assignedCategory option:selected').val() <!--This Part Right Here, I don't know how to make this an Array.-->
},
success: (data) => {
$.each(data, (i, e) => {
var elem = '<option value="' + e.value + '">' + e.text + '</option>'
$('#assignedSubCategory').append(elem);
$('#assignedSubCategory').selectpicker('refresh');
});
}
});
}
Controller
[HttpPost]
[AllowAnonymous]
public JsonResult GetSubCat(int?[] CatId)
{
var getCat = db.Subcategories.FromSqlRaw($#"
select sc.* from CRM_Subcategories sc
left join CRM_Categories c on sc.CategoryId = c.Id
where c.Id IN ({CatId})").Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Value
}).ToList();
return Json(getCat);
}
1.You could get selected array like below:
$('#assignedCategory').val();
2.Upon you select an option in selectlist, the onchange event will be triggered. That is to say if you select multiple options, it will trigger GetSubCat function for multiple times and post to backend for multiple times. If you do not care with this. Just change ajax post data to: $('#assignedCategory').val();.
3.You use selectpicker in your code, it seems you use Bootstrap-select plugin in your project. Bootstrap-select exposes a few events for hooking into select functionality. I think you could use hidden.bs.select event to post your selected array list to backend. This event is fired when the dropdown has finished being hidden from the user. That is to say it will trigger ajax upon the select menu closed.
Here is a working sample:
<div class="col-lg-3 col-md-3 col-sm-3" id="category"> //add id here...
<select id="assignedCategory" class="form-control selectpicker" title="Category" value="#ViewBag.AssignedCategory" multiple >
<option value="1">aa</option>
<option value="2">bb</option>
<option value="3">cc</option>
</select>
</div>
<div class="col-lg-3 col-md-3 col-sm-3">
<select id="assignedSubCategory" class="form-control selectpicker" title="Sub-Catergory" multiple>
</select>
</div>
#section Scripts
{
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/css/bootstrap-select.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select#1.13.14/dist/js/bootstrap-select.min.js"></script>
<script>
$('#category').on('hide.bs.select', function (e) {
$.ajax({
url: '#Url.Action("GetSubCat")',
type: 'post',
dataType: 'json',
data: {
CatId: $('#assignedCategory').val()
},
success: (data) => {
$.each(data, (i, e) => {
var elem = '<option value="' + e.value + '">' + e.text + '</option>'
$('#assignedSubCategory').append(elem);
$('#assignedSubCategory').selectpicker('refresh');
});
}
});
});
</script>
}

MVC 4.x Validate dropdown and redirect to next page

Beginner question:
I have an MVC app where there are three dropdowns on a page. Currently I'm using AJAX to evaluate a drop down on form submission and modify a CSS class to display feedback if the answer to the question is wrong.
HTML:
<form method="post" id="formQuestion">
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<p>This is a question:</p>
</div>
<div class="col-md-4">
<select id="Question1">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
<div class="col-md-4 answerResult1">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<button class="btn btn-success" type="submit" id="btnsubmit">Submit Answer</button>
</div>
</div>
</form>
AJAX:
#section scripts {
<script>
$(document).ready(function () {
$("#formQuestion").submit(function (e) {
e.preventDefault();
console.log($('#Question1').val())
$.ajax({
url: "/Home/DSQ1",
type: "POST",
data: { "selectedAnswer1": $('#Question1').val() },
success: function (data) { $(".answerResult1").html(data); }
});
})
});
</script>
}
Controller:
public string DSQ1(string selectedAnswer1)
{
var message = (selectedAnswer1 == "3") ? "Correct" : "Feed back";
return message;
}
I have three of these drop downs, that all get evaluated by AJAX in the same way. My question is, how would I go about evaluating all three and then returning a particular View if all three are correct.
I would like to avoid using hard-typed http:// addresses.
You could declare a global script variable prior to your document ready function, this will determine if the fields are valid. See var dropdown1Valid = false, ....
Then on your ajax success function, you could modify the values there. Say in the ajax below, your answering with first dropdown, if your controller returned Correct, set dropdown1Valid to true.
Lastly, at the end of your submit function, you could redirect check if all the variables are true, then redirect using window.location.href="URL HERE or use html helper url.action window.location.href="#Url.Action("actionName");
#section scripts {
<script>
var dropdown1Valid = false;
var dropdown2Valid = false;
var dropdown3Valid = false;
$(document).ready(function () {
$("#formQuestion").submit(function (e) {
e.preventDefault();
console.log($('#Question1').val())
$.ajax({
url: "/Home/DSQ1",
type: "POST",
data: { "selectedAnswer1": $('#Question1').val() },
success: function (data) {
$(".answerResult1").html(data);
if(data == "Correct"){
// if correct, set dropdown1 valid to true
dropdown1Valid = true;
}
// option 1, put redirect validation here
if(dropdown1Valid && dropdown2Valid && dropdown3Valid){
// if all three are valid, redirect
window.location.href="#Url.Action("actionName","controllerName", new { })";
}
}
});
// option 2, put redirect validation here
if(dropdown1Valid && dropdown2Valid && dropdown3Valid){
// if all three are valid, redirect
window.location.href="#Url.Action("actionName", "controllerName", new { })";
}
})
});
</script>
}

How do I post the value of a radio button to a database using AJAX?

I want to be able to post the value of a radio button to a database, without having to submit the form, hence why I have attempted this using 'on change'.
$("input:radio[name=q1_MC]").on("change", function () {
var dunno1 = $(this).serialize();
$.ajax({
url: "get_response.php",
type: "POST",
data: dunno1,
success: function (data) {
console.log("working)";
},
error: function (request, status, error) {
console.log(request.responseText);
}
});
});
My console.log does show when I click one of my radio buttons.
Inside get_response.php I have:
<?php
require("db_connection.php");
if((isset($_POST['your_name']) {
$yourName = $conn->real_escape_string($_POST['your_name']);
$q1_MC = $conn->real_escape_string($_POST['q1_MC']);
$q2 = $conn->real_escape_string($_POST['q2']);
$q3 = $conn->real_escape_string($_POST['q3']);
$q4 = $conn->real_escape_string($_POST['q4']);
$q5 = $conn->real_escape_string($_POST['q5']);
$q6 = $conn->real_escape_string($_POST['q6']);
$q7_MC = $conn->real_escape_string($_POST['q7_MC']);
$q8 = $conn->real_escape_string($_POST['q8']);
$sql="INSERT INTO commenttable (name, q1_MC, q2, q3, q4, q5, q6, q7_MC, q8) VALUES ('".$yourName."','".$q1_MC."', '".$q2."', '".$q3."', '".$q4."', '".$q5."', '".$q6."', '".$q7_MC."', '".$q8."')";
if(!$result = $conn->query($sql)){
die('There was an error running the query [' . $conn->error . ']');
} else {
echo "Thank you! Your feedback is appreciated";
}
}
?>
HTML:
<input type="radio" name="q1_MC" value="Excited"> Excited
<input type="radio" name="q1_MC" value="Optimistic"> Optimistic
<input type="radio" name="q1_MC" value="Indifferent"> Indifferent
<input type="radio" name="q1_MC" value="Nervous"> Nervous
<input type="radio" name="q1_MC" value="Sceptical"> Sceptical
if((isset($_POST['your_name']) will only be true when you submit the whole form. In your case you appear to be posting just the key/value of the radio button.
EG:
$("input:radio[name=q1_MC]").on("change", function() {
var dunno1 = $(this).serialize();
console.log(dunno1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label><input type="radio" name="q1_MC" value="test1" />test1</label>
<label><input type="radio" name="q1_MC" value="test2" />test2</label>
</form>

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:

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