So I have this problem.
I have the following form on my webpage:
<form>
<textarea rows="3" id="pasteText"> </textarea>
<button class="btn btn-success btn-block" type="submit" id="paster" onclick="captureText();">Paste!</button>
And I have a JavaScript method to capture the text in the textarea here:
function captureText() {
var value = $("#pasteText").val();
//var sent = "../../lib/_add.php?data="+value;
$.post('../../lib/_add.php', {data: value});
}
I'm trying to send the value inside the textarea to the data in PHP (the add.php adds the data variable to my database). What's the best way to go about it? Everything I've tried so far hasn't worked.
Thanks!
You don't need jQuery $.post to submit the form. A simple HTML form would do.
<form action="../../lib/_add.php" method="post">
<textarea rows="3" name="data" id="pasteText"></textarea>
<input class="btn btn-success btn-block" id="paster" type="submit" value="Paste!" />
</form>
You are using input type "Submit". So you have to return false from your function if you want to continue uisng ajax to submit form. In this case your javascript would look like:
function captureText() {
var value = $("#pasteText").val();
//var sent = "../../lib/_add.php?data="+value;
$.post('../../lib/_add.php', {data: value});
return fasle;
}
Otherwise a simple form works fine.
Enjoy!.
function captureText() {
var value = $("#pasteText").val();
//var sent = "../../lib/_add.php?data="+value;
$.post('../../lib/_add.php', {data: value})
.done(function(data) {
alert("Data Loaded: " + data);
// add some result confirmation code from php
});
alert("data received");
}
check jquery path and php file path
Related
I have this piece of code.
It's a input for a newsletter.
<form id="newsletter-form" name="newsletter-form" method="post" action="/newsletter">
<div class="form-group">
<label for="exampleInputEmail1"><span>Cadastre-se em nossa newsletter</span></label>
<input type="email" class="form-control" id="newsletter-email" name="newsletter-email" placeholder="e-mail" value="">
</div>
<button class="btn btn-secondary btn-block" type="button"><i class="fas fa-paper-plane fa-fw mr-1"></i>Cadastrar</button>
</form>
Quite simple!
And I have this JS:
$(function()
{
var form = $('#newsletter-form');
// ----------
$(form).submit(function(form_response)
{
form_response.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response)
{
$('#newsletter-email').removeClass('is-invalid');
$('#newsletter-email').addClass('is-valid');
$('#newsletter-email').val(response);
})
.fail(function(data)
{
$('#newsletter-email').removeClass('is-valid');
$('#newsletter-email').addClass('is-invalid');
if (data.responseText !== '')
{
$('#newsletter-email').val(data.responseText);
}
else
{
$('#newsletter-email').val('Ocorreu um erro!');
}
});
});
});
My PHP check if email is valid, if already is inserted, etc, etc.
The PHP returns codes and echos correctly(I use it on other parts of my website)
The thing is:this form is not even triggering the JS to run the PHP.
It should run the PHP and add a is-valid or is-invalid class on the inpute and show the feedback as value or placeholder.
Any ideas why it's not working?
Just to add it as answer your button type was button not submit so eaither use input type submit or change button type to submit :D
This is your original code. var form = $('#newsletter-form');
Since you have put the form tag into a variable, you don't need to use $. Change $(form) into form. The code will look like this.
form.submit( /* some code */ );
or if you don't want to store it into variable, you can directly call the function from jquery.
$('#newsletter-form').submit( /* some code */ );
I am trying to post data through my website via ajax, however for some reason it seems to echo the success message but does not get the mobile field data. it's just blank. When i inspect with firebug, it gives the response, but the POST tab is empty.
My controller contains the following :
function submit()
{
//set validation rule
// get post data
$emailid = $this->input->post('mobile');
// write your database insert code here
echo "<div class='alert'>Thanks for Subscribing! Please stay tuned to get awesome tips...</div> here is $emailid";
}
And my view contains :
<label>Mobile</label>
<input type="number" name="mobile" id="mobile" class=" form-control" />
<button type ="submit" id="submit" name="submit" class="btn btn-info btn-block" /> NEXT </button>
The JS
<script type="text/javascript">
$("#submit").click(function(e) {
e.preventDefault();
var mobile = $("mobile").val();
$.ajax({
url: "https://cheddarplatform.com/complete/submit",
method: "POST",
data: {mobile: mobile},
success: function(data) {
$("#message").html(data);
},
error: function() {
alert("Please enter valid email id!");
}
});
});
</script>
$("mobile") is not a proper selector, as you do not have a HTML element of that type anywhere. Probably you want to use $("#mobile") and have a look at your browser's network tab to find this error easier the next time
I have my first PHP page having search form:
<form action="#" class="form-inline" id="form_srch">
<input type="text" id="toSearch" name="toSearch" placeholder="Enter Application Number" class="form-control" style="width:250px" required >
<button type="button" class="btn btn-primary" onclick="search()">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>
</button>
<i><b><p style="display:none;color:red" id="result">** Empty Value</p></b></i>
</form>
<div id="ajax"></div>
and a javascript function
<script>
function liveCheck() {
$("#result").show();
}
function search() {
var inp = $("#toSearch").val();
if(jQuery.trim(inp).length > 0)
{
jQuery.ajax({
url: "load_search_prereg.php",
data:{ to : inp },
type: "POST",
success:function(data){
$("#ajax").load('load_search_prereg.php');
//alert(data);
},
error:function (){}
});
}
else{
liveCheck();
}
}
</script>
And i have my second PHP page named load_search_prereg.php to process the POSTed input and the code is
<?php
require '../backend/_classes.php';
$x = new DB();
$id = $_POST['to'];
$sql=$x->select(1,'*','tblregistration','app_number',"'$id'");
$fetch = $sql->fetchObject();
var_dump($fetch);
The problem is when i clicked the search button in my first PHP page, It displays no array of posted data while im using the $("#ajax").load('load_search_prereg.php'); method in my javascript. But when i use alert(data);, it returns the expected result. Does the problem occur in $("#ajax").load('load_search_prereg.php'); method ? Help pls.
Not:
$("#ajax").load('load_search_prereg.php');
But:
$("#ajax").html(data);
I've assumed you just want to write this data into div
edit:
instead of var_dump($fetch); you must return your data a JSON object, eg:
$fetch = $sql->fetchObject();
echo json_encode($fetch);
Then you can do in js what you want
It should be method:"POST" instead of type: "POST".
By default method is set to GET.
Because of my web style, i don't want to use input & textarea and get information by using $_POST[] and i need to get information that is in DIV element.
For example , I want to get information in this :
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
and :
$_POST[myname];
But i can't do it with $_POST , How can i do it ??
And if this method can't do this , do you know any other method to get information from DIV like this ?
you can call a onsubmit function and make a hidden field at the time of form submission like this
HTML
need to give a id to your form id="my_form"
<form action="submit.php" method="post" id="my_form">
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="submit" value="submit" name="submit" />
</form>
Jquery call on submit the form
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.mine').text();
$(this).append("<input type='hidden' name='myname' value=' " + hvalue + " '/>");
});
});
PHP : submit.php
echo $_POST['myname'];
You can use this method. First, with javascript get content of <div>
Code:
<script type="text/javascript">
var MyDiv1 = Document.getElementById('DIV1');
</script>
<body>
<div id="DIV1">
//Some content goes here.
</div>
</body>
And with ajax send this var to page with get or post method.
You would need some JavaScript to make that work, e.g. using jQuery:
$.post('http://example.org/script.php', {
myname: $('.mine').text()
});
It submits text found inside your <div> to a script of your choosing.
You can use following structure;
JS:
$(document).ready(function() {
$("#send").on("click", function() {
$.ajax({
url: "your_url",
method: "POST",
data: "myname=" + $(".mine").text(),
success: function(response) {
//handle response
}
})
})
})
HTML:
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="button" name="send" id="send" value="Send"/>
You can see a simulation here: http://jsfiddle.net/cubuzoa/2scaJ/
Do this in jquery
$('.mine').text();
and post data using ajax.
Put the content of DIV in a variable like below:
var x = document.getElementById('idname').innerHTML;
I am trying to use jQuery-AJAX to submit the data in my form to my controller (index.php) where it is processed by PHP and inserted via PDO into the database if valid. Once the code is inserted into the database, the div where the form previously existed should be replaced by the contents of another page (newpage.php). The original page should not be refreshed upon submitting of the form, only the div where the form previously existed should be refreshed. There is a particular problem with my code, although I can't seem to find where the issue is at:
Here is my jQuery:
<script type="text/javascript">
function processForm() {
var action= $('#action').val();
var data = $('#data').val();
var dataString = 'action=' + action + '&data=' + data;
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
}
</script>
Here is my HTML: (As a side note, I noticed that when I take the "return false;" out of the HTML, that the form will submit to my database, but the whole page also reloads - and is blank. When I leave the "return false;" in the HTML, the newpage.php loads correctly into the div, but the data does not make it into the database)
<form action="" method="post" onsubmit="processForm();return false;">
<input type="hidden" name="action" value="action1" />
<input type="text" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Here is my PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
I feel like I am making a silly mistake somewhere, but I just can't put my finger on it. Thanks for any assistance you can provide!
SOLUTION (via Jen):
jQuery:
<script type="text/javascript">
function processForm() {
var dataString = $("#yourForm").serialize();
$.ajax ({
type: 'POST',
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
</script>
HTML:
<form id="yourForm">
<input type="hidden" name="action" value="action1" />
<input type="text" id="data" name="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
What I learned: Use the .serialize() jQuery method if it is an option, as it will save a bunch of time writing out the var for each form value and .serialize() does not typically make mistakes sending the info to php.
Give this a try:
$("#yourForm").submit(function(){
// Could use just this line and not vars below
//dataString = $("#yourForm").serialize();
// vars are being set by selecting inputs by id but id not set in form fields
var action= $('#action').val(); // value of id='action'
var data = $('#data').val(); // value of id='data'
var dataString = 'action=' + action + '&data=' + data;
// dataString = 'action=&data=' so nothing is posted to db
// because input fields cannot be found by id
// fix by adding id fields to form fields
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
And change the form to (I added the id attributes):
<form id="yourForm">
<input type="hidden" id="action" name="action" value="action1" />
<input type="text" id="data" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Seems like you need an explanation rather than a fix of code. Here is a brief explanation for the 2 cases:
When you take out return false; the code will treat your form as a normal HTML form that will be submitted to the server via action="", which leads to nowhere. The Javascript, however, also does its job in this case but because the page is redirected to nowhere, then it turns blank at the end.
When you put return false; back to the form, the form will catch the event handler and know that this form will be returned FALSE to submit. That's why you can see how your Javascript code does the job. However, one thing you should notice is that your jQuery AJAX function needs to POST (or GET) to a processing file, not '.'
Considering this reply based on no knowledge of your real situation. You need to look back over your code and see how you can edit it. Would be happy to reply if you have any questions.
Hope this small hint helps (: