Why jQuery Code is not working in Magento - javascript

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

Related

ajax onchange form submission is not working

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;
}
?>

Popup message and ajax to jquery form

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

Running a PHP form using AJAX

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.

How to Insert and display record without refreshing web page in codeigniter version?

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

Getting value from contenteditable div

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());

Categories