AJAX not submitting fom - javascript

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

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

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 call successful, but can't get radio values from $_POST

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>

Getting form $_POST data from Ajax/Jquery in php

As always thanks in advance if you can help with this one.
I'm trying to use Ajax to call a script and post the form data at the same time. Everything works as expected except the $POST data which comes back blank when I try to echo or print it. Can anyone shine a light on what I have missed here please?
<form id="guestlist" name="guestlist">
<?php // Collect CLUBS data to pass to guestlist script ?>
<input type="hidden" name="gl_clubname" value="<?php echo $ptitle; ?>" />
<input type="hidden" name="gl_clubnumber" value="<?php echo $phoneno_meta_value; ?>" />
<input type="hidden" name="gl_clubemail" value="<?php echo $email_meta_value; ?>" />
<?php // Collect USERS data to pass to guestlist script ?>
<input type="hidden" name="gl_name" value="<?php echo $fullname;?>" />
<input type="hidden" name="gl_email" value="<?php echo $email;?>" />
<input type="hidden" name="gl_dob" value="<?php echo $birthday;?>" />
<input type="hidden" name="gl_propic" value="<?php echo $profile_url;?>" />
<div id="clubcontactleft">
<textarea id="clubmessage" name="gl_message" placeholder="Your message" rows="4" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/userreview.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 94px; width:250px; margin-bottom:15px;"></textarea>
<input type="text" name="gl_when" placeholder="Enquiry Date" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/calendaricon.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
<input type="text" name="gl_phonenumber" placeholder="Phone Number" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/phonecall.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
</div>
<div class="guestlistbutton">Send Message</div>
</form>
<script type="text/javascript">
$(document).ready(function($){
$(".guestlistbutton").on('click',function(event) {
event.preventDefault();
$("#clubcontactform").empty();
var url = "http://www.xxxxxx.com/wp-content/themes/xxxxxx/guestlist.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#guestlist").serialize(), // serializes the form's elements.
success: function(data)
{
$('#clubcontactform').append(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
Here is the php file that it pulls in
<?php
echo 'Pulling in guestlist.php<br/>';
$gl_message = $_POST['gl_message'];
print_r($gl_message);
echo $gl_message;
?>
Thanks!
Every thing seems to be correct only you forget to include the jquery file. please include and try once. If still persist the issue will create the Jsfiddle
I checked your code in my local machine and I got the following error "Caution provisional headers are shown". If you have the same message in your browser console, this information can help you: "CAUTION: provisional headers are shown" in Chrome debugger
Also, I see that js work perfectly. Problem in your url address. Try send your form to itself, just write html part and php part of code in one file.
<div>
<form id="Get_FRm_Data">
/*
Some field using.....
/*
</form>
<button type="button" name="submit" class="submit_act">Submit</button>
</div>
<script>
var file_pathname = window.location.protocol + "//" + location.host + "/foldername/";
$(document).on("click", ".submit_act", function ()
{
var $this_val=$(this);
$this_val.html("Loading...").prop("disabled",true);
var $data_ref = new FormData($("#Get_FRm_Data")[0]);
$data_ref.append("action", "fileaction_name");
$pathname = file_pathname + "filename.php";
$.ajax({
url: $pathname,
type: 'POST',
data: $data_ref,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function (result, status)
{
console.log(result);
if (status == "success")
{
$this_val.html("Submit").prop("disabled",false);
}
}
});
});
</script>
<?php
if (isset($_POST['action']))
{
$action = $_POST['action'];
if($action=="fileaction_name")
{
print_r($_POST);
}
}
?>

search result not showing in the same window

my search result does not show on the same window, i would want the result to be displayed on the same window. i have found the same question but the code is different from what I'm using so i cant relate to it: Search wont show on same page
scenario 1:
if I put in the action="search_result2.php" - it will redirect the result on the other page
scenario 2:
if i used action="" in this code below, its not doing anything
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
$(document).ready(function(){
$("#results").show();
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#search").on('click',function() {
var find = $('#find').val();
var field = $('#field').val();
$.post('search_result2.php',{find:find, field:field}, function(data){
$("#results").html(data);
});
return false;
});
});
</script>
</head>
<body>
<div id="container" style="width:auto">
<div id="mainContent">
<h2>Search</h2>
<form name="search" method="post" action="">
Seach for: <input type="text" name="find" id="find" /> in
<Select NAME="field" id="field">
<Option VALUE="testA">A</option>
<Option VALUE="testB">B</option>
<Option VALUE="testC">C</option>
<Option VALUE="testD">D</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" id="search" value="Search" />
</form>
<div id="results">
</div>
</div>
</div>
</body>
</html>
here is my search_result2.php:
<?php
//This is only displayed if they have submitted the form
if (isset($_POST['searching']) && $_POST['searching'] == "yes")
{
echo "<h2>Results</h2><p>";
//If they did not enter a search term we give them an error
if (empty($_POST['find']))
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("host", "username", "passw") or die(mysql_error());
mysql_select_db("testdb") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($_POST['find']);
$find = strip_tags($_POST['find']);
$find = trim ($_POST['find']);
$field = trim ($_POST['field']);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM testtable WHERE upper($field) LIKE'%$find%'");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
echo $result['testA'];
echo " ";
echo $result['testB'];
echo "<br>";
echo $result['testC'];
echo "<br>";
echo $result['testD'];
echo "<br>";
echo "<br>";
}
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
If you want to load in the same page, without refreshing the page, you'll need to make an ajax request.
If you can reload the page, the php part must be in the same "location" as your original link.
For example if you put that code on the top of the same file with the form (and rename it with a .php extension), it should work (if the php can interpret in that folder).

Categories

Resources