Pass closest value via ajax - ajax

I have a table created using a while loop thats displays a list of items so that the user can select an item to delete which is done via ajax.
I would like to use JQuery's closest attribute but I can't work out the correct syntax. The output I get from this is Object Object
The table
<form id="del_opinion">
<table id="asked_list">
<?php
while($row = mysqli_fetch_assoc($result)){
<tr>
<td>
<?php echo $row['name']; ?>
</td>
<td>
<input type="button" name="del_question" value="" class="trash_btn">
<input type="hidden" class="id_question" name="question_id" value="<? echo $row['questionID']; ?>">
<input type="hidden" class="id_user" name="user" value="<?php echo $id; ?>" >
</td>
</tr>
<? } ?>
</table>
</form>
The ajax
<script>
$(document).ready(function() {
$('.trash_btn').click(function(){
var question = $(this).closest('.id_question');
var user = $(this).closest('id_user');
$.ajax({
url: 'opinion_del.php',
type:'POST',
data: 'question='+ question +'&user='+user,
dataType: 'json',
success: function(response){
$('#responses_table').html(response);
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
The php have done for testing
$question_id = $_POST['question'];
$id = $_POST['user'];
$sql = "SELECT * FROM adviceQuestion WHERE questionID = '$question_id'";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
if($result){
$output = $question_id;
}
echo json_encode($output);
If I type a literal value to $output it works fine and if I type a literal value in either of the jquery vars they work correctly too so I'm convinced it is something to do with the closest syntax
I have also tried adding a class to the table row called details and using
var question = $(event.target).closest('.details').find('.id_question');
If I alert question it says [object Object]

var user = $(this).closest('id_user');
Change to this
var user = $(this).closest('.id_user');
You didnt specified a c lass "." dot ))) Maybe will help

OK, sussed it...
Changed this
var question = $(this).closest('.id_question');
var user = $(this).closest('id_user');
to
var question = $(this).next('.id_question').val();
var user = $(this).next('.id_user').val();

Related

Success function not being called after making AJAX request codeigniter

When I make an AJAX call from view and pass form data to the controller. I get a couple of problems. First, the code inside success is never executed, and second, the page is being refreshed even though it is an AJAX call. Can anyone tell me where am I doing wrong?
I have seen a lot of questions since yesterday but none of them were able to solve my problem.
Model code
public function insert_user($name, $email) {
$data = array();
$data['name'] = $name;
$data['email'] = $email;
$data['created_at'] = date('y-m-d');
$this->db->insert('all_users', $data);
return true;
}
Controller code
public function insert_user () {
$data = $this->input->post();
$name = $data['name'];
$email = $data['email'];
$this->User_model->insert_user($name, $email);
$this->load->view('view');
}
Ajax request code
const insertBtn = $(".insert-btn");
insertBtn.on("click", function () {
const name = $(".insert-form input[type=name]");
const email = $(".insert-form input[type=email]");
$.ajax({
url: "<?php echo base_url() ?>index.php/Users/insert_user",
type: "post",
data: {name, email},
dataType: "json",
success: function () {
$("body").append("Request made successfully");
}
})
});
My form looks something like this:
<form class="insert-form" action="<?php echo base_url() ?>index.php/Users/insert_user" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<button class="insert-btn">Insert Data</button>
</form>
NOTE: I am able to successfully insert data into the database.
The browser is submitting the form before your AJAX code gets a chance to run/finish.
Instead of binding an event to the click event of the button, you want to bind to the submit event of the form. Then you want to cancel the browser's default action. This is done via the e.preventDefault(); method.
Also, dataType: "json" is not needed here. dataType tells jQuery what kind of data your AJAX call is returning. You generally don't need it as jQuery can automatically detect it. Plus, if you are not returning a JSON document, then this may cause a problem.
const insertForm = $(".insert-form");
insertForm.on("submit", function (e) {
const name = insertForm.find("input[type=name]");
const email = insertForm.find("input[type=email]");
e.preventDefault();
$.ajax({
url: "<?php echo base_url() ?>index.php/Users/insert_user",
type: "post",
data: {name, email},
success: function () {
$("body").append("Request made successfully");
}
})
});
Controller code
public function insert_user () {
$data = $this->input->post();
$name = $data['name'];
$email = $data['email'];
$data = $this->User_model->insert_user($name, $email);
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
Ajax request code
const insertBtn = $(".insert-btn");
insertBtn.on("click", function () {
const name = $(".insert-form input[type=name]");
const email = $(".insert-form input[type=email]");
$.ajax({
url: "<?php echo base_url() ?>Users/insert_user", // <?php echo base_url() ?>controller_name/function_name
type: "post",
data: {name, email},
dataType: "json",
success: function () {
$("body").append("Request made successfully");
}
})
});
form looks something like this:
<form class="insert-form" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<button class="insert-btn">Insert Data</button>
</form>
The page was being refreshed because I had a button that was acting as submit button on changing it to the input of the type button it does not submits the form and we don't see the page being refreshed. And also the AJAX request made also runs successfully.
<form class="insert-form" action="<?php echo base_url() ?>index.php/Users/insert_user" method="post">
<input type="text" name="name" placeholder="Enter name">
<input type="email" name="email" placeholder="Enter email">
<input type="button" class="insert-btn" value="Insert Data">
</form>

ajax not append data on div?

I dont know what the problem is here, I try to append the content, but its not.
var InPro = false;
$(document).ready(function(){
var form = $('#form32');
var submit = $('#submit');
form.on('submit', function(e) {
if(InPro) return;
InPro = true;
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'post.php',
type: 'POST',
cache: false,
data: form.serialize(),
success: function(data){
InPro = false;
var item = $(data).hide().fadeIn(800);
$('#post-show').append(data);
$("#form32")[0].reset();
},
});
});
});
and here the post.php:
<?php
include_once("config.php");
include_once("verifica.php");
// No direct access to this file
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!IS_AJAX) {die('Restricted access');}
session_start();
$user = $_SESSION['user'];
$comment = $_POST['comment'];
if($comment==""){
die();
}
$ip = getenv("REMOTE_ADDR");
$data = date ("ymdHis");
$i=mysql_query("INSERT INTO posts (id, foto, user, titulo, youtube, button, data, ip) VALUES ('','0','$user','$comment','$youtube','$button','$data','$ip')");
$idpostfeed = mysql_insert_id();
echo"$comment";
?>
and my form:
<form id="form32" method="post"> <textarea name="comment" id="comment" class="comment" placeholder=""></textarea> <input type="submit" id="submit" class="button" value="Submit Comment"> </form> <div id=post-show></div>
so, I want to show result in #post-show div, but it is not working. what is wrong?
thank you!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

How to insert into database after processing data through ajax formdata

My goal is to upload a file and insert data into a database table with ajax using formdata. I can do both separately. Or at least, I can use formdata to upload a file and I can use ajax to insert data into a database, but putting it together has proven difficult. The tutorial for this code seemed to indicate it would do it, and based on what I understand, the ajax is processing the entire form, but it's only uploading the file. I'm not having any issue with that and unfortunately, that's what most of the questions and tutorials I'm finding seem to be directed towards.
I think the issue is with my php insert code. Should I be inserting differently because of how the data is passed through ajax? Or am I more lost than that and just think I'm passing it all through ajax? I feel like I'm so close now, but I can't figure out what I'm doing wrong.
Thank you for any help.
The form and ajax:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form name="multiform" id="multiform" action="upload.php" method="POST" enctype="multipart/form-data">
Name: <input type="text" name="dname" /> <br/>
Age :<input type="text" name="age" /> <br/>
Image :<input type="file" name="photo" /><br/>
<input type="submit" value="Ajax File Upload" />
</form>
<script>
//Callback handler for form submit event
jQuery(document).ready(function() {
$("#multiform").submit(function(e)
{
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData($(this)[0]);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(data, textStatus, jqXHR)
{ alert(data)
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //Prevent Default action.
});
$("#multiform").submit(); //Submit the form
});
</script>
The php:
<?php
$username="...";
$password="...";
$database="...";
$target = "...";
$target = $target . time() . '_' . basename( $_FILES['photo']['name']);
$File = time() . '_' . basename($_FILES['photo']['name']);
$name = $_POST['dname'];
$age = $_POST['age'];
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Death");
print_r($_POST);
print_r($_FILES);
mysql_query("INSERT INTO wp_demo('name','age','File')VALUES('$name','$age','$File')");
if(isset($_FILES["photo"]))
{
//Filter the file types , if you want.
if ($_FILES["photo"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["photo"]["tmp_name"],$target);
echo $_FILES['photo']['name'] . " is now available";
}
}
?>
EDIT: Nevermind. I still don't know what's wrong here, but it ultimately just needs to work in wordpress. I got it to work there with this:
global $wpdb;
if($wpdb->insert('wp_demo',array(
'name' => $name,
'age' => $age,
'File' => $File
))===FALSE) {
echo "error";
}
else {
echo "success";
}
Now I just need to figure out why it submits on page load...

How to submit form using ajax inside wordpress plugin

I am creating small plugin where i want to submit form data using ajax but it giving response zero.
Here is my call i have added all code in a single file for the time being
file name :index.php
<?php wp_enqueue_script("jquery");?>
<?php
function myaddgallery(){
global $wpdb;
echo "abac";
}
add_action('wp_ajax_myaddgallery' , 'myaddgallery');
add_action('wp_ajax_nopriv_myaddgallery' , 'myaddgallery');
?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#shaGalleryForm').submit(function(e){
// prevent normal submit behaviour
e.preventDefault();
var name = jQuery("#shaGalleryName").val();
alert(name);
//var postData = jQuery("#shaGalleryForm").serialize();
//console.log(postData);
var name = "shalu";
jQuery.ajax({
type: "POST",
url: "http://localhost/plugindevelop/wp-admin/admin-ajax.php",
data : {action: "myaddgallery", name : name},
success: function(response){
//console.log(postData);
console.log("added success");
alert(response);
},
error: function(data){
console.log("fail");
}
});
});
}) ;
</script>
<div class='wrap'>
<h2>Add Gallery</h2>
<p>This is where from you can create new gallery</p>
<form name="shaGalleryForm" id="shaGalleryForm" method="post">
<table class="form-table">
<tr>
<th>Gallery Name</th>
<td>
<input type="text" id="shaGalleryName" name="shaGalleryName">
<p class="description">Add gallery name also please avoid special character</p>
</td>
</tr>
</table>
<p class="submit">
<input type="submit" value="Save" id="shaSaveGallery" name="shaSaveGallery" class="button button-primary">
</p>
</form>
</div>
Try to add die() after you echo the data
function myaddgallery(){
global $wpdb;
echo "abac";
die();
}

