I'm trying to pass the parameter of a form $_POST['txtBody'] into a div via jquery/javascript.
the PHP file to be loaded:
ajax-rewriter.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
print_r($_POST);
$articleBody = strtolower($_POST['txt']);
echo "<pre><b>Original:</b><br /><br /><p>" . $articleBody . "</p></pre>";
$word = "";
$length = strlen($articleBody);
$OutputBody = "";
for ($i = 0; $i < $length; $i++) {
$word = $word . $articleBody[$i];
if ($i == $length - 1)
$comeCha = " ";
else
$comeCha = $articleBody[$i + 1];
$retStr = getWordPattern($word, $comeCha, "syn/en.syn");
if ($retStr != "") {
$OutputBody .= $retStr;
$word = "";
}
}
echo "<br>";
echo "<pre><b>Spun:</b><br /><br /><p>" . $OutputBody . $word . "</p></pre>";
}
?>
The HTML form:
<div id="mainContent"></div>
<div class="panel panel-primary">
<div class="panel-heading">Your article rewriter API is: (<span class="results"><b>http://www.wraithseo.com/api.php?rewriter=1&key=<?php echo $user['api_key']; ?></b></span>)</div>
<div class="panel-body">
<form id="frmAjax" action="rewriter.php" method="post" class="form-horizontal container-fluid" role="form">
<div class="row form-group">
<div class="col-sm-4 text-right"><label for="txtBody" class="control-label">Article:</label></div>
<div class="col-sm-8"><textarea class="form-control" id="txtBody" name="txtBody" required="required"></textarea></div>
</div>
<div class="row form-group">
<div class="col-sm-12 text-right">
<button type="submit" name="spinText" class="btn btn-default">Spin!</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">Paste in an article above and hit <b>Spin</b>!</div>
</div>
<script>
$(document).ready(function(){
$('#frmAjax').submit(function(e) {
e.preventDefault(); // important so the submit doesn't clear the data...
$.ajax({
type: "POST",
url: "ajax-rewriter.php",
data:{ txt: <?php echo $_POST['txtBody']; ?> }
})
$("#mainContent").load('ajax-rewriter.php')
});
});
</script>
I have tried but cannot remember the proper way to pass the $_POST['txtBody'] value to the loaded .php file and show it in the div
Any help would be appreciated.
So it looks like you want to send whatever is typed into the <textarea class="form-control" id="txtBody" name="txtBody" required="required"></textarea> element to be passed to the php file ajax-rewriter.php for processing via JQuery ajax, correct?
I don't think you should be trying to get from your $_POST variable inside your AJAX request. Rather, you're sending the value of the textarea through your AJAX request (which is utilizing the POST method to send the data).
Here is what I believe you are looking for:
$(document).ready(function(){
$('#frmAjax').submit(function(e) {
var text = $('#txtBody').val(); // ADDED THIS
e.preventDefault();
$.ajax({
type: "POST",
url: "ajax-rewriter.php",
data:{textData : text} // MODIFIED THIS
})
$("#mainContent").load('ajax-rewriter.php')
});
});
Then, in your php file, you can get the text variable through the $_POST variable:
$data = $_POST["textData"];
You can then choose what to do whatever you want with the data in your php file. If you are trying to send the data via ajax to php, modify it via php, then send it back as a response to the ajax request, look into JQuery's success and complete callback functions that are part of the JQuery ajax call.
Here is an example using the success callback:
$.ajax({
type: "POST",
url: "email.php",
data: {fullName, phoneNumber, email, comments, response},
success: function(dataRetrieved){
$("#response").html(dataRetrieved);
}
});
The php file email.php receives the data via $_POST through the ajax request, processes it, and then the email.php file will echo data as output from the server. The data that is echoed is sent back as a response to the ajax request, which can be retrieved as a parameter in the success callback.
Related
The function that this do is when the user clicked the button, it will execute the Ajax codes and then get the value of the input and send it to the PHP file and then send it back to the Ajax code to display the message from the MySQL table.
I tried changing my codes, changing div ids, changing syntax, clearing block of codes but none seems to work.
AJAX
<script>
$(document).ready(function() {
$("#snd").click(function() {
var msgg = $('input[name=message]').val();
$.ajax({
type: "POST",
url: 'automatedchat_func.php',
data: {newmsg: msgg},
success: function(data) {
$("#conversation").html(data);
}
});
});
});
</script>
HTML UPDATED
<div class="convo">
<div class="convo_field" id="conversation">
</div>
<div class="obj">
<div class="txtbox">
<form method="POST">
<input type="input" id="msg" name="message" placeholder="Type exact or related word(s) of your question"/>
</form>
</div>
<div class="but_send"><button id="snd" name="send">SEND</button></div>
</div>
</div>
PHP UPDATED
<?php
include 'database/connect.php';
session_start();
$sql = "SELECT * FROM ai WHERE keywords LIKE '%$_POST[message]%' OR '$_POST[message]%_' OR '$_POST[message]_'";
$result = $conn->query($sql);
if ($row = $result->fetch_assoc()) {
echo "Hi ". $_SESSION['name'] .".<br> " . $row['message'];
}
?>
Changes with suggestion(in comment):-
<div class="convo">
<div class="convo_field" id="conversation">
</div>
<div class="obj">
<div class="txtbox">
<input type="input" id="msg" name="message" placeholder="Type exact or related word(s) of your question"/>
</div><!-- form not requird -->
<div class="but_send"><button id="snd" name="send">SEND</button></div>
</div>
</div>
<!-- Add jquery library so that jquery code wiil work -->
<script>
$(document).ready(function() {
$("#snd").click(function() {
var msgg = $('#msg').val(); // id is given so use that, its more easy
$.ajax({
type: "POST",
url: 'automatedchat_func.php',
data: {newmsg: msgg},
success: function(data) {
$("#conversation").html(data);
}
});
});
});
</script>
automatedchat_func.php(must be in the same working directory where your above html file exist)
<?php
error_reporting(E_ALL);// check all type of error
ini_set('display_errors',1);// display all errors
include 'database/connect.php';
session_start();
$final_result='';//a variable
if(isset($_POST['newmsg']) && !empty($_POST['newmsg'])){// its newmsg not message
$message = $_POST['newmsg'];
$sql = "SELECT * FROM ai WHERE keywords LIKE '%$message%' OR '$message%' OR '$message'"; // check the change ere
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) { // while needed
$final_result .="Hi ". $_SESSION['name'] .".<br> " . $row['message']."<br>";
}
}else{
$final_result .="Hi please fill the input box first";
}
echo $final_result; // send final result as response to ajax
?>
Note:- your query is still vulnerable to SQL Injection. So read for prepared statements and use them
first of all, I know this topic has been discussed in the past but I didn't manage to come to a conclusion, so any help is VERY appreciated.
I know a bit of html but I'm not a programmer, I had someone building a website for me but the web form is often sending duplicate (even 3 or 4 times) emails. I believe (assume) it has to do with people refreshing or hitting the submit button more than once. I tried to disable the 'submit' but I didn't manage to.
At this stage any fix would help. As long as I stop receiving multiple emails from senders.
I will try giving you as much information as possible.
This is the html code for the form:
<div class="form-input">
<div class="form-title">NAME</div>
<input id="form-name" type="text"></input>
</div>
<div class="form-input">
<div class="form-title">EMAIL</div>
<input id="form-email" type="text"></input>
</div>
<div class="form-input">
<div class="form-title">MESSAGE</div>
<textarea id="form-msg" type="text"></textarea>
</div>
<div class="form-input">
<div class="form-title"> </div>
<input id="form-send" type="submit" value="SEND"></input>
</div>
</div><!--end of form holder-->
<div id="details-error">Please comlete all fields and include a valid email</div>
<div id="form-sent">Thankyou for your enquiry - We will be in touch shortly!</div>
</div>
</div>
</div>
</div>
the following is the script I have:
// Contact Form Code
$('#form-send').click(function(){
var name = $('#form-name').val();
var email = $('#form-email').val();
var message = $('#form-msg').val();
var option = $('#form-select').val();
var error = 0;
if(name === '' || email === '' || message === ''){
error = 1;
$('#details-error').fadeIn(200);
}else{
$('#details-error').fadeOut(200);
}
if (!(/(.+)#(.+){2,}\.(.+){2,}/.test(email))) {
$('#details-error').fadeIn(200);
error = 1;
}
var dataString = '&option=' + option +'&name=' + name + '&email=' + email + '&text=' + message;
if (error === 0) {
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
success: function () {
$('#details-error').fadeOut(1000);
$('#form-sent').fadeIn(1000);
}
});
return false;
}
});
});
And lastly, the mail.php:
<?php
if ($_POST) {
$name = $_POST['name'];
$email = $_POST['email'];
$text = $_POST['text'];
$option = $_POST['option'];
$headers = $option . "\r\n" . $name . "\r\n" . $email;
//send email
mail("xxx#email.net", "Mail Enquiry", $text, $headers);
}
?>
If the submit button is being pressed more than once then this may work.
Try adding the following line of code right after $('#form-send').click(function(){
$('#form-send').attr('disabled', 'disabled');
This will disable the submit button after it has been clicked once. If the page is reloaded by the user, it will be enabled.
Note: this code has not been tested.
if (error === 0) {
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
success: function () {
$('#details-error').fadeOut(1000);
$('#form-sent').fadeIn(1000);
}
});
This portion of code in #form-send click function is what to do when the submission was successful, you could modify the submit button to disable further clicks if you feel the users are clicking submit after they already submitted the form.
$('#form-send').attr('disabled','disabled'); // only disable the #form-send and not other forms that may need to still be submitted.
You should change the input to a button:
<input id="form-send" type="submit" value="SEND"></input>
to
<button id="form-send" type="button">SEND</button>
Because otherwise the form will be submitted once through ajax and then again via the form submit/page refresh
This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
}
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Looks like you never tell AJAX that the POST name is 'centro', try to change this:
data: $("#form_"+i).serialize(),
for this
data: { 'centro' : $("#form_"+i).serialize()},
I've run into the same problem with my ajax calls that I call via the POST method. My data was actually getting passed in the message body. I had to access it through the following method:
php://input
This is a read only wrapper stream that allows you to read raw data from the message body.
For more information on this wrapper visit this link.
Tray adding the following to your PHP file:
$centro = file_get_contents("php://input");
// Depending on how you pass the data you may also need to json_decode($centro)
echo json_encode($centro);
// See if you get back what you pass in
This read the message body (with my posted data) and I was able to access the value there.
Hope this helps.
try to using this code in your ajax post :
jQuery('#centro_'+i).click( function() {
$.ajax({
data: $("#centro_"+i).closest("form").serialize(),
dataType:"html",
success:function (data, textStatus) {
$('#cuentas').html(data);
alert(data);},
type:"post",
url:"load_cuentas.php"
});
});
Try this:
HTML
<?php
$i=0;
$f=0;
$consulta = $db->consulta("SELECT * FROM centro");
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){ ?>
<form id="form_<?php echo $f++; ?>"> //begin form with its id
<div class="centro" id="centro_<?php echo $i++; ?>">
<?php echo $resultados1['nombre_centro']; ?>
<br>
<input type="hidden" name="centro" value="<?php echo $resultados1['id_centro']; ?>">
<!--this is the data that is going to be sent. I set up a hidden input to do it.-->
</div>
</form>
<div id="cuentas" class="cuentas">
<!--where data is going to be displayed-->
</div>
<br>
<?php
}
}
?>
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('.centro').on('click',function() {
var formElem=jQuery(this).closest('form');
jQuery.ajax({
url: 'load_cuentas.php',
cache: true ,
type:'POST',
dataType: 'json',
data: $(formElem).serialize(),
success: function(output_string){
jQuery(formElem).next('div.cuentas').html(output_string);
alert(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
Server page:
<?php
include ('mysql.php');
$db = new mysql();
$centro = $_POST['centro']; //this is not getting any data. the whole ajax thing
$consulta = $db->consulta("SELECT * FROM cuenta WHERE id_center = '$centro'");
$output_string=array();
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){
$output_string []= 'test text';
}
}
mysql_close();
echo json_encode($output_string);
?>
Hi currently i have an app on Zend php framework, and i heavily using json to fetch data from controller. Now i am not sure whether the way i parse json data into hmtl within javascript are good or not. Below are my sample code.
controller:
public function searchAction()
{
$search = $this->getRequest()->getParam('search');
$user = new Application_Model_User();
$userMapper = new Application_Model_Mapper_UserMapper();
$usersearch = $userMapper->findByString($search);
for($i=0; $i<count($usersearch); $i++)
{
$usersearch[$i]['pic'] = $this->view->getLoginUserImage($usersearch[$i]['social_id'],$usersearch[$i]['login_type'],null,null,square);
}
$this->_helper->json($usersearch);
}
View: member.phtml
<div class="container">
<div class="clearfix page-header">
<h1 class="heading">Member Search</h1>
</div>
<div class="clearfix layout-block layout-a">
<div class="column column-alpha member-search-container">
<div class="search-input-container clearfix">
<form action="/member_search?query=" class="member-search-form" id="member-search-form" method="get" name="member_search_form" data-component-bound="true">
<fieldset>
<legend>Member Search</legend>
<label for="name_field">
<strong> Name</strong>
</label>
<span class="formNote">
(e.g. Bob Smith, Bob S.)
</span><br>
<input type="hidden" name="action_search" value="Search">
<input class="name-field" id="story-title" name="query" size="90" type="text" placeholder="search" autocomplete="off" style="width:220px;">
<div id="search-box"></div>
<div class="auto-name" style="display: none;"></div>
</fieldset>
</form>
</div>
<div class="member-search-results">
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
});
$('#story-title').keyup(function(e){
var searchbox = $(this).val();
if(searchbox == '')
{
$(".similar_story_block").hide();
}else {
$.ajax({
url:"<?= $this->baseUrl('index/search')?>",
data:{'search':$('#story-title').val()},
dataType:"json",
type:"POST",
cache:false,
success:function(data){
if(data.length > 0)
{
var divHtml = '<div class="similar_story_block" style="display: block;">'+
'<div class="head">'+
'<p>People</p>'+
''+
'</div>'+
'<ul>';
for(var count=0; count<data.length;count++)
{
if(data[count]['reviews_num'] != null )
{
data[count]['reviews_num']
}
else
{
data[count]['reviews_num'] = 0
}
divHtml+='<li>'+
'<a class="pushstate no-confirm" href="' + baseUrl + 'user/' + data[count]['user_unique_name'] + '">'+
'<div class="image">'+
'<img alt="" src="'+data[count]['pic']+'">'+
'</div>'+
'<div class="fleft col-400">'+
'<p>'+ data[count]['name'] +'</p>'+
'<span>'+data[count]['reviews_num']+' Reviews</span>'+
'</div>'+
'</a>'+
'</li>';
}
divHtml += '</ul></div>';
$("#search-box").html(divHtml);
$(".search-box").show();
}
else {
$("#search-box").html('');
$(".search-box").hide();
}
}
}) }
});
function closeSearchBox(event)
{
disabledEventPreventDefault(event);
$(".similar_story_block").hide();
}
</script>
Currently the above code will do a live query of members who already signup to the site. The code work very well, but i am not sure if this is right way of doing. Below is how it looks on chrome debug console
it seems i am exposing too much of details. It would be appreciated if anyone can suggest a better way of fetch a data from controller, or how it can be done by using partial template.
Thanks for your help !!!
You can either render your template via PHP and send HTML down the wire, or you can send JSON and render your template using JavaScript.
I would suggest the latter using something like HandlebarsJS.
Define the HTML template:
<script id="member-template" type="text/x-handlebars-template">
<p>Name: {{ name }}</p>
<p>Role: {{ role }}</p>
</script>
Our example JSON data:
var data = {"name": "Bob", "role": "Manager"};
Render our template with our JSON data:
var template = Handlebars.compile($("#member-template").html());
var html = template(data);
The html variable will be your compiled HTML that you can insert witin your <div class="member-search-results"> div.
I think if your project has a lot of visitors and this operation uses often you can relay this function to them. It's could reduce little load on the server. But it could work only if you have very many visitors (pageview). But if your project not so big you can't feel the difference and "PHP way" could be easier on my mind.
i'm trying to send the value of the search textbox via jquery on keydown to the php page so that it can display the results containing the search keyword. however, the php page is not reading $_POST of the input textbox [not button].
html:
.keydown(function() {
//create post data
var postData = {
"bsearch" : $(this).val()
};
//make the call
$.ajax({
type: "POST",
url: "quotes_in.php",
data: postData, //send it along with your call
success: function(response){
$("#bquote").html(response);
}
});
})
. . .
<!-- Begin Search -->
<div id="search" style="display:none;">
<input type="text" class="bsearch" name="search" value="Search" />
</div>
<!-- End Search -->
php:
include_once "inc/class.quotes.inc.php";
$quotes = new Quotes($db);
if (isset($_POST['search']))
//$quotes->searchQuotes();
echo 'Searching. . ';
else
$quotes->displayQuotes();
it seems it is not reading the $_POST['search'] because it does not echo the text 'Searching. .' but instead goes to the else part and displays the quotes.
i tried this code to find out what is happening:
echo "<pre>";
print_r($_POST);
echo "</pre>";
this displays an empty array. what am i doing wrong?
either change postData object key to "search" or check for $_POST['bsearch']
var postData = {
"search" : $(this).val()
};