PHP AJAX POST multiple same name - javascript

I have code like this:
<form method="post" id="result-image" name="result-image" action="" >
<?php $i=1; foreach ($data as $key => $datas) { ?>
<div class="col-md-2 thumb custom-size col-lg-3 col-xs-4">
<label class="btn btn-default turunin " >
<img class="thumbnail img-responsive img-check" src="<?php echo $datas['thumbnail'];?>" alt="<?php echo $datas['image_alt'];?>" title="<?php echo $datas['title']; ?>">
<div class="caption" style="text-align:center; margin-top:-15px; padding-bottom:0px;"><?php echo $datas['size'];?></div>
<input type="checkbox" name="cek[]" id="cek" class="hidden" value="<?php echo $i ?>" autocomplete="off" >
<input type="hidden" name="image[]" id="image[]" value="<?php echo $datas['image'] ?>" />
<input type="hidden" name="page[]" id="page[]" value="<?php echo $datas['page'] ?>" />
<input type="hidden" name="size[]" id="size[]" value="<?php echo $datas['size'] ?>" />
<input type="hidden" name="thumbnail[]" id="thumbnail[]" value="<?php echo $datas['thumbnail'] ?>" />
<input type="hidden" name="image_alt[]" id="image_alt[]" value="<?php echo $datas['image_alt'] ?>" />
<input type="hidden" name="title[]" id="title[]" value="<?php echo $datas['title'] ?>" />
</label>
</div>
<?php $i++; } ?>
<button type="submit" id="edit_submit" class="btn btn-success edit_submit">Next Step <i class="fa fa-arrow-right" aria-hidden="true"></i></button>
</form>
then I want POST via AJAX, this my little javascript:
jQuery(document).ready(function($) {
$('#result-image').submit(function(e) {
e.preventDefault();
data = { action : 'aad_edit_results',
//////////// WHAT I SHOULD WRITE /////
// image : $("#image").val(), /// This work if one
// page : $("#page").val(), /// This work if one
// size : $("#size").val(), /// This work if one
// title : $("#title").val(), /// This work if one
//////////// WHAT I SHOULD WRITE /////
beforeSend : function(){
$('#myPleaseWait').modal('show');
//$('.edit_submit').attr('disabled',true);
},
};
$.post(ajaxurl, data, function(response) {
$("#edit-image-modal").html(response).modal();
$('#myPleaseWait').modal('hide');
//$('#edit_submit').attr('disabled',false);
});
return false;
});
});
how can I change this code, because it only work if single name is used?
// image : $("#image").val(), /// This work if one
// page : $("#page").val(), /// This work if one
// size : $("#size").val(), /// This work if one
// title : $("#title").val(), /// This work if one
I have tried many more concepts but they are not working, can anybody help me?

I think it will help you. Convert form data to JavaScript object with jQuery
You can send this converted data with ajax, but if you want to send to ajax only checked elements you can use it.
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
// you can also change it to $('#result-image').submit(function(){});
$("#edit_submit").on({
click: function (e) {
e.preventDefault();
var form = $('#result-image'),
data = form.serializeObject(),
checkbox = form.find('input[type=checkbox]:checked'),
sendAjaxData = [];
$.each(checkbox, function (i, k) {
sendAjaxData[i] = {
image: data['image[]'][k.value - 1], // why -1? because of your checkbox value starts from 1, but `i` starts from 0
page: data['page[]'][k.value - 1],
// ...... write your other inputs
};
});
console.log(sendAjaxData); // send to ajax `sendAjaxData`
// .. ajax request goes here.
$.ajax({
url: "sendRequest.php",
method: "POST",
data: {data:sendAjaxData},
dataType: "json", // if you want to get object data use json, but you want to get text data then use html
success: function (data) {
},
error: function (data) {
}
});
return false;
}
});
PHP File sendRequest.php
<?php
print_r($_POST);
//also you can get with $_POST["data"];
I hope it will help you.

