Ajax call successful, but can't get radio values from $_POST - javascript

My site is fully asynchronus, most of the html gets created and destroyed on button presses and every one of them prevents navigation.
At this part I produce a form with a "rate 1 to 10" array of radioboxes, post it using jQuery.ajax() and send it to process where it's either echoed back (for now) or echo "nothing was selected.".
This is the form,
<?php
<form id="surveyForm" action="processSurvey.php" method="post">
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">';
for ($i = 0; $i <= 10; $i++) {
echo '
<span class="lead form-options">' .'</span>
<label class="radio-inline">
<input type="radio" name="sabor" id="saborRadio'. $i .'" value="'. $i .'">'. $i.'
</label>';
}
echo '
</div>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>
?>
This is the javascript:
$('body').on('click', '.surveyForm', function(){
console.log("Clicked on .surveyForm-btn");
var data = $('#surveyForm').serialize();
console.log( data );
$.ajax({
method: "POST",
url: "processSurvey.php",
data: data,
success: function(result){
console.log("Ajax call to processSurvey success");
$("#surveyForm").clearForm();
console.log(result);
console.log( data );
}
});
return false;
});
And this is the process php:
<?php
if (isset($_POST['sabor'])) // if ANY of the options was checked
echo $_POST['sabor']; // echo the choice
else
echo "nothing was selected.";
print_r($_POST);
?>
This is the console after clicking submit WITH a selected radiobox:
Clicked on #surveyForm
[EMPTY LINE]
Ajax call to processSurvey success
nothing was selected.
[EMPTY LINE]
This means the submit is successful, but the form data is empty. I've been trying to find the problem since yesterday, I'm pretty sure I'm passing the data wrong but can't find anything in google that I haven't tried.
EDIT: Added most sugestions, problem persists. Maybe the html structure is wrong? The form and the submit don't seem to be connected.
EDIT 2: I found something very strange, on the final code there seems to be an extra closing tag, like this
<form id="surveyForm" action="processSurvey.php" method="post"></form>
<h3>Alimentos</h3>
<h4>Sabor</h4>
I have no idea where is that coming from, but is defenitely the problem.

there are a lot of notes here
1- you will get confused with form id='surveyForm' and button class='surveyForm' so its better to change it a little bit to button class='surveyForm_btn'
2- I think you should serialize the form not the button
var data = $('#surveyForm').serialize(); // not .surveyForm
3- IDs must be unique
4- $("#surveyForm").clearForm(); // not .surveyForm
finally check all comments
and Its better to use
$('body').on('submit', '#surveyForm', function(){});
Edited answer:
1- please check everything after each step
<form id="surveyForm" action="processSurvey.php" method="post">
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>
in js
$('body').on('submit', '#surveyForm', function(){
var data = $(this).serialize();
$.ajax({
method: "POST",
url: "processSurvey.php",
data: data,
success: function(result){
console.log(result);
}
});
return false;
});
in php
<?php
echo 'Connected successfully';
?>
this code will output Connected successfully in console .. if this work add your for loop and make a check again

Try to write your htm like that :
<h3>Alimentos</h3>
<h4>Sabor</h4>
<div class="form-group">
<?php
for ($i = 0; $i <= 10; $i++) {
?>
<span class="lead form-options"></span>
<label class="radio-inline">
<input type="radio" name="sabor" id="saborRadio<?=$i ?>" value="<?= $i ?>" /><?= $i?>
</label>
<?php
} ?>
</div>
<div class="form-group">
<button class="btn btn-default surveyForm-btn" type="submit">Enviar</button>
</div>
</form>

Related

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);
}
})
});

Immediately update value inside textarea, taken from session after ajax send in codeigniter

I wanted to retrieve value from session immediately after it updates, but for some reason, sometimes, the value that I get is still the old value, but some other time it gets the new value. Perhaps there is something missing in my code. Here is the code:
HTML
<?php
$temp_message = $this->session->userdata('temporary_message');
?>
<form action="<?php echo base_url($form_url)?>" method="post">
<div class="box-body">
<div class="form-group">
<label for="receiver_number">Receiver:</label>
<textarea class="form-control" id="receiver_number" name="receiver_number" rows="5"><?php if (isset($temp_message)) { echo $temp_message['num_temp']; }?></textarea>
<span class="help-block"><?php echo form_error('receiver_number');?></span>
</div>
<div class="form-group <?php if(form_error('message-text') != NULL) { echo 'has-error'; }?>">
<label for="message_text">Message Text</label><div class="pull-right"><span id="chars">0</span></div>
<textarea class="form-control" name="message_text" id="message_text" rows="5"><?php if(isset($temp_message)) { echo $temp_message['message_temp']; }?></textarea>
<span class="help-block"><?php echo form_error('message_text'); ?></span>
<p id="message_temp" hidden><?php if(isset($temp_message)) { echo $temp_message['message_temp'];} ?></p>
</div>
<div class="box-footer">
<button type="submit" name="submit" id="submit" value="Submit" class="btn btn-primary">Submit</button>
<button type="submit" name="submit" value="Cancel" class="btn btn-warning">Cancel</button>
</div>
</form>
=================== JS ==================
$(window).on('unload, load, beforeunload', function () {
let tempNum= $('#receiver_number').val();
let messageTemp = $('#message_text').val();
$.ajax({
type: "POST",
url: "<?php echo base_url('save-textarea'); ?>",
dataType: "JSON",
data: {
receiver_number: tempNum,
message_text : messageTemp
}
});
});
================== Controller ==================
function save_textarea()
{
$data['num_temp'] = $_POST['receiver_number'];
$data['message_temp'] = $_POST['message_text'];
$message_session = $this->session->userdata('temporary_message');
if (isset($message_session))
{
if (($message_session['num_temp'] != $data['num_temp']) || ($message_session['message_temp'] != $data['message_temp']))
{
$this->session->unset_userdata('temporary_message');
$this->session->set_userdata('temporary_message', $data);
}
}
else
{
$this->session->set_userdata('temporary_message', $data);
}
echo json_encode($data);
}
So, I echoed out the value from the temporary_message session inside the <textarea>. As I said, sometimes the values in the <textarea> changed, sometimes it don't, therefore I have to insert the same value again, and reload the page, for several times (1, 2, sometimes 3 times). The values are being sent to the controller every time the user reload or change other page, then return to the same page again.
Thank you for the help.

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(){
...
});

Refresh div with jquery in ajax call

I have a div that has foreach's in them like so:
<div id="conversation">
<?php foreach($singles as $question): ?>
<div class="well well-sm">
<h4><?php echo $question['question_title']; ?></h4>
</div>
<div class="bubble bubble--alt">
<?php echo $question['question_text']; ?>
</div>
<?php endforeach; ?>
<?php foreach($information as $answer): ?>
<div class="bubble">
<?php echo $answer['answer_text']; ?>
</div>
<?php endforeach; ?>
</div>
And I also have a form to put in a new answer:
<form method="post" style="padding-bottom:15px;" id="answerForm">
<input type="hidden" id="user_id" value="<?php echo $_SESSION['user_id']; ?>" name="user_id" />
<input type="hidden" id="question_id" value="<?php echo $_GET['id']; ?>" name="question_id" />
<div class="row">
<div class="col-lg-10">
<textarea class="form-control" name="answer" id="answer" placeholder="<?php if($_SESSION['loggedIn'] != 'true'): ?>You must be logged in to answer a question <?php else: ?>Place your answer here <?php endif; ?>" placeholder="Place your answer here" <?php if($_SESSION['loggedIn'] != 'true'): ?>disabled <?php endif; ?>></textarea>
</div>
<div class="col-lg-2">
<?php if($_SESSION['loggedIn'] != 'true'): ?>
<?php else: ?>
<input type="submit" value="Send" id="newAnswer" class="btn btn-primary btn-block" style="height:58px;" />
<?php endif; ?>
</div>
</div>
</form>
I am submitting the form via ajax and would like the div #conversation to refresh and reload the for each every time the user submits an answer to the question. Right now I have the following ajax code:
<script type="text/javascript">
$("#newAnswer").click(function() {
var answer = $("#answer").val();
if(answer == ''){
$.growl({ title: "Success!", message: "You must enter an answer before sending!" });
return false;
}
var user_id = $("input#user_id").val();
var question_id = $("input#question_id").val();
var dataString = 'answer='+ answer + '&user_id=' + user_id + '&question_id=' + question_id;
$.ajax({
type: "POST",
url: "config/accountActions.php?action=newanswer",
data: dataString,
success: function() {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#answerForm").find("input[type=text], textarea").val("");
$("#conversation").hide().html(data).fadeIn('fast');
}
});
return false;
});
</script>
You will notice that I have tried $("#conversation").hide().html(data).fadeIn('fast'); but it did not successfully do the job. It only reloaded the information that was passed through ajax into the div instead of just reloading the foreach.
How can I refresh the div or the <?php foreach(); ?> in the success function of the ajax call?
Mitch, I'm looking at this part:
success: function() {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#answerForm").find("input[type=text], textarea").val("");
$("#conversation").hide().html(data).fadeIn('fast');
}
See the expression ".html(data)"??? Where is "data" being declared? The code above will never work. Now, look at the lines below. Particularly the first one. See my change?
success: function(data) {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#answerForm").find("input[type=text], textarea").val("");
$("#conversation").hide().html(data).fadeIn('fast');
}
Once you make this change, you need to use a debugger (chrome's or otherwise) to examine that what's coming back from your ajax call (which we don't have here) is what you need. But first, fix the bug.
Good luck.
jQuery .load() method (http://api.jquery.com/load/) can fetch and update single block from webpage. It will reload whole webpage in background, so some overhead is generated..
Change your ajax success to something like below:
success: function() {
$.growl({ title: "Success!", message: "Your answer was submitted successfully!" });
$("#conversation").load("config/accountActions.php #conversation >*");
}
This should load your conversation block and all it's childs and replace current(old) conversation block.

Categories

Resources