I create a form with PHP and jQuery, I add this in footer of my website, all I need is to display the form results in a popup in the main of my website not in the footer and make this to work without page refresh (with ajax). I add here my entire code:
<form enctype="multipart/form-data" action="" method="post">
<input name="url" type="text"/>
<input type="submit" name="submit" value="Check" class="btn btn-primary"/><br/>
</form>
<?php
if(isset($_REQUEST['submit'])) {
$url = $_REQUEST['url'];
if(substr( $string_n, 0, 7 ) != "http://" && substr( $string_n, 0, 8 ) != "https://")
$url = "http://".$url;
if(stripos($url,"folder/")>0)
$content = file_get_contents($url);
else
$content = file_get_contents($url."/folder/");
if(preg_match("/Copyright ver\. ([0-9.]+)/", $content, $result))
echo "Your year is : ".$result[1];
else
echo "Sorry cannot determine year";
}
?>
EDIT
dont forget to put jquery in top of the html page
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
Check below solution
//this will be your html file
<form id="form1" enctype="multipart/form-data" action="" method="post">
<input name="url" type="text"/>
<input type="submit" name="submit" value="Check" class="btn btn-primary"/><br/>
</form>
<script>
$(function() {
$('#form1').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function(html) {
alert(html);
}
});
});
});
</script>
create a post.php file put your php code
<?php
if (isset($_REQUEST['submit']))
{
$url = $_REQUEST['url'];
if (substr($string_n, 0, 7) != "http://" && substr($string_n, 0, 8) != "https://")
$url = "http://" . $url;
if (stripos($url, "folder/") > 0)
$content = file_get_contents($url);
else
$content = file_get_contents($url . "/folder/");
if (preg_match("/Copyright ver\. ([0-9.]+)/", $content, $result))
echo "Your year is : " . $result[1];
else
echo "Sorry cannot determine year";
}
?>
If you are only using the code provided, you are still missing some AJAX code. As you have used both the jQuery and JavaScript tags, I wasn't sure if you are using Vanilla or jQuery (my example uses jQuery).
My example will make an AJAX request when the user clicks the submit button. $your_url will need to be set to a file which contains your PHP code you specified in the question.
$('#my_button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
text: $('#some_text').val(),
},
url: "<?php echo $your_url; ?>",
success: function(data) {
console.log($data);
}
});
});
<form enctype="multipart/form-data" action="" method="post">
<input name="url" type="text" / id="some_text">
<input type="submit" name="submit" value="Check" class="btn btn-primary" id="my_button" />
</form>
Your PHP will need to be changed so that it works correctly with this AJAX request. As mentioned in the comments, it seems like you do not fully understand how AJAX works, and how it communicates with PHP. I suggest the following documentation and tutorials:
AJAX documentation
AJAX beginners guide
Related
When I use ajax to add to cart in details page it works fine but as a button in the products page where there is multiple ones it doesn't work.
I tried limiting the products to 1 and it worked .
So I guess the problem is that I'm using the same form id in multiple forms.
<form method="POST" id="add_to_cartt">
<input type="hidden" name="cart_id" value="<?php echo $final['id'];?>" id="cart_id">
<input type="hidden" name="cart_quantity" value="<?php echo "1" ?>">
<button class="btn js-prd-addtocart" >Add To Cart</button>
</form>
$(document).ready(function(){
$('#add_to_cartt').on('submit', function(e){
//Stop the form from submitting itself to the server.
e.preventDefault();
var cart_id = $('#cart_id').val();
var cart_quantity = $('#cart_quantity').val();
$.ajax({
type: "POST",
url: 'carthandler.php',
data: {cart_id : cart_id, cart_quantity : cart_quantity,},
success: function(data){}
});
});
});
I am making a comment system where a user can comment something to a post and then other users can reply to that comment. I have made a function to comment which works perfectly. I also wanted a similar function to work for that reply to comment part so I copied the same function and made some changes to the code like variable names etc. But its not working. When I write a reply and press enter it takes me to a new line rather than submitting. Please help me.
// COMMENT UPDATE (WORKING)
$(document).on('keydown', '.commentarea', function(event) {
var comtt = $(".commentarea").val();
if(comtt!=''){
if(event.keyCode == 13 && !event.shiftKey) {
var id = $(this).attr('id');
var status_id = id.replace("postcomment_", "");
createComment(status_id);
event.preventDefault();
}
}
});
function createComment(status_id){
var comment = $('#postcomment_'+status_id).val();
$.ajax({
url: "post-comment.php",type: "POST",
data: {comment : comment, statsid : status_id},
success: function (data) {
$("#showbox_"+status_id).append(data);
},
error: function () {
alert("Ooops!! Problem Ocurred. Please try again later. If problem persists, please contact support!");
},
complete: function(xhr) {
$('#postcomment_'+status_id).val('');
}
})
}
// REPLY TO COMMENT (SAME FUNCTION BUT NOT WORKING)
$(document).on('keydown', '.replyarea', function(event) {
var comtr = $(".replyarea").val();
if(comtr!=''){
if(event.keyCode == 13 && !event.shiftKey) {
var rid = $(this).attr('id');
var commentId = rid.replace("replycomment_", "");
createReply(commentId);
event.preventDefault();
}
}
});
function createReply(commentId){
var creply = $('#replycomment_'+status_id).val();
$.ajax({
url: "post-replies.php",type: "POST",
data: {creply : creply, cmtid : commentId},
success: function (data) {
$("#showreply_"+commentId).append(data);
},
error: function () {
alert("Ooops!! Problem Ocurred. Please try again later. If problem persists, please contact support!");
},
complete: function(xhr) {
$('#replycomment_'+commentId).val('');
}
})
}
PHP Part:
<?php while($get_stf = $get_stq->fetch()){ extract($get_stf); // fetch posts ?>
<?php while($fetch_cmts = $get_cmtq->fetch()){ extract($fetch_cmts); // fetch comments?>
<!-- Reply to comments form -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width" id="cmt_form_id_<?php echo $cmt_id; ?>">
<input type="hidden" name="comment_id" value="<?php echo $cmt_id; ?>" id="cmtsid_<?php echo $cmt_id; ?>" />
<textarea name="reply" placeholder="Give a reply..." class="reply-comment-field replyarea" id="replycomment_<?php echo $cmt_id; ?>"></textarea>
</form>
<!-- End Reply to comments form -->
<?php } ?>
<!-- Comment form -->
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" class="full-width" id="cmt_form_id_<?php echo $cmt_id; ?>">
<input type="hidden" name="comment_id" value="<?php echo $cmt_id; ?>" id="cmtsid_<?php echo $cmt_id; ?>" />
<textarea name="reply" placeholder="Give a reply..." class="reply-comment-field replyarea" id="replycomment_<?php echo $cmt_id; ?>"></textarea>
</form>
<!-- End Comment form -->
<?php } ?>
Both functions are same. But one being used for COMMENTS is working perfectly whereas the one used for REPLY TO COMMENTS is not working. It should submit the form and insert the data when I press enter in REPLY TO COMMENTS form after writing some text just like FACEBOOK. Please help.
your comment is broken the code:
Change this:
<!-- Reply to comments form -- >
for this:
<!-- Reply to comments form -->
and update.
I have an admin panel running AngularJS, however when submitted forms it had an error. But I seemed to fix this using javascript, but I'm trying to figure out a way to where when the submit button is clicked, and there is an error - it shows that error on the page rather than an updated javascript. I have this:
<?php
require_once('../dist/inc/config.php');
session_start();
if ($_SESSION['username']) {
}else {
header("Location: /");
}
?>
<?php
$grab = mysql_query("SELECT * FROM settings");
$row = mysql_fetch_assoc($grab);
$val = $row['val'];
if ($_POST) {
$val = mysql_real_escape_string($_POST['val']);
if ($val == "") {
echo ('<div class="alert alert-error" style="margin: 8px; text-align: center;"><strong>Error:</strong> Please enter a site title!</div>');
}
else {
// update the site title
$updateSite = "UPDATE settings SET val='$val'";
mysql_query($updateSite) or die("MySQL Error - Could not update site title");
echo ('<div class="alert alert-success" style="margin: 8px; text-align: center;"><strong>Success:</strong> The site name has been successfully updated!</div>');
}
}
?>
<form action="ajax/yo.php" method="POST" id="load" name="#load">
<input name="val" type="text" value="<?php echo $val ?>" size="31"/>
<input name="submit" type="submit" value="Update" class="button" />
</form>
And here's my javascript that's on the same page as my PHP information above:
<script type="text/javascript">
var frm = $('#load');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
Like I said, It updates the SQL perfectly. It's just I don't want the javascript to execute, I'd rather have the PHP errors from the echo's, appear on the page. However I think that's a problem, because my AngularJS runs like this:
page#ajax/yo.php
If it's any help, I use the http://devoops.me/ admin panel.
try this
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data);
}
});
Usually the right approach to process forms "inside" angular is to use AJAX, because otherwise you easily may break angular's page logic by reloading the page, any angular application is a single page web app, and any communication with server should be done through AJAX.
In your case, you can show server message by adding its response to DOM may be like this:
success: function (data) {
frm.append(data);
}
But, there of course may be some reasons, to not to do so, then, if you set action attribute to <form> brouser should send your POST request, and try to render the response as new page and because of it, response should contain full page in this case, not only message! so it should look like:
echo '<form action="ajax/yo.php" method="POST" id="load" name="#load">
<input name="val" type="text" value="<?php echo $val ?>" size="31"/>
<input name="submit" type="submit" value="Update" class="button" />
<div class="alert alert-success" style="margin: 8px; text-align: center;"><strong>Success:</strong> The site name has been successfully updated!</div>
</form> ';
but in fact it may be required to include much more in response, because again, if not use AJAX you should return a whole page (if not using some framing technique) including angular and then angular page will initiated from scratch.
I have a code here of inserting and displaying record without refreshing web page using ajax and plain php but I don't know how to set this up using codeigniter. Please help. Here are the codes
inserting.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle">
<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
document.getElementById('content').focus();
$("#flash").hide();
}
});
} return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Update" name="submit" class="comment_button"/>
</form>
</div>
<div id="flash"></div>
<div id="display"></div>
demo_insert.php
PHP Code display recently inserted record from the database.
<?php
include('db.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
mysql_query("insert into messages(msg) values ('$content')");
$sql_in= mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc");
$r=mysql_fetch_array($sql_in);
}
?>
<b><?php echo $r['msg']; ?></b>
In your wellcome controller you can add the following:
public function inserting()
{
$this->load->view('inserting');
}
public function process()
{
$content=$this->input->post('content');
if($this->db->insert('mytable', array('msg' => $content))){
echo "<b>{$content}</b>";
}
You should then use inserting.php as your view, in application/views, and the ajax url would be /process.
Didn't test it, but this should do the trick. Also, you should check this example http://runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php
Up to this point, I've been using a textarea as the main input for a form. I've changed it to use a contenteditable div because I wanted to allow some formatting.
Previously, when I had the textarea, the form submitted fine with Ajax and PHP. Now that I've changed it to use a contenteditable div, it doesn't work anymore and I can't tell why.
HTML:
<form>
<div name="post_field" class="new-post post-field" placeholder="Make a comment..." contenteditable="true"></div>
<input name="user_id" type="hidden" <?php echo 'value="' . $user_info[0] . '"' ?>>
<input name="display_name" type="hidden" <?php echo 'value="' . $user_info[2] . '"' ?>>
<ul class="btn-toggle format-post">
<button onclick="bold()"><i class="fa-icon-bold"></i></button>
<button onclick="italic()"><i class="fa-icon-italic"></i></button>
</ul>
<div class="post-buttons btn-toggle">
<button class="btn-new pull-right" type="submit">Submit</button>
</div>
</form>
JQuery Ajax:
$(document).ready(function() {
$(document).on("submit", "form", function(event) {
event.preventDefault();
$.ajax({
url: 'php/post.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
alert(data.message);
}
});
});
});
PHP (post.php): Just your typical checks and echo a message back. This is just a snippet of the code.
<?php
$user_id = $_POST["user_id"];
$display_name = $_POST["display_name"];
$post_content = $_POST["post_field"];
$array = array('message' => $post_content);
echo json_encode($array);
?>
For some reason, it's not sending back the post content anymore ever since I added the contenteditable div.
Please help!
The contents of the div are not serialized. You would have to add them on your own.
var data = $(this).serialize();
data += "post_field=" + encodeURIComponent($("[name=post_field]").html());