Use classes, not IDs. ID (= unique IDentifier) must be unique across the DOM.
var values = $.map( $(".someInputClass"), function(elem){
return $(elem).val();
})
console.log(values);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="someInputClass" value="Input 1"/>
<br>
<input class="someInputClass" value="Input 2"/>
<br>
<input class="someInputClass" value="Input 3"/>
<br>
<input class="someInputClass" value="Input 4"/>
This code grabs all the <input>, reads their values and puts them in an array. Then send the array of values to the server. That's one way to do it.

Related

How to serialize form data by number in javascript and submit with a specific number

I'm working on a personal project, where I've more forms than one (comment forms under each post). Each form I give a number according to post id.
<form id="postCommentsForm<?php echo $ansRow['id'];?>" class="form">
<div class="input-group mb-3">
<a href="user/<?php echo $username;?>">
<img class="p-1 m-0" src="images/<?php echo $userAvatar;?>" width="35" height="35" alt="<?php echo $userAvatar;?> profile picture">
</a>
<input name="post_comment<?php echo $ansRow['id'];?>" id="add_comments" type="text" autofocus autocomplete="off" class="add_comments form-control pl-3 pr-3" placeholder="<?php echo $userFname;?>, type something" aria-label="Recipient's username" aria-describedby="button-form">
<input type="text" hidden id="question_id" name="question_id" value="<?php echo $row['id'];?>">
<input type="text" hidden id="answer_id" name="answer_id" value="<?php echo $ansRow['id'];?>">
<input type="text" hidden id="session_id" name="session_id" value="<?php echo $_SESSION['id'];?>">
<div class="input-group-append">
<button class="btn btn-secondary submit-comments" type="submit" name="submit_comment<?php echo $ansRow['id'];?>" id="postComments">Comment</button>
</div>
</div>
</form>
javascript code
$(document).ready(function() {
$("[id^=postCommentsForm]").on("submit", function(e) {
e.preventDefault();
var add_comments = $("#add_comments").val();
var question_id = $("#question_id").val();
var answer_id = $("#answer_id").val();
// var session_id = $("#session_id").val();
if(add_comments == "" ){
$("#error-message").html("All fields are required!").slideDown();
$("#success-message").slideUp();
}else{
//Ajax
$.ajax({
url: "include/forms-data/comments.php",
type: "POST",
data: {
add_comments: add_comments,
question_id: question_id,
answer_id: answer_id
},
success: function(data) {
if (data != 0) {
$("[id^=postCommentsForm").trigger("reset");
$("#success-message").html("Question Added Successfully!").slideDown();
$("#error-message").slideUp();
} else {
//alert("Can't save record");
$("#error-message").html("Something went wrong!").slideDown();
$("#success-message").slideUp();
}
}
});
}
});
});
How I can fetch #comments(postID here), and submit form data successfully under the postID?
I hope I define well the question.
Jquery's "starts with selector" can help. check out here
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
var element_id = this.getAttribute("id");
});
});
Live Demo:
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
console.log($(this).attr('id'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='comments1'>b</button>
<button id='comments2'>a</button>

Return mysql fetch data and insert into form field value

i have a list of clients on a page, each client has an icon to click on to edit the client details.
<i class="fas fa-user-edit gray openModal" data-modal="modal2" client="'.$client['id'].'"></i>
Everything is good up to this point. click the icon the proper modal opens and it triggers the js file just fine. (I did alot of console logs to ensure). The client variable in my jquery file holds fine and i'm able to get it passed to the php file.
in the php file i'm able to pull the information into an array and i was able to just echo the $client['firstName'] and have it show in the console.
when i moved to getting that information and parse it as the Json is when i got lost. Can someone please help me take my result and load into my form fields. The code i have now may be totally off because i've been playing with different code from different searches.
form (shortened to two fields for ease of example)
<form id="form" class="editClient ajax" action="ajax/processForm.php"
method="post">
<input type="hidden" id="refreshUrl" value="?
page=clients&action=view&client=<?php echo $client['id'];?>">
<input type="hidden" name="client" value="<?php echo $client['id'];?>">
<div class="title">
Client Name
</div>
<div class="row">
<!-- first name -->
<div class="inline">
<input type="text" id="firstName" name="firstName" value="<?php echo $client['firstName']; ?>" autocomplete="nope" required>
<br>
<label for="firstName">First Name<span>*</span></label>
</div>
<!-- last name -->
<div class="inline">
<input type="text" id="lastName" name="lastName" value="<?php echo $client['lastName']; ?>" autocomplete="nope" required>
<br>
<label for="lastName">Last Name<span>*</span></label>
</div>
</form>
javascript/jquery file
$('.openModal').on('click', function() {
//$('body, html, div').scrollTop(0);
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
var data = result.rows;
$("#firstName").val(data[0]);
}
})
});
php file
<?php
include('../functions.php');
$sql = 'SELECT * FROM clients WHERE id="'.$_POST['id'].'"';
$result = query($sql);
confirmQuery($result);
$data = fetchArray($result);
echo json_encode(['response' => $data, 'response' => true]);
?>
UPDATED ----------
Here is my final js file that allowed my form values to be set.
$('.openModal').on('click', function() {
var that = $(this),
client = that.attr('client');
$.ajax({
type: "post",
url: "ajax/getClient.php",
data: {id:client},
success: function(response){
var result = JSON.parse(response);
$("select#primaryContact").append( $("<option>")
.val(result[0].primaryContact)
.html(result[0].primaryContact)
);
$("select#primaryContact").append( $("<option>")
.val("")
.html("")
);
if (result[0].email !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].email)
.html(result[0].email)
);
}
if (result[0].phoneCell !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneCell)
.html(result[0].phoneCell)
);
}
if (result[0].phoneHome !== "") {
$("select#primaryContact").append( $("<option>")
.val(result[0].phoneHome)
.html(result[0].phoneHome)
);
}
$("input#firstName").val(result[0].firstName);
$("input#lastName").val(result[0].lastName);
$("input#address").val(result[0].address);
$("input#city").val(result[0].city);
$("input#zip").val(result[0].zip);
$("input#email").val(result[0].email);
$("input#phoneCell").val(result[0].phoneCell);
$("input#phoneHome").val(result[0].phoneHome);
$("input#phoneFax").val(result[0].phoneFax);
$("input#source").val(result[0].source);
$("input#referBy").val(result[0].referBy);
$("input#client").val(result[0].id);
}
})
});

