I made a comment column by putting process.php in the page header, but when I want to load a #comment-list, 1 page entered into the div.
I've tried changing ajax.url and it works, but it will affect the entire system that was created.
I want to load this part when ajax is successful
HTML
<div id="comment-list" class="widget-body">
<?php news_comment($server_conn,$id_news); ?>
</div>
FORM
<form action="<?php echo FullURL() ?>" method="post" id="newcomment">
<div class="form-group">
<label for="comment">* Comment:</label>
<textarea class="form-control" rows="3" name="text_comment" placeholder="Your Comment" required></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submit-comment" name="submit-comment" value="<?php echo $row['id_news']; ?>">Post Comment</button>
</form>
AJAX
$("#submit-comment").click(function(event){
event.preventDefault();
var submit = $(this).attr('value');
var post_url = $("#newcomment").attr("action");
var request_method = $("#newcomment").attr("method");
var form_data = $("#newcomment").serialize();
$.ajax({
url : post_url,
type: request_method,
data : form_data + '&submit-comment=' + submit,
success: function(){
$("#newcomment")[0].reset();
$("#comment-list").load(post_url + "#comment-list");
}
})
});
When Ajax responds successfully, I want #comment-list loads automatically, without entering a 1-page display
Related
I have a page with a form that contains many fields and an image:
<form method="POST" action="http://project.dev/model/useradd" accept-charset="UTF-8" autocomplete="off" id="AddModel" enctype="multipart/form-data">
<input name="_token" type="hidden" value="yeq4iLVIyXiYyMbORaY5fA6zxIYDFWNJTqNVYiP9">
<div class="form-group">
<label for="material">Material</label>
<input type="text" class="form-control" name="material" maxlength="30" style="width:30ch">
</div>
<div class="form-group">
<label for="color">Color</label>
<input type="text" class="form-control" name="color" maxlength="10" style="width:20ch">
</div>
<div class="form-group">
<label for="description">Description</label>
<input type="text" class="form-control" name="description" maxlength="500">
</div>
<div class="form-group">
<label for="image">Picture</label>
<input id="modelpic" name="image" type="file">
<br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show the preview of the image through javascript */
<div class="form-group">
<input id="AddBtn" class="btn btn-default" type="submit" value="Submit">
</form>
here is the javascript that shows the image preview in the form after selection:
$(document).ready(function() {
$('#modelpic').on("change", function () {
//shows image preview in DOM
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support
if (/^image/.test( files[0].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(this.files[0]); // read the local file
reader.onloadend = function(){ // show image in div
$('#imagePreview').show().html('<img id="theImage" src="' +this.result+ '" class="img-fluid" alt="Your Image" />');
}
}
})
});
What I need to do is show a preview of the post as it will appear before confirming submission.
How can I do it with jquery? My guess is I also have to modify the action part of the form code action="http://project.dev/model/useradd" in the html to something like self or something? Is it correct?
How do I get the submitted form data along the picture after hitting submit in jquery and use that to output the html to a preview div?
--- I also thinked to send the data to the server, save the image temporarily in public then load it in the preview. The problem is that if I use ajax to intercept the submission the image is not submitted. I think it's a problem of specyfing the data. My JS script code is like this:
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "#AddModel", function (e) {
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (textStatus) {
{
var json = JSON.parse(textStatus.responseText);
console.log (json);
}
}
});
e.preventDefault();
});
});
});
I think this is wrong probably in the datatype or something.
I'm working on a footer generator.
Which looks like this:
This "preview" button has 2 functions function 1 is posting the values that the user entered in the black box like this :
and the second function is to show me a button(which is hidden by default with css) called "button-form-control-generate" with jquery like this:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Now here comes my problem:
If i click on preview it refreshes the page.. so if i click on preview it shows the hidden button for like 1 second then it refreshes the page and the button goes back to hidden. So i tried removing the type="submit" but if i do that it wont post the entered data like it did in image 2 it will show the hidden button though, but because the submit type is gone it wont post the entered data on the black box.
Here is my code:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate"name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
The jquery:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Already tried prevent default but if i do this the users entered data doesnt show in the preview box. Looks like preventdefault stops this bit from working:
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
I heard this is possible with ajax, but i have no idea how in this case i already tried to look on the internet..
if you have a type="submit" inside a form, it will submit the form by default. Try to use <input type="button" instead. Then you can use ajax on the button action, that will run without refreshing the page.
Here's an example of how to use ajax:
function sendAjax() {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
$(".result").html(JSON.stringify(data))
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="button" onclick="sendAjax()" value="callAjax" />
<div class="result"></div>
</form>
Add
return false;
to your jQuery-function at the end. With this you can avoid the submit.
Then you need to add an ajax-function, which sends the data from your form to the php-script you already use.
This is just an example:
$.ajax({
url: "YOUR-PHP-SCRIPT"
}).done(function (content) {
// ADD HERE YOUR LOGIC FOR THE RESPONSE
}).fail(function (jqXHR, textStatus) {
alert('failed: ' + textStatus);
});
So you have to do $.ajax post request to the php. Something like this:
<script>
$('.form-control').click(function() {
$.post(url, {data}, function(result) {
footerPreview();
}, 'json');
});
</script>
So footerPreview will be called when your php returns result.
//add in javascript
function isPostBack()
{
return document.referrer.indexOf(document.location.href) > -1;
}
if (isPostBack()){
$("button.form-control-generate").show();
}
you can create an index.php:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" id="tm">
<option val=""></option>
<option val="©">©</option>
<option val="™">™</option>
<option val="®">®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" id="cn" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate" name= "submit" id="generate">
Generate
</button>
</form>
<div class="output" id="output">
</div>
<script type="text/javascript">
$('#generate').on('click', function(e){
e.preventDefault();
var companyname = $('#cn').val();
var trademark = $('#tm').val();
$.ajax({
url: 'process.php',
type: 'post'.
data: {'company':companyname,'trademark':trademark},
dataType: 'JSON',
success: function(data){
$('#output').append("<div id='footer_date'>"+data.trademark + " " + data.date + " " + data.company + " </div>");
},
error: function(){
alert('Error During AJAX');
}
});
})
</script>
and the process.php:
<?php
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["company"];
$date = date("Y");
$array = array(
'trademark' => $trademark,
'company' => $company,
'date' => $date
);
echo json_encode($array);
?>
Be sure that the index.php and the process.php will be under the same folder.. ex.public_html/index.php and public_html/process.php
This is my registration form located in login.html:
<form action="Registar.php" method="post">
<input type="text" name="user" placeholder="Username (Sem espaços)" maxlength="25">
<input type="text" placeholder="Email" name="email" maxlength="31"/>
<input type="text" name="nome" placeholder="Nome" maxlength="31"/>
<input type="text" name="morada" placeholder="Morada" maxlength="120"/>
<input type="hidden" name="action" value="login">
<input type="number" name="telefone" placeholder="Telefone" maxlength="15"/>
<button type="submit" class="btn btn-default" name="submit">Signup</button>
</form>
It goes to "Registar.php" and runs the verification's i want like if the fields are empty or if the username already exists and show's that verification's in a jquery dialog.
Heres my Jquery script:
function alerta(msg,link){
var dialog = $('<div>'+msg+'</div>');
$(function() {
$( dialog ).dialog({
modal: true,
buttons: {
Ok: function() {
window.location = link;
}
}
});
})
};
The thing is it shows the dialog on the blank page of "Registar.php" and since i scripted some nice styles and overlays for my jquery dialog i want to show the jquery dialog verification messages in login.html and have that page in the background/overlay of the dialog.
Is there any way to do that but still running the action form to an external php script?
Thanks in advance!
One way to achieve this would be to use AJAX instead of sending the form via POST. Here's an example:
HTML
<form id="myForm" action="" method="post">
//your form content
</form>
JQuery
$('#myForm').on('submit', function(e) {
e.preventDefault(); //stop form submission
var formData = $(this).serialize();
$.ajax({
type: "POST",
url: "Registar.php",
data: formData,
success: function(result) {
//result is the value returned from Registrar.php
console.log(result);
//show the modal
}
});
});
JSFiddle
I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>
Im facing a really strange problem here. I use bootstrap for some of my tooltips alerts etc. Now I have a ajax form that responds error messages in a alert if something is wrong. This all works fine but when i click the "close" button of the alert box the alert dissapears but then the form submit button does not work anymore? I dont know why it's behaviour is like this can someone help me out?
Also, when i do not close the alert, then when I enter new data and click on submit it does submit. Only after closing alert form does not submit anymore
Form (with error div)
<!-- ERROR BOX -->
<div id="regError" class="alert alert-error" style="margin-right: 20px; display: none;"></div>
<!-- ERROR BOX -->
<form id="registerform" action="ajax/register.php" method="post">
<fieldset> <span class="help-block"><B>Jou gegevens</B></span>
<input name="username" class="span4" type="text" value="Gebruikersnaam" onblur="onBlur(this)" onfocus="onFocus(this)" placeholder="Gebruikersnaam">
<input name="email" class="span4" type="text" value="Email adres" onblur="onBlur(this)" onfocus="onFocus(this)" placeholder="Email adres">
<input class="span4" type="text" value="Email adres (opnieuw)" onblur="onBlur(this)" onfocus="onFocus(this)" placeholder="Email adres (opnieuw)">
<input class="span4" type="text" value="Wachtwoord" onblur="onBlur(this)" onfocus="onFocus(this)" placeholder="wachtwoord">
</fieldset>
<button type="submit" class="btn btn-primary" >Save changes</button>
<button type="button" class="btn">Cancel</button>
javascript ajax call
$(document).ready(function () {
$("#registerform").submit(function () {
//Get al form data This = form and EL is element of the form
var el = $(this),
// get form action and method attribute
url = el.attr('action'),
type = el.attr('method'),
// emty data array to fill with form data
data = {}
// The loop to get al form data
el.find('[name]').each(function (index, value) {
var el = $(this)
name = el.attr('name'),
value = el.val();
//make data object
data[name] = value;
});
//Do the ajax call
$.ajax({
type: type,
url: url,
data: data,
success: function (response) {
$('#regError').html(response);
$('#regError').fadeIn();
}
})
return false;
})
})
the PHP is just to test if it works..
<?php
if (isset($_POST)) {
echo '<button type="button" class="close" data-dismiss="alert">×</button>';
print_r($_POST);
}
Well because i could not find a solution i just removed the close button.