I just need to display names of the array using ajax. Following code is working but the result ( Nilantha Ruwan Nimal Shamitha Alex) is just display and disappears.
Index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
</head>
<body>
<div class="container" style="margin-top:50px";>
<form >
<div class="form-group">
<input type="text" id="name" class="form-control" placeholder="Enter Name....">
</div>
<div class="form-group">
<button class="btn btn-success" id="btn">Enter</button>
</div>
</form>
<div class="msg"></div>
</div>
<script type="text/javascript" src="assets/js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
var name = $("#name").val();
$.post("ajax.php",{ajax_name:name},function(response){
$(".msg").html(response);
})
.fail(function(error){
alert(error.statusText);
})
})
})
</script>
</body>
</html>
ajax.php
<?php
if(isset($_POST['ajax_name'])){
$store = array("Nilantha","Ruwan","Nimal","Shamitha","Alex");
foreach($store as $names) {
echo $names,"<br>";
}
}
?>
Try the following code.
<script type="text/javascript">
function submit() {
jQuery("form").submit(function(e) {
e.preventDefault();
var name = jQuery("#name").val();
jQuery.ajax({
type: 'POST',
url: 'ajax.php',
data: {ajax_name:name},
success: function(response) {
jQuery(".msg").html(response);
jQuery('#name').val('');
},
error: function() {
console.log("Something wrong");
}
});});
}
jQuery(document).ready(function() {
submit();
});
</script>
I would suggest looking at the network tab of Chrome Devtools and ensuring that the AJAX call isn't running twice. I would think that if the query ran twice but the second one did not have any name attached then it would return blank once the first one had received its response.
Related
I am using blade.php in my development, and I have a concern in validating if the input is a valid instagram url. I have tried doing this:
<form class="search_form" id="apply" action=" method="post">
#csrf
<label>
<input type="url" pattern="https?://.+" required id="instagram" value="" placeholder="Instagram Post URL (Paste Here)">
</label>
<div class="flex_box">
<button class="btn pink applyfnsh_btn" type="button" id="save">Confirm</button>
</div>
</form>
UPDATE this modal is displayed after validation
<div class="applyfnsh_modal">
<div class="applyfnsh_box">
<div class="modal_close">
<img src="../../assets/images/close.png" alt="close">
</div>
<p>Success</p>
</div>
</div>
modal.js
$(".applyfnsh_btn").on("click", function(){
$(".apply_modal").toggleClass("open");
$(".applyfnsh_modal").toggleClass("open");
});
$(".applyfnsh_modal").on('click touchend', function(event) {
if (!$(event.target).closest('.applyfnsh_box').length) {
$(".applyfnsh_modal").toggleClass("open");
$("body").toggleClass("open");
}
});
location is here
<script src="{{ url('/assets/js/modal.js') }}"></script>
And by the way, I'm using ajax in saving data to db so that page is not refreshed.
<script>
$(document).on("click", "#save", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "post",
url: '/contest/apply/{{ $contest->id }}',
data: {url : $("#instagram").val(), user_id: 1, contest_id: {{ $contest->id }} },
success: function(store) {
},
error: function() {
}
});
});
</script>
This isn't working and even processes the data when the button is clicked even if the input is not a url or empty.
Is there a way to do it without making a function?
here it is :
$(document).on("click", "#save", function() {
var instagramLink = $('#instagramLink').val();
var pattern = new RegExp('https://www.instagram.com/p/(.+?)', 'g');
if((instagramLink != undefined || instagramLink != '') && instagramLink.match(pattern)){
alert(instagramLink + 'is valid');
/*
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
url: '/contest/apply/{{ $contest->id }}',
data: {url :instagramLink, user_id: 1, contest_id: {{ $contest->id }} },
success: function(store) {
},
error: function() {
}
});
*/
}else{
alert('Please Enter Valid Instagram Link');
$('#instagramLink').val('');
// show modal
$('.applyfnsh_modal').modal('open');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<form class="search_form" id="apply" action="" method="post">
<label>
<input type="url" required id="instagramLink" value="" placeholder="Instagram Post URL (Paste Here)" class="form-control"/>
</label>
<div class="flex_box">
<button class="btn btn-primary" type="button" id="save">Confirm</button>
</div>
</form>
</body>
</html>
update-2 : remove your existing scripts :
$(".applyfnsh_btn").on("click", function(){
$(".apply_modal").toggleClass("open");
$(".applyfnsh_modal").toggleClass("open");
});
$(".applyfnsh_modal").on('click touchend', function(event) {
if (!$(event.target).closest('.applyfnsh_box').length) {
$(".applyfnsh_modal").toggleClass("open");
$("body").toggleClass("open");
}
});
display modal using this way when it is required to display :
to OPEN MODAL : $('.applyfnsh_modal').addClass('open');
to CLOSE MODAL : $('.applyfnsh_modal').removeClass('open');
so
if (validation successfull){
// submit form using AJAX
}else{
$('.applyfnsh_modal').addClass('open');
}
also create one function to close modal :
$(document).on('click','.modal_close',function(){
$('.applyfnsh_modal').removeClass('open');
});
I am trying to display the POST data of my form to the same page with Ajax. This is working fine but I am new to OOP and my class which builds an array with the POST content is getting overwritten on every request.
I understand I could post the data to a JSON file or Database but I wanted it to be solely displaying a "growing" array.
Index.php
<html>
<head>
<head>
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
<link href="https://fonts.googleapis.com/css?family=Poppins:400,500,600,700,800" rel="stylesheet">
</head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function () {
var frm = $('form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$("#response").html(data);
}
});
ev.preventDefault();
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="flex40">
<div class="container40">
<form id="form" action="response.php" method="post">
<input name="postName" type="text" placeholder="Name" required>
<select name="postEyeColour">
<option>Blue</option>
<option>Red</option>
<option>Yellow</option>
<option>Green</option>
</select>
<button name="submit" type="submit">New Person</button>
</form>
<div class="character-table">
<table id="response"></table>
</div>
</div>
</div>
</div>
</body>
</html>
response.php
<?php
require_once 'Classes/Person.php';
$character = new Person;
if (isset($_POST['postName'])) {
$character->createNewPerson();
$character->getPersonList();
}
?>
Classes/Person.php
<?php
class Person {
private $personList = array();
public function createNewPerson() {
// Build Array From Post Data
$newPerson= array(
"Name" => $_POST['postName'],
"Eye Colour" => $_POST['postEyeColour']
);
//Push New Person to data array
$this->personList[] = $newPerson;
}
public function getPersonList() {
print_r($this->personList);
}
}
?>
What happens is that the data is posted to the array but every time I add some more data it is resetting the Array with the new data not appending it.
Hello so I have 2 submit buttons with different names (btn1, btn2) in my html form and what I am trying to do is to submit to another page without refreshing page. So what I wanted to do is if I click btn1 submit it will do something and if I click btn2 it will do another thing. My code in the html page is this
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
$.ajax({
url:'update.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1"> <input type="submit" name="btn2">
</form>
</body>
</html>
And the code in my update.php page
<?php
if(isset($_POST['btn1'])) {
//insert query
} else if(isset($_POST['btn2'])) {
//another insert query
}
?>
I actually got it working if I only have 1 submit button and no if(isset()) thing in the update.php page. What can I do to use 2 submits and with issets in another page without refreshing the main page?
$(this).serialize();
The above code statement doesn't include name of the submit button as a key value pair.
So, as people have suggested before me, you should use button instead of submit button. Something like this.
HTML and JS
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#btn1, #btn2').on('click',function(e) {
var datastr = $(this).serialize() + "&button_id="+$(this).attr('id');
$.ajax({
url:'update.php',
data:datastr,
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm" action="update.php">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<button id="btn1">Button1</button><button id="btn2">Button2</button>
</form>
</body>
</html>
AND PHP would be:
<?php
if($_POST['button_id'] == 'btn1') {
//do something
} else if($_POST['button_id'] == 'btn2') {
//do something else;
}
?>
Use this, may useful for you
try
$('#myForm').on('submit',function(e) {
e.preventDefault();
});
OR
<button type="button">
Use on click event on the button and add the value attribute to the submit button, the value of the click button will be pased to the php file
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('input[type="submit"]').on('click',function(e) {
e.preventDefault();
$.ajax({
url:'update.php',
data:{'txt_amount':$('input[name="txt_amount"]').val(),'btn': $('input[type="submit"]').val()}
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1" value="btn1"> <input type="submit" name="btn2" value="btn2">
</form>
</body>
</html>
php:
<?php
if($_POST['btn'] == 'btn1') {
//do something
} else if($_POST['btn'] == 'btn2') {
//do something else;
}
?>
I've been experimenting with modal dialogue boxes and came across one which uses the FancyBox JQuery tool. I am trying to understand why the validation script works correctly when the modal elements are in HTML form on the same page (in the body tags) as the script, however if I generate these elements in a php file the validation script fails.
Please see my index.php file:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" media="all" href="style-modal.css">
<link rel="stylesheet" type="text/css" media="all" href="fancybox/jquery.fancybox.css">
<script type="text/javascript" src="fancybox/jquery.fancybox.js?v=2.0.6"></script>
<script type ="text/javascript" src="like2.js"></script>
<title></title>
<script type="text/javascript">
$(document).ready(function() {
$(".load").load('show.php');
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var commentid = $("#commentid").val();
alert("clicked!");
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(mailvalid == true) {
$("#send").replaceWith("<em>Sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
});
}
});
});
</script>
</head>
<body>
<div class="load">
</div>
</body>
</html>
Please see the php file "show.php" which I load:
<?php
include('connect.php');
echo '<div class="load">
<button class="modalbox" href="#inline">Click</button>
</div>
<div id="inline">
<h3>Enter your email to receive updates</h3>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<input type="hidden" id="commentid" name="commentid" value="5">
<br>
<button id="send">Send E-mail</button>
</form>
</div>
</div>';
?>
In this format when I click "Click" on index.php, the modal appears as normal, however when I click "Send E-mail" with or without data, the modal fades without any feedback or validation. Is it possible to work with this set up? All works as expected when the contents of div id="inline" from show.php are put into the body of index.html. Please assist
this script receive time from www.time.is and from #twd ID and show when click on the send btn.
I have two problems:
1-only show first receive time and don't update when click on send again
2- page refresh and lose data
I have Three problem with below code:
<?php include 'simple_html_dom.php'; ?>
<!DOCTYPE html>
<html>
<head>
<title>Untitled 1</title>
<script src="js/jquery.js"></script>
</head>
<body>
<form action="" method="POST">
<input id="url" name="url" type="text" value="http://www.time.is/">
<input id="address" name="address" type="text" value="#twd">
<input id="send" type="submit" value="get">
</form>
<ul id="times">
</ul>
<script type="text/javascript">
$("#send").click(function(events) {
events.preventDefault();
var url = $("#url").val();
var address = $("#address").val();
var dataString = 'url=' + url + '&address=' + address;
$.ajax({
type: "POST",
url: "read.php",
data: dataString,
success: function() {
var result = "<?php echo getme($url,$address); ?>";
alert(result);
$('#times').append('<li></li>');
}
});
return true;
});
</script>
<?php
function getme($url, $address) {
$html = file_get_html($url);
$code = $html->find($address, 0);
return $code;
}
echo getme($url, $address);
?>
</body>
</html>
any body can help me ..
Thanx all
Try this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function timer(){
$.post( "process.php", function( data ) {
$('#times').append('<li>'+data+'</li>');
});
}
setInterval(function(){timer()},1000);
});
</script>
</head>
<body>
<ul id="times"></ul>
</body>
</html>
And put this in your process.php file:
<?php
include 'simple_html_dom.php';
$html = file_get_html('http://www.time.is/');
foreach($html->find('#clock0') as $element){
echo $element->plaintext;
}
?>
This is my test result:
11:15:43AM
11:15:46AM
11:15:51AM
11:15:53AM
11:15:53AM
11:16:10AM
11:15:52AM
11:15:42AM
11:16:09AM
11:16:17AM
11:16:12AM
Note:
1- It is advisable that you change intervals from 1000 milliseconds (1 second).
2- Don't forget to use clearInterval() after specific repeat.