select specific element jquery inside php foreach loop

I have foreach loop in php on front page for getting images and description of the image, inside foreach loop I have form, form is use for sending comment, this is front page..
<?php foreach ($photo as $p) : ?>
<div class="photo-box">
<div class="galP photo-wrapper" >
<div data-fungal="<?php echo $p->id; ?>" class='galFun-get_photo'>
<img src="<?php echo $p->thumb; ?>" class='image'>
</div>
</div>
<div class='inline-desc'>
<a href="/gallery/user.php?id=<?php echo $p->userId; ?>">
<?php echo $p->username; ?>
</a>
</div>
<form method="POST" action="" class="form-inline comment-form galForm">
<div class="form-inline">
<input type="hidden" class='photoId form-control' name="photoId" value="<?php echo $p->id; ?>" >
<input type="hidden" class='userId form-control' name="userId" value="<?php echo $session->userId; ?>" >
<textarea cols="30" rows="3" class='comment fun-gal-textarea' name="comment" placeholder="Leave your comment"></textarea>
<button type='button' name='send' class='sendComment'>SEND</button>
</div>
</form>
<div class='new-comm'></div>
<div class='comments-gal' id='comments'>
<div data-id='<?php echo $p->id; ?>' class='getComment'>
<span>View comments</span>
</div>
</div>
</div>
Using ajax I want to send userId,photoId and comment after clicking the button that has class sendComment. When I send comment on the first image everything is ok but when I try to send comment for some other image it wont work. I can't select that specific input and textarea for geting the right value .This is my jquery
$('body').on('click','.sendComment',function(){
var selector = $(this);
var userId = selector.siblings($('.userId'));
var photoId = selector.siblings($('.photoId'));
var c = selector.siblings($('.comment'));
var comment = $.trim(c.val());
if (comment == "" || comment.length === 0) {
return false;
};
$('#no-comments').remove();
$.ajax({
url: '/testComment.php',
type: 'POST',
data: {comment:comment,userId:userId,photoId:photoId}
}).done(function(result) {
...
}
})
});
Also, I have tried in every possible way to get the right value from the form without success..
This line
var userId = selector.siblings($('.userId'));
will be unlikely to get the correct input as, according to https://api.jquery.com/siblings/
.siblings( [selector ] )
selector
A string containing a selector expression to match elements against.
so this would need to be :
var userId = selector.siblings('.userId');
at that point you also need to get the actual value from the input, giving:
var userId = selector.siblings('.userId').val();
var photoId = selector.siblings('.photoId').val();
var c = selector.siblings('.comment');
and the rest of the code as-is.

