My ajax code can't send values to other php page [duplicate] - javascript

This question already has answers here:
JavaScript: Inline Script with SRC Attribute?
(3 answers)
Closed 6 years ago.
I tested my update.php file and it works perfect and there is not any error when i checked my script via console . Only problem in here . Ajax can't send values "id" "comment_area" to update.php file . What is the mistake in here ?
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js">
$(document).ready(function() {
$("#b_news").submit(function(evt) {
evt.preventDefault();
var text = $('#breaking_news_text').val();
var id = 21;
$.ajax({
type: "POST",
url: "update.php",
data: {
comment_area: text,
id: id
},
success: function() {
alert("sucess");
}
});
});
});
</script>
<form id="b_news" method="post" action="">
<div>
<div>
<textarea id="breaking_news_text" class="breaking_news_text" rows="6" cols="50" placeholder="Add text here..." required></textarea>
</div>
</div>
<div>
<input type="button" id="save" value="Save Changes" />
</div>
</form>
<?php
include("./inc/connect.inc.php");
$id=$_POST['id'];
$update = $_POST['comment_area'];
$sql = "update comments set comment_area='$update' Where id='$id'";
$result = mysqli_query($mysqli, $sql)or die("error");
?>

Seems to me that your button simply can't submit the form because of its type.
Try to change the type attribute of the button to submit this way :
<input type="submit" id="save" value="Save Changes"/>

You have two problems.
First you can only have one script per script element. The script can either be referenced by the src attribute or it can be between the start and end tags.
If you try to do both, as you are here, then only the src will be respected.
Use separate <script> elements for your two scripts.
Second, you have no way to trigger the submit event. The submit event will trigger when the form is submitted, but you can't do that from a textarea or a button. Replace the button with a submit button.

Related

Ajax won't initiate POST request to php form

For some reason, my form won't post, any ideas as to why(I already know that everything else on my server is operational)? Code below:
PHP
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "<br>";
$ret = file_put_contents('user.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
}
?>
https://pastebin.com/hHeMD4Mq
HTML/AJAX JS
<form id ="form">
<p>Name:</p>
<input name="field1" type="text" id ="name" />
<h3> </h3>
<p>Message:</p>
<textarea name="field2" type="text" id ="message"></textarea><br/>
<button onclick="pos();">reply</button>
</form>
</td>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function pos(){
var values=$("form").serialize();
$.post('form.php', values, function(response) {
console.log("Response: "+response);
});}
</script>
https://pastebin.com/eAVE8EGS
demo on my site:
jakesandbox.com/dnd/
(any info not provided above will be provided upon request in the comments)
The problem is your button is actually submitting the form (Which is essentially reloading the page, as it's submitting to itself). You need to do one of 2 things:
Change your button to a type="button" to prevent it from submitting (A button inside of a form element automatically becomes a submit button):
<button type="button" onclick="pos();">reply</button>
Prevent the click action from taking place (Thus preventing the submit):
<button type="button" onclick="pos(event);">reply</button>
<script type="text/javascript">
function pos(e){
e.preventDefault();
var values=$("form").serialize();
$.post('form.php', values, function(response) {
console.log("Response: "+response);
});}
</script>
-OR-
<button type="button" onclick="pos(); return false;">reply</button>
It turns out your form is actually sent normally with GET request (you can probably see the page reload). It occurs when a button inside a form has no specified type (default being submit).
A button of type "submit" inside a form submits the form while a button of type "button" doesn't.
Just add the attribute type="button" to your button and your problem should be solved.
<button type="button" onclick="pos();">reply</button>
On your php end to debug if the data actually came
<?php
header('Content-Type: application/json');
echo json_encode($_POST);
Then on your js
$.post('form.php', values, function(response) {
console.log(response); // return json
});}

How to make content editable with button

