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.
Related
The code is working fine but the problem is that when I add this code to Magento it the Javascript doesn't work.
Let me explain a little bit about code. There is a simple form that has only one input field which is intended to enter phone numbers. There is another file called form.php that has all the PHP code. Whenever someone enters a phone number in the input field the PHP saves that number in the CSV file which is created in the backed. I don't want to redirect the form to another page, I just wanted a small message to appear in the same page without page reloading or redirecting.
For that, I added a jQuery code and it was working fine but the code was created to add it on Magento but when I add this code to Magento then the only the Javascript code doesn't work. Does anyone have a solution for this?
$(function() {
$("#myform").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
$("#message").hide();
$("#response").html(data);
}
});
});
});
<form id="myform" action="https://www.tawakkalfabric.com/form.php" method="post">
<div class="block-content">
<div class="form-subscribe-header">
<label for="newsletter">Sign Up for Our Newsletter:</label>
</div>
<div class="input-box">
<input type="tel" name="name" placeholder="Sign Up for Our WHATSAPP" />
</div>
<div class="actions">
<button type="submit" class="button"><span><span>Subscribe</span></span></button>
</div>
<div id="message"></div>
<div id="response"></div>
</div>
</form>
The code below is in form.php:
<?php
$email = $_POST['email'];
$name = $_POST['name'];
$data = $name.",".$email;
$file = "sample.csv";
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
print "<h1 align=center>Thank you for submitting your email address!</h1>";
?>
<html>
<head>
<title>ThankYou Page</title>
</head>
<body>
<h1>GO BACK</h1>
</body>
try following code
<script>
$(document).on("submit", "#myform", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
$("#message").hide();
$("#response").html(data);
}
});
});
</script>
Magento (similar to WordPress) doesn't automatically allow for the $ alias, so you will need to include the code with the jQuery dependencies and then either create the alias or change the $ to jQuery.
See https://magento.stackexchange.com/questions/97184/how-to-use-jquery-library-in-magento-2
I have a PHP file which SELECT's all from the row found based on an SQL query. When I put the echo in a div, I get all information, but when I try to echo it into an input box in a form, it does not shows.
What am I doing wrong?
Please also note that I am aware that I am (most likely) making a lot of mistakes when it comes to security practices or programming standards, but this whole thing (PHPDesktop > https://github.com/cztomczak/phpdesktop) will get packed into an EXE file which will run locally only (no need for an online connection as the SQLite3 DB gets packed in with the EXE), and I am still figuring out how to program this in the first place, so efficient and tidy coding are not high on my list yet ;-)
DO_CUSTEDIT.PHP
$custName = $_POST['custName'];
$query = "SELECT * FROM `CustDB` WHERE CustName LIKE '%$custName%'";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
$custID = $row['CustID'];
......;
}
if (!$result) {
echo $db->lastErrorMsg();
$db->close();
exit;
} else {
echo $custID;
echo ......;
$db->close();
exit;
}
EDITCUST.PHP / Javascipt
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function(strMessage) {
if (strMessage == "Customer updated successfully") {
$("#message").text(strMessage);
$("#neweditform").get(0).reset();
} else {
$("#message").text(strMessage);
}
}
});
});
});
</script>
EDITCUST.PHP / HTML
<form id="editcustform" name="editcustform" action="" method="post">
<div class="row">
<div class="column-half" style="background-color:#fff">
<table>
<tr>
<td>
<a>Customer ID</a>
</td>
<td>
<div class="inputb">
<input type="text" name="custID" value="<?php echo (isset($custID)) ? $custID: ''; ?>" readonly/>
</div>
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<table style="table-layout:fixed">
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="subeditcust" type="submit" class="mainbtn">Create</button>
</td>
<td style="background-color: rgb(215,215,215); padding:0 10px;">
<button id="reseteditcust" type="reset" class="mainbtn">Reset</button>
</td>
</table>
</div>
</form>
<input type="text" name="custID" value="<?php echo (isset($custID) ? $custID: ''); ?>" readonly/>
Replace this line with yours it will work. IA
It seems you have two different files, right? DO_CUSTEDIT.PHP and EDITCUST.PHP
The variables are being created on DO_CUSTEDIT.PHP and the when you are creating the HTML code those variables ($custID) are not setted.
Is one file including or requiring the other?
EDITCUST.PHP is your first page from you are submitting form to DO_CUSTEDIT.PHP
When you land on EDITCUST.PHP variable $custID is not created
When the form is submitted through ajax, the ajax returns the data inform of object or array depending on how you are echoing the data from DO_CUSTEDIT.PHP
I would recommend to use json_encode() php function to return inform of array
To debug the value by logging the data in console (though function console.log())
After returning the value from ajax, you have to populate the value in form through jquery something like $(input[name="custID"]).val( data.custID )
I managed to figure it out!
DO_CUSTEDIT.php / PHP
$results = array($custID, $custName);
echo json_encode($results, JSON_PRETTY_PRINT);
EDITCUST.php / HTML
<input type="text" id="custID" name="custID" value="" readonly/>
<input type="text" id="custName" name="custName" value="" readonly/>
EDITCUST.php / JS
<script>
$(document).ready(function() {
$("#subeditcust").on('click',function(e) {
e.preventDefault();
$.ajax( {
url: "lib/do_editcust.php",
method: "post",
data: $("form").serialize(),
dataType: 'json',
success: function(data){
document.getElementById('custID').value = data[0];
document.getElementById('custName').value = data[1];
}
});
});
});
</script>
i am trying to submit a form using onchange event. my form contain check box, on check form should be submit and send the data to php and return value from php page.
bellow is my form
<form id="search_form" method="post">
<input class="le-checkbox" type="checkbox" name="filter1[]" value="<?=$bkey?>" /> <label><?=$bkey?></label>
<input class="le-checkbox" type="checkbox" name="filter2[]" value="<?=$bkey?>" /> <label><?=$bkey?></label>
<input class="le-checkbox" type="checkbox" name="filter3[]" value="<?=$bkey?>" /> <label><?=$bkey?></label>
<input class="le-checkbox" type="checkbox" name="filter4[]" value="<?=$bkey?>" /> <label><?=$bkey?></label>
</form>
and i am using ajax to send data and retrieve from php page
<script type="text/javascript">
$(document).on("change",'[type="checkbox"]',function(){
var url = "protest.php";
$.ajax({
type: "POST",
url: url,
data: $("#search_form").serialize(),
success: function(data)
{
//$('.ajax_result').html(data);
alert(data);
}
});
return false;
});
</script>
if the form is submitted php result is shown in alert(data) bellow is my php example page
<?php
if (isset($_POST)){
echo "data submited";
}
?>
first of all its not working and in alert message is showing source code please check the image
i am unable find the issue
Just put exit after your echo.
<?php
if (isset($_POST)){
echo "data submited";
exit;
}
?>
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
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());