AJAX not submitting fom

I am working with a script wherein I should be able to submit a form without page reload with the help of AJAX. The problem is that the form is not submitted to the database. Any help would be appreciated. I had messed with the codes but nothing works for me.
Here is the javascript code:
<script type="text/javascript">
setInterval(function() {
$('#frame').load('chatitems.php');
}, 1);
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var usercontent = $("#username").val();
var namecontent = $("#nickname").val();
var dataString = 'content=' + textcontent;
var userString = 'content=' + usercontent;
var nameString = 'content=' + namecontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "chatitems.php",
data: {
dataString,
userString,
nameString
},
cache: true,
success: function(html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#frame").focus();
}
});
}
return false;
});
});
</script>
this is my form:
<form action="" method="post" name="form">
<input type="hidden" class="form-control" id="username" name="username" value="<?php echo $username; ?>" readOnly />
<input type="hidden" class="form-control" id="nickname" name="nickname" value="<?php echo $nickname; ?>" readOnly />
<input type="hidden" class="form-control" id="chat_role" name="chat_role" value="<?php echo $pm_chat; ?>" readOnly />
<input type="hidden" class="form-control" id="team" name="team" value="<?php echo $manager; ?>'s Team" readOnly />
<input type="hidden" class="form-control" id="avatar" name="avatar" value="<?php echo $avatar; ?>" readOnly />
<div class="input-group">
<input type="text" class="form-control" id="content" name="content" />
<span class="input-group-btn">
<input type="submit" name="submit" class="submit_button btn btn-primary" value="Post"></input>
</span>
</div>
</form>
and finally, this is my PHP code:
<?php
include('db.php');
$check = mysql_query("SELECT * FROM chat order by date desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$nickname=mysql_real_escape_string($_POST['nickname']);
$username=mysql_real_escape_string($_POST['username']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into chat(message,ip,username,nickname) values ('$content','$ip','$username','$nickname')");
}
$req = mysql_query('select * from chat ORDER BY date desc');
while($dnn = mysql_fetch_array($req))
{
?>
<div class="showbox">
<p><?php echo $dnn['username']; ?> (<?php echo $dnn['ip']; ?>): <?php echo $dnn['message']; ?></p>
</div>
<?php
}
?>
I know there is something wrong with my code somewhere but had spent few days already but no avail. Im hoping that someone would help.
UPDATE
The form is being submitted successfully with this code only data: dataString but when I added the nameString and the userString thats when everything doesnt work as it should. I tried messing around that code but still got nothing.
To find out what is wrong with this you need to establish that:
a) The click event is firing, which you could test by adding a console.log('something'); at the top of that function.
b) The AJAX function is working somewhat correctly, which again you could check by adding a console.log() in the success callback of the AJAX request. You can also check console for errors, e.g if the chatitems.php is 404'ing
c) That all the data you're collecting from the DOM e.g var textcontent = $("#content").val(); contains what you're expecting it to. Again console.log().
d) That the page you're calling is successfully processing the data you're sending across, so die() a print_r() of the $_POST values to check the data it's receiving is in the format your expecting. You also need to add some error handling to your mysql code: https://secure.php.net/manual/en/function.mysql-error.php (or better yet use PDO or MySQLi https://secure.php.net/manual/en/book.pdo.php), which will tell you if there's something wrong with your MySQL code. You can check the return of you're AJAX call (which would include any errors) by console.log(html) in your success callback.
Information you gather from the above will lead you to your bug.
If i understand right, it seem you try to bind event before the button is available. Try (depend on the version of JQuery you use) :
$(document).on('click, '.submit_button', function(){
...
});