I am trying to make the input type text field editable on click with button but it is not working properly. tried all possible thing any suggestion please
<html><body>
<script>
$(document).ready(function()
{
$('#btnEdit').click(function()
{
$("input[name='name']").removeAttr("readonly");
});
});
</script>
<?php
require_once ('connectdb.php');
$sql = "SELECT * FROM general_information";
$result = $dbhandle->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form>
<input type = "text" name = "name" value = <?php echo $row["email"];?> readonly>
<button class="btn btn-primary" id="btnEdit" > edit </button>
<?php } } ?>
</form>
</body></html>
There are two problems I see in the code,
Button is submitting the form and reloading the page. Use preventDefault() to override form submit.
Use prop instead of removeAttr.
$(document).ready(function(){
$('#btnEdit').click(function(e){
e.preventDefault();
$("input[name='name']").prop("readonly", false);
});
});
UPDATE from #cmorrissey comment.
In textbox, quotes are missing in the value attribute
<input type = "text" name = "name" value = "<?php echo $row["email"];?>" readonly>
Your button is posting the form thus reloading the page so Change your button and give it an onclick event function like onclick="editInputField()":
Edit
Give the input and id:
<input type = "text" id = "name" name = "name" value = <?php echo $row["email"];?> readonly>
Then your javascript function to make the input editable:
<script type="text/javascript">
function editInputField(){
document.getElementById("name").readOnly = false;
}
</script>
EDIT
I noticed you using jquery even though the question is tagged with javascript.
The reason why your code is not working has to do with:
1: The button as mentioned earlier so change it to:
Edit
2: How your targeting the input field, use the field id like this:
$("#fieldID").removeAttr("readonly");
You can use disable or readOnly attributes. Here you have two examples.
<input type="text" id="name" disabled="disabled" value="Example"/>
<input type="text" id="name2" readonly="readonly" value="Example2"/>
<button onclick="myFunction()">Click me</button>
function myFunction() {
document.getElementById("name").disabled = false;
document.getElementById("name2").readOnly = false;
}

Simple ajax post not working

I am an AJAX noob. I was writing code to understand it, but no matter what I couldn't make it work. Textarea in the code should update comment_area of comment of id=218 when user pressed "save" button. There is probably a mistake in my AJAX code which I couldn't find.
My AJAX script:
<script type="text/javascript">
$(document).ready(function() {
$("#save").submit(function() {
var text = $('#breaking_news_text').val();
var id = 218,
$.ajax({
type: "POST",
url: "update.php",
data: {comment_area:text , id:id}
success: function() {
alert("sucess");
}
});
});
});
</script>
<div id="b_news">
<form method="post" action="">
<div>
<div>
<textarea id="breaking_news_text" class="breaking_news_text" rows="6" cols="50" placeholder="Add text here..." required></textarea>
</div>
</div>
<div>
<input type="button" id="save" value="Save Changes"/>
</div>
</form>
</div>
My update.php file
<?php
include("./inc/connect.inc.php");
if(isset($_POST['comment_area']))
{
$update = mysqli_real_escape_string($mysqli, $_POST['comment_area']);
$sql = "update comments set comment_area='$update' Where id='".$_POST['id']."'";
$result = mysqli_query($mysqli, $sql);
}
?>
The submit works on a form and you have it on the input element.
Try:
$("#b_news form").submit(function(evt) {
evt.preventDefault(); //this is required to stop the default form submission
Documentation can be found here
Also, if these dom elements are dynamically loaded, you might want to read up on event delegation

How to submit two forms at a time and store first form submit output value as 2nd form value?

Using the below form 1, i'm generating a goo.gl short url inline in #shortUrlInfo area. I want to use the generated short url in 2nd form to save it in wordpress custom field.
Form 1:
<form method="post" action="">
<input style="display:none;" type='text' id='longUrl' value='<?php echo get_post_meta( get_the_ID(), 'longurl', true ); ?>' />
<input name="shorturlinput" type="button" id="shortIt" value="Short It" /></form>
<div class="info" id="shortUrlInfo"></div>
Form 2:
<?php
global $post;
if( isset($_POST['submit_meta']) ) {
if( ! empty($_POST['change_meta']) ) {
update_post_meta($post->ID, 'shorturl', $_POST['change_meta']);
}}
?>
<form method="post" action="">
<input type="text" name="change_meta" value="" />
<input type="submit" name="submit_meta" value="Submit" />
</form>
How can i submit the first form and pass the generated short url to 2nd form and submit that short url value in custom field with one click?
Or atleast, how can we display the generated short url in 2nd form input, which if we click on submit button, it should save in database.
It's my first question here & I've tried my best to find answer before posting here with no luck.
Well its all ajax . you need to post your data with ajax function to the controller which save the shortened url in data base , how ? like this :
give your second form + the first input of your second form 2 ids
$("#shortIt").click(function(){
var longUrl = $('#longUrl').val()
$.post("ur_url.php",
{
"longUrl": longUrl // here the url will be sent to your server and server communicates
// with goo.gl url shorter by its api and respond you with a variable called data
},
function(data, status){ // your server send here the shorturl and this function calls it
//also this function will be run after the server respond is completed
$('#inputID').val(data) // data will be set inside the input value
document.getElementById("#SecondForm").submit(); // your second form submits and your
// server needs to get the data and save it in your data base
});
});
all will be done with a single click .
also you can do many things when the process is going on . but i hope i gave you some clue :P
Try this in HTML:
<form (return to script)>
<input 1>
</form>
<input 2>
Then in script:
get input 1 and input 2
Next example code shows how to achieve what I believe you want (with one click!). Explanation first: one form (file #1) sends a text to a script (file #2), this script redirects to another form (file #3), this form gets the original text and automatically resend it to another script (file #4) that inserts it in database, next image explains it better:
As you can see, the text in the first form becomes a value for the second form.
Now the code. In order to test next code, you will have to create four text files and give them the given names (if you change the filenames, you will have to change the "action" property in the forms), copy-paste my code in your files, then, open you browser and run only the first file like this) :
http://localhost/form_sequence_1.php
These are the files:
form_sequence_1.php
<html>
<body>
FORM 1
<br/>
<form method="post" action="form_sequence_2.php">
Enter a text
<input type="text" name="my_text" />
<br/>
<input type="submit" value="Send text" />
</form>
</body>
</html>
form_sequence_2.php
<?php
session_start();
$_SESSION[ "my_text" ] = $_POST[ "my_text" ];
header( "Location: form_sequence_3.php" );
?>
form_sequence_3.php
<?php
session_start();
?>
<html>
<head>
<script type="text/javascript">
function autosendform () {
setTimeout( "sendform()","3000" );
}
function sendform () {
document.getElementById( "my_form" ).submit();
}
</script>
</head>
<body onload="autosendform();">
FORM 2
<br/>
<form method="post" action="form_sequence_4.php" id="my_form">
Text entered in previous form
<input type="text" name="my_text" value="<?php echo $_SESSION[ "my_text" ]; ?>"/>
<br/>
<input type="submit" value="AUTOSENDING FORM IN 3 SECONDS" />
</form>
</body>
</html>
form_sequence_4.php
<?php
session_start();
echo $_SESSION[ "my_text" ] . " succesfully inserted into database.";
?>
More explanations:
Value in form 1 sends the text to form 2.
In the middle of form 1 and form 2 we need a script to capture the value.
Form 2 automatically resends the value thanks to a timer in JavaScript.
The last script gets the value and insert it in database (not for real).
The advantage of this approach is that the scripts allow you to do many things with the value or values, like validating or conversion.
Next is your code with my JavaScript timer code adapted :
<?php
global $post;
if ( isset($_POST['submit_meta']) )
if ( ! empty($_POST['change_meta']) )
update_post_meta( $post->ID, 'shorturl',$_POST['change_meta'] );
?>
<html>
<head>
<script type="text/javascript">
function autosendform () {
setTimeout( "sendform()","3000" );
}
function sendform () {
document.getElementById( "my_form" ).submit();
}
</script>
</head>
<body onload="autosendform();">
<form method="post" action="" id="my_form">
<input type="text" name="change_meta" value="" />
<input type="submit" name="submit_meta" value="Submit" />
</form>
</body>
</html>

Convert a DIV to textarea with specific "name" attribute

I have a small admin panel that I have created to do simple database tasks for my DayZ server. Now I want to make a simple editor for the news blurb on my website. The news blurb is stored in a table on my database. What I want is when the page loads it simply echo's the data and looks like it does on the live site. Then, when I click on it, I want it to convert into:
<textarea name="edit><?php echo news; ?></textarea>
This is my current code:
function divClicked() {
var divHtml = $(this).html();
var editableText = $("<textarea name="edit" />");
editableText.val(divHtml);
$(this).replaceWith(editableText);
editableText.focus();
// setup the blur event for this new textarea
editableText.blur(editableTextBlurred);
}
$(document).ready(function() {
$("#editable").click(divClicked);
});
<form method="post" action="newsedit.php">
<div id="editable"><?php echo $news; ?></div>
<input type="submit" value="Edit News" />
</form>
Now, this does work in the sense that when I click on the text it does convert into a textarea. The problem is that it doesn't give it the "edit" name so when I hit the sumbit button, it is as if I submitted nothing and it deletes all the data out of the table because
<textarea name="edit"></textarea>
is technically empty. Are there any ways to make it so when I click on the text it will convert the code to textarea with that specific name so there is actual data when I hit submit?
Change the form to:
<form method="post" action="newsedit.php">
<div id="<?php echo $newsID;?>"><?php echo nl2br($news); ?></div>
<input type="submit" value="Edit News" />
</form>
Where $newsID is returned along with the $news text.
The nl2br($news) will just make sure the line breaks are honored.
var editableText = $("<textarea name='edit' />");
http://jsfiddle.net/H5aM4/ inspect the textarea
TRY This
$("#editable").click( function(){
$(this).replaceWith(function() {
return $("<textarea name='edit'>").text(this.innerHTML);
});
});
Here is the working example

Categories