how to get the dropdown selected value and send it to controller in codeigniter

am having the following code
view
<script>
$(document).ready(function()
{
$("#Login").click(function()
{
$("#message").html("");
var action = $("#loginform").attr('action');
var login_data = {
username: $("#txt_email").val(),
password: $("#txt_password").val(),
language: $("#language").val(),
is_ajax: 1
};
$.ajax(
{
type: "POST",
url: '<?php echo base_url();?>survey/login',
data: login_data,
success: function(response)
{
if(response == 'success')
{
$("#message").html("<span class='success'>You have logged in successfully!</span><p>Redirecting...</p>");
setTimeout(function() {
window.location.href = '<?php echo base_url();?>survey/communication_letter';
}, 2000);
}
else
{
$("#message").html("<span class='error'>OOPS! Authentication failed</span>");
}
}
});
return false;
});
});
</script>
</head>
<body>
<div id= "header">
<br/>
<p style="text-align:center; color:#8D0F1D;font-size:28px" >Work Environment Survey</p>
</div>
<div id= "bar" style="z-index:1">
<div id="logo" style="z-index:2">
</div>
</div>
<br/>
<br/>
<div id="homemain">
<!--div id="content-login"-->
<br/><br/><br/>
<form action="#" id="loginform" method="post">
<table border="0" align="center" cellpadding="5" cellspacing="10" >
<tr>
<td>Email Id </td>
<td><input type="text" id="txt_email" name="username" /></td>
</tr>
<tr>
<td>Password </td>
<td><input type="password" id="txt_password" name="password" /></td>
</tr>
<tr>
<td>Select Language</td>
<td><select style="width:215px" name="language" id = "language" ><option value="simplified">English with Simplified Chinese</option>
<option value="traditional">English with Traditional Chinese</option>
</select></td>
</tr>
</table>
<input type="image" id="Login" style="position:relative;left:120px" src="<?php echo base_url();?>images/login.png"/>
</form>
and the controller is as follows
public function login()
{
if(isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax']) {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
echo $verify = $this->user_model->user_login($username, $password);
exit;
}
$this->load->view('login');
}
here how can i get the dropdown selected value depending on the language selected i need to open the next page. please someone help me please, thanks.
you can get that by using $_POST or $_REQUEST like you did for username
if(isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax']) {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$language= $_REQUEST['language'];
echo $verify = $this->user_model->user_login($username, $password);
exit;
}
I think this what you want, when user enter correct credential, user will be redirected to the page depending on the language selected by the user. You do not need to access language in your controller because you are redirecting from you login page,
you controller has to be
public function login()
{
if(isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax']) {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$verify = $this->user_model->user_login($username, $password);
if($verify){
echo 1;
}else{
echo 0;
}
}
}
you don't need to load view, as it is an ajax response.
$.ajax(
{
type: "POST",
url: '<?php echo base_url();?>survey/login',
data: login_data,
success: function(response)
{
if(response == 1)
{
$("#message").html("<span class='success'>You have logged in successfully!</span><p>Redirecting...</p>");
setTimeout(function() {
if($("#language").val() == "simplified"){
window.location.href = '<?php echo base_url();?>survey/communication_letter';
}else{
window.location.href = '<?php echo base_url();?>survey/trad_communication_letter'; }
}
}, 2000);
}
else
{
$("#message").html("<span class='error'>OOPS! Authentication failed</span>");
}
}
});
I hope this will help you. please check you development tool (chrome) or firebug (firefox) that your request is going and what is coming in response.
The correct way to grab the selected index value from drop down is
$('#language option:selected').val();
also in your controller you can verify the ajax request using
$this->input->is_ajax_request()

Resources