Processing form using jQuery

I need to process my form using jQuery (without refresh my site ) and using one buddon i want to add or delete row from my database .
Inserting to database works fine
Deleteting too but i dont know what i need to do that after first click i add to database but after second click i delete row from database.
My FORM
<form action="index.php" method="post" id="myForm">
<input type="hidden" name="option" value="com_mediamall" />
<input type="hidden" name="task" value="addToFav" />
<input type="hidden" name="addMediaId" value="<?php echo $media->id; ?>" />
<input type="hidden" name="delRow" value="<?php echo $del->id; ?>" />
<input type="submit" name="submit" id="sub" value="1"></input>
</form>
jQUERY
<script>
$("#sub").click( function() {
$.post( $("#myForm").attr("action"), $("#myForm :input").serializeArray());
});
$("#myForm").submit( function() {
return false ;
});
</script>
FUNCTION INSERT OR DELETE
function addToFav() {
$user =& JFactory::getUser();
$db2 =& JFactory::getDBO();
$mediaid = $_POST['addMediaId'];
$delid = $_POST['delRow'];
if(isset($_POST['submit']) == '1') {
$query = ' INSERT INTO `#__mediamall_favourite_media` (`id`, `userid`, `mediaid`) VALUES ("","'.$user->id.'","'.$mediaid.'")';
}
elseif(isset($_POST['submit']) == '0') {
$query = ' DELETE FROM #__mediamall_favourite_media WHERE id = "'.$delid.'" ';
$db2->setQuery($query);
$db2->query();
}
}
Will be apriciate form your help because i spend a lot of hours to find the anwer and without the result .. Thanks
you need to use preventDefault
$('#myForm').submit(function(e){
e.preventDefault();
var url = $("#myForm").attr("action");
$.post(url,{data : $('#myForm').serialize()},function(data){
//process
});
});
and you can also use json to retrieve data from php so in your php file you can do
$data['res'] = 'ok';
$data['something_else'] = 'value';
echo json_encode($data);
Then process it like this
$('#myForm').submit(function(e){
e.preventDefault();
var url = $("#myForm").attr("action");
$.post(url,{data : $('#myForm').serialize()},function(data){
//process
console.log(data.res);
console.log(data.something_else);
}.'json');
});
Toggle submit button value after insert or delete like,
$("#sub").click( function() {
var url=$("#myForm").attr("action");
$.post(url, $("#myForm :input").serializeArray(),function(){
var val=$("#sub").val()==1 ? 0 : 1;// toggle value of submit for insert or delete
$("#sub").val(val);
});
});
In PHP change your condition from isset($_POST['submit'])=='1' to isset($_POST['submit']) and $_POST['submit'] == '1'
Code like,
if(isset($_POST['submit']) and $_POST['submit'] == '1') {
$query = ' INSERT INTO `#__mediamall_favourite_media` (`id`, `userid`, `mediaid`) VALUES ("","'.$user->id.'","'.$mediaid.'")';
}
elseif(isset($_POST['submit']) and $_POST['submit'] == '0') {
$query = ' DELETE FROM #__mediamall_favourite_media WHERE id = "'.$delid.'" ';
}
if($query)
{
$db2->setQuery($query); //after if - else conditions
$db2->query();
}
HTML
<form action="" onsubmit="return false;" method="post" id="myForm">
<input type="hidden" name="option" value="com_mediamall" />
<input type="hidden" name="task" value="addToFav" />
<input type="hidden" name="addMediaId" value="<?php echo $media->id; ?>" />
<input type="hidden" name="delRow" value="<?php echo $del->id; ?>" />
<input type="submit" name="submit" id="sub" value="1"></input>
JQUERY
$('#myForm').submit(function(){
$.post(url,$('#myForm').serialize(),function(success){
if(success=='success'){
alert('Data Sent);
// or do something else
}
});
});

Categories

Resources