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
Related
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.
Am trying to submit stuff typed in tinyMCE using a Jquery function but am not certain how to do that and how the server side form-processor should accept the data.
This is what I have so far.
Anyone see something that am missing here? I know am close. am just missing something.
Thanks in advance.
==THE HTML==
<form onsubmit="save_tinyMCE_Stuff();" method="post" action="form_processor.php?action=save" >
<textarea class="classname" id="tme0" name="elm1" rows="25" cols="80" style="width: 100%" >Product Details Will appear Here. This information will be compiled by purchasing Department<br/>
Some Text here
</textarea><br /><input type="submit" name="save" value="Save" /><input type="reset" name="reset" value="Undo All" />
</form>
==THE SCRIPT IN HTML FILE==
save_tinyMCE_Stuff(){
$dataString = tinymce.get('tme0').getContent();
$zeurl = 'form_processor.php?action=save&data=' + $dataString;
$.ajax({type: "POST",url: $zeurl,data: $dataString,cache: false,success: function(result){alert(result);}});
}
==THE PHP==
form_processor.php
<?php
if($_GET['action'] == 'save'){
echo $_POST['WHAT NAME TO USE HERE'];
}
?>
You don't need to tinymce. Just submit textarea value.
like this:
function save_tinyMCE_Stuff() {
$dataString = $('textarea').val();
$zeurl = 'form_processor.php?action=save&data=' + $dataString;
$.ajax({
type: "POST",
url: $zeurl,
data: $dataString,
cache: false,
success: function(result) {
alert(result);
}
});
}
If a form gets submitted, it will become available as the name attribute the element has. So for your tinyMCE stuff, it would be $_POST['elm1'];
Because the name of your textarea is elm1.
Getting all textarea's with jquery example: Fiddle
In my page there are several DIVs, which are supposed to show different news items depending on the user selection and a press of a submit button.
Am I able to refresh only a single DIV when the relevant submit button is clicked?
I tried <input type ="button"> instead of <input type="submit"> but that didn't work as expected. My code is below:
<div class="dloader"></div>
<div class="search">
<form action="" method="post">
Furniture:
<input type="text" name="val1" id="val1" value="<?=$_POST['val1']?>" />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
<?php
if( isset($_POST['submit']) ){
$postItemHeader = htmlentities($_POST['val1']);
}?>
<script>
$(window).load(function() {
$(".dloader").fadeOut("slow");
})
</script>
Take One Button For Post Event
<input type="submit" id="add" name="add" />
If You want to pass the Text Data, so a text value from the Text to fetch the particular data
<div id="result">Result should appear here</div>
Use Javascript To POst The Text Data To Back End
$(document.ready(function() {
$("#add").click(function(e) {
e.preventDefault();
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#add').val,
success: function(data, status) {
$("#result").html(data)
}
});
});
});
What you need is AJAX. (read the documentation). A simple example is here.
The HTML
<div id="target_div"></div> <!-- Here is where you gonna place your new content -->
<input type='button' id='trigger' onClick="get_new_data()" value="Get new Content"> <!-- When this button is pressed get new content -->
The Javascript
function get_new_data()
{
$.ajax(
{
type: POST,
url: "you-url-here.php",
dataType:"HTML", // May be HTML or JSON as your wish
success: function(data)
{
$('div#target_div').html(data) // The server's response is now placed inside your target div
},
error: function()
{
alert("Failed to get data.");
}
}); // Ajax close
return false; // So the button click does not refresh the page
} // Function end
When a user search items in <div class="searchBar"> I want to POST the data to <div id="auto"> and get only <div id="auto"> refreshed rather than reloading the full page.
My problem is that when the Submit button is clicked, the entire page is loading. I need to be able to refresh only <div id="auto"> when the submit button is clicked. The main purpose is that I want to avoid <div class="menuList"> being reloaded every time Submit is clicked. Below is my code.
<div class="searchBar">
<form action="" method="post">
Furniture item:
<input type="text" name="val1" id="val1" value="<?=$_POST['val1']?>" />
<input type="submit" id="submit" value="Submit" name="submit" />
</form>
</div>
<div class="menuList">
List of Furniture:
<select id='myList' name="mList" onchange='document.getElementById("val1").value = this.value;'><option value="">Furniture Available</option>
</select>
</div>
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function() {
refresh();
});
function refresh(){
$("#submit").click(function(e) {
e.preventDefault();
$.ajax({
url: 'php/filep.php',
type: 'POST',
data: $('#submit').val,
success: function(data, status) {
$("#result").html(data)
}
});
$(".result").fadeOut("slow");
refresh();
});
}
</script>
</body>
filep.php
if( isset($_POST['submit']) ){
$resData = htmlentities('img/'.$_POST['val1']).'/';
}
if( isset($resData) ) {
$files = '*.*';
$fin = glob($resData.$files);
$counts = count($fin);
$imgs = array();
$div= '';
foreach ($imgs as $fin) {
$div .= '<div class="imgSlots">';
$div .= '<li><div class="imgSlotsInner"><input type="image" src="'.$fin.'"/><testDes>"'.basename($fin.$files).'"</testDes></div></li>';
$div .= '</div>';
}
echo $div;
}
yes you can refresh the single div only. what exactly you need to do is refresh the html of that div i.e. first delete the html of that div like
$('#auto').html('');
and then put you content again what you have fetched from the Ajax posting in that Div. like if you are going to refresh a Grid or table just write the inline HTML and fill all the data coming from ajaxpost. You may use .each method to make it in loop
Thanks
I have a form, and it has a field for entering a PIN code. Here I am using ajax for finding place when enter PIN code. It works when that field is not enclose in a form. If it is enclosed in a form, AJAX is not working.
HTML CODE:
<form id="form" class="blocks" action="#" method="post" enctype="multipart/form-data">
<div class="col_4 right">
<label for="fullname">FirstName:</label>
<input name="fname" type="text" class="text" />
</div>
<div class="col_4 right">
<label for="pincode">Pin-Code:</label>
<input name="pincode" type="text" class="text" id="pincode" />
<div id="section1"></div>
</div>
</form>
JS CODE:
<script>
$(document).ready(function() {
$('#pincode').keyup(function (e) {
if (e.keyCode == 13) {
//ajax request
$.ajax({
url: "pincode_check.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) { <!--console.log(data.success);-->
if(data.success){
//console.log(data.results[0].formatted_address.split(','))
var long_address=data.results[0].formatted_address.split(',');
console.log(long_address[0]);
$('#section1').append(long_address[0]);
}
}
});
}
});
});
</script>
PHP CODE(pincode_check.php):
<?php
$pincode=$_REQUEST['pincode'];
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$pincode.'&sensor=false');
$response= json_decode($geocode); //Store values in variable
$lat = $response->results[0]->geometry->location->lat; //Returns Latitude
$long = $response->results[0]->geometry->location->lng; // Returns Longitude
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$long.'&sensor=false');
$data= json_decode($geocode);
if($data==true)
{ // Check if address is available or not
$data->results[0]->formatted_address ;
$data->success=true;
echo json_encode($data);
}
else {
$data->success= false;
echo json_encode($data);
}
?>
The default content type in $.ajax is application/x-www-form-urlencoded. But you've set your form content to multipart/form-data.
multipart/form-data is normally used for sending files with POST. I don't think you need that, so you don't need to specify enctype at all, just remove it and use the default form encoding, which is application/x-www-form-urlencoded.
(Additionally, the default request type in $.ajax is GET, so if you do want to send a file, you'll need to change that too..as well as add the attribute type="file" to your form I believe...)