I want to make form html look like this :
<script>
function name()
{
var name = $('#name').val();
var url_send = 'send.php';
$.ajax({
url : url_send,
data : 'name='+name,
type : 'POST',
dataType: 'html',
success : function(pesan){
$("#result").html(pesan);
},
});
}
</script>
<script src="assets/bootstrap-sweetalert.js"></script>
<script src="assets/sweetalert.js"></script>
<link rel="stylesheet" href="assets/sweet-alert.css">
<form action="#" method="post">
<label>Name</label>
<input type="text" name="name"><br>
<input type="submit" onclick="name();">
<div id="result"></div>
and this is send.php
<?php
$name = $_POST['name'];
if($name) {
echo 'success';
} else {
echo 'failed';
}
?>
And the problem is,how i show SweatAlert modal,when result of php is Success Sweatalert will show Success Modal.And when failed it will show Failed Modal ?
Now what must i edit to my script?
I hope you are expecting code with jquery ajax;
See the code below;
index.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<link rel="stylesheet" type="text/css" href="sweetalert-master/dist/sweetalert.css">
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="sweetalert-master/dist/sweetalert.min.js"></script>
<script>
$(document).ready(function () {
$("#submit").on("click", function(e){
e.preventDefault();
var name_val = $("#name").val();
$.post( "send.php", {name_send:name_val}, function(data){
if (data == 'success'){
swal("Good job!", "Nice work!", "success");
return false;
}else{
swal("Here's a message!", "Please type a name");
}
});
});
});
</script>
</head>
<body>
<form>
<label>Name</label>
<input type="text" name="name" id="name"><br>
<input type="submit" id="submit">
</form>
</body>
</html>
send.php
<?php
$name = $_POST['name_send'];
if($name) {
echo 'success';
} else {
echo 'failed';
}
?>
$.ajax({
url : url_send,
data : {name: name},
type : 'POST',
dataType: 'html',
success : function(pesan){
$("#result").html(pesan);
},
});
in your ajax code you placed data : 'name='+name, , please have a look at what i did , maybe that helps
Jquery ajax accepts object in data parameter data: {key:value}. In the question we are using string as a parameter to data of jquery ajax
Related
I trying to print the data which was entered by the user, and transfer that through ajax and trying to print or echo it with the help of php code, but I could not do that. enter code here
this is my code:
<html>
<head>
<title>
test ajax
</title>
<script src="jquery.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type="text" id="a"><br>
<input type="button" id="b" value="display">
</form>
<script>
$(document).ready(function() {
$('#b').click(function() {
let a = $('#a').val();
alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {
c: a
},
success: function() {}
});
});
});
</script>
</body>
</html>
<?php
extract($_POST);
if(isset($_POST["c"])) {
echo $_POST["c"];
}
?>
I think that, I have the problem with the php code. please give me any solution.
Try it like this
This is your Html
<html>
<head>
<title>
test ajax
</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type = "text" id = "a" > <br>
<input type = "button" id = "b" value = "display" >
</form>
</body>
</html>
<script>
$(document).ready(function(){
$('#b').click(function() {
let a = $('#a').val();
//alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {c: a},
success: function(response) {
alert(response);
}
});
});
});
</script>
This is your same_file.php
<?php
//extract($_POST); code works even without this
if(isset($_POST["c"])) {
echo $_POST['c'];
}
?>
Not sure if your jquery library call is ok so I called the one on the web instead. Also your success:function() was not doing anything which is why you didn't receive anything.
Also always format your code with some indention so that it can be easier to read and comprehend by others.
You probably want to echo before the body is rendered.
But in true, unless you need to process the data the user sends, you don't need PHP at all.
And in truth, you probably don't need jQuery as well, fetch() works just fine.
$(document).ready(function() {
$('#b').click(function() {
let a = $('#a').val();
alert(a);
$.ajax({
type: "POST",
url: "same_file.php",
data: {
c: a
},
success: function() {}
});
});
});
<?php
if (isset($_POST["c"]))
{
// print/echo user data send from form.
echo $_POST["c"];
// stop the script from rendering the html below.
exit();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h2>test button</h2><br>
<form>
<input type="text" id="a"><br>
<input type="button" id="b" value="display">
</form>
<!-- add script element with js code here -->
</body>
</html>
I'm trying out a tutorial to learn how to do instant search with PHP/jQuery. I can't seem to find why this code won't work. This search was working before when I had the PHP in the same file as the index, but when I moved it to another file, it stopped working. I keep getting this console error message with each keystroke: ReferenceError: Can't find variable: $_POST. Any help would be deeply appreciated.
index.php file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset-utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function searchkey() {
var searchTxt = $("input[name='search']").val();
$_POST("search.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});
}
</script>
<title>Search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search for members..." onkeyup="searchkey();">
<input type="submit" value="Search">
</form>
<div id="output"></div>
</body>
</html>
search.php file (same location as index.php)
<?php
$connection = mysqli_connect('localhost','root','root','LBD');
$output='';
if(isset($_POST['searchVal'])){
$searchkey= $_POST['searchVal'];
$searchkey=preg_replace("#[^0-9a-z]#i", "", $searchkey);
$query = mysqli_query($connection,"SELECT * FROM members WHERE ownerName LIKE '%$searchkey%' OR companyName LIKE '%$searchkey%'") or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output="There was no search result!";
}
else{
while($row=mysqli_fetch_array($query)){
$oName=$row['ownerName'];
$cName=$row['companyName'];
$output .='<div>'.$oName.'<br/>'.$cName.'</div>';
}
}
}
echo ($output);
?>
Looks like you've used the PHP $_POST in your script..
Try to use:
$.POST
Try this
$.ajax({
url: "search.php",
type: 'POST',
data: {
searchVal: searchTxt
},
})
.done(function(output) {
$("#output").html(output);
});
i am trying to echo the value entered by the user in the input tag using jquery and ajax .
the following is my code
< script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script> <
script type = "text/JavaScript" >
function showMessage() {
var message = document.getElementById("message").value;
$.ajax({
url: 'value_pass.php',
type: 'GET',
data: {
var_PHP_data: message
},
success: function(data) {
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//case error
}
});
} <
/script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Enter message: <input type="text" id="message">
<input type="submit" onclick="showMessage()" value="submit" />
<?php echo "hi".$_GET['var_PHP_data'];?>
</body>
</html>
My php script is:
<?php
echo "hi".$_GET['var_PHP_data'];
?>
the code alert the success prompt , but i am not able to access the value using GET , any pointers on what i am doing wrong.
If you are doing this on same page add your php script at the top of the page that handle your ajax request
Like this
<?php if(isset($_GET['var_PHP_data'])){
echo "hi".$_GET['var_PHP_data'];
die;
}?>
<!-- rest of your html code start from here -->
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Enter message: <input type="text" id="message">
<input type="submit" onclick="showMessage()" value="submit" />
</body>
</html>
If you using ajax, follow below code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Enter message: <input type="text" id="message">
<input type="submit" onclick="showMessage()" value="submit" />
<span id = 'PHP_data'></span>
</body>
</html>
<script src = "//code.jquery.com/jquery-1.11.0.min.js" > < /script>
<script type = "text/JavaScript" >
function showMessage() {
var message = document.getElementById("message").value;
$.ajax({
url: 'value_pass.php',
type: 'GET',
data: {
var_PHP_data: message
},
success: function(data) {
message1 = "Hi "+message
$('#PHP_data').html(message1);
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
//case error
}
});
}
</script>
If you are using form submit use below code
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method ='GET'>
Enter message: <input type="text" id="message" name = "message">
<input type="submit" value="submit" />
<?php if(isset($_GET['message'])){
echo "hi".$_GET['message'];
die;
} ?>
</form>
</body>
</html>
Basically I've got a AJAX Login page that is working and everything but when I successfully login I want it to redirect to a page without it reloading I'm not sure how its done as I am very new to langauge. Many thanks
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js"></script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<title>Popup Login</title>
<script type="text/javascript">
$(document).ready(function(){
$("#login_a").click(function(){
$("#shadow").fadeIn("normal");
$("#login_form").fadeIn("normal");
$("#user_name").focus();
});
$("#cancel_hide").click(function(){
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
});
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "login.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='1')
{
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<a href='logout.php' id='logout'>Logout</a>");
}
else
{
$("#add_err").html("Wrong username or password");
}
},
beforeSend:function()
{
$("#add_err").html("Loading...")
}
});
return false;
});
});
</script>
</head>
<body>
<?php session_start(); ?>
<div id="profile">
<?php if(isset($_SESSION['user_name'])){
?>
<a href='logout.php' id='logout'>Logout</a>
<?php }else {?>
<a id="login_a" href="#">login</a>
<?php } ?>
</div>
<div id="login_form">
<div class="err" id="add_err"></div>
<form action="login.php">
<label>User Name:</label>
<input type="text" id="user_name" name="user_name" />
<label>Password:</label>
<input type="password" id="password" name="password" />
<label></label><br/>
<input type="submit" id="login" value="Login" />
<input type="button" id="cancel_hide" value="Cancel" />
</form>
</div>
<div id="shadow" class="popup"></div>
</body>
</html>
login.php
<?php
session_start();
$username = $_POST['name'];
$password = $_POST['pwd'];
$mysqli=mysqli_connect('');
$query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row >=1 ) {
echo '1';
$_SESSION['user_name']=$row['username'];
}
else{
echo 'false';
}
?>
When I successfully login I want it to redirect to a page without it reloading
As long as the page to be redirected to is on the same domain, or you can set CORS headers properly, and you can deal with relative links, then in your success callback you can replace the entire page's HTML with that of the new page.
You can start another ajax call for your new page, and use document.write() to obliterate the existing HTML like so:
...
success: function(html){
if(html=='1') {
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut(400, function(){
// Completely replace the page's HTML
$.ajax({
type: 'GET',
url: 'http://example.com/logged-in',
async: false, // You want this synchronous
success: function(data) {
// This code block replaces your current page seamlessly
document.open();
document.write(data);
document.close();
},
error: function(e){
alert(e.message);
}
});
});
}
...
Here is a demo:
$("#bye").fadeOut(1400, function(){
$.ajax({
type: 'GET',
url: 'http://enable-cors.org/',
async: false,
success: function(data) {
// This is a quick-n-dirty hack
// to get the relative links working for the demo
var base_href = '<base href="http://enable-cors.org/">';
document.open();
document.write(base_href + data);
document.close();
},
error: function(e){
alert(e.message);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="bye"><h1>Logged in Successfully</h1></div>
Firstly I apologize for posting another one of these questions, but I've dove through a ton of SO questions related to this topic and haven't be able to figure out my problem. I'm new to PHP and an amature at best using Jquery mobile and the like.
I'm attempting to post to a .php file and get a response back. Eventually this will evolve into a database posting yada yada. For now, I can't seem to get my response back from my post. I'm running Xampp to host the php, Jquery Mobile is being used in other functions so it does work properly,
HTML:
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
Javascript:
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
$.post(dbURL, {
//These are the names of the form values
Username: $('#username').val(),
Password: $('#password').val()
}, function (data,status) {
alert(status); //Won't fire
alert(html); //Won't fire
var response = html;
alert(response); //Won't fire
if (response == "Success")
{
alert("Success!"); //Won't fire
//testlog.innerHTML = "Success";
}
else
{
alert("Failure!");//Won't fire
//testlog.innerHTML = "Failure";
}
});
alert("Finished"); //Fires
};
PHP
<?php
// VARS
$Username=$_GET["Username"]; //Also tried _POST
$Password=$_GET["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
My best guess is that something is wrong with the .php because all of the questions I've looked at seem to confirm my JavaScript is right. All of my alerts fire except the ones in the call back function. The username and password are also correctly being set so that isn't the problem. I tried using _POST and _GET in my .php, I originally was using _POST because I was posting data but I was following this question: (Phonegap contact form not working over PHP) and it did the opposite so I changed it. No difference. My .php is actually hosted for sure (I can navigate to it without an error). I also tried using the $.ajax function but had the same issues.
Thanks in advance.
EDIT: Added more of the HTML (all that should be relevant) per request, can't add it all as it is too long.
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<!-- Stylesheets -->
<link rel="stylesheet" href="css/snctfy2/snctfy2.css" />
<link rel="stylesheet" href="css/snctfy2/jquery.mobile.icons.min.css" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link href="jquerymobile/jquery.mobile.structure-1.4.2.min.css" rel="stylesheet" type="text/css" /> <!-- Add .structure after theme-->
<!-- Jquery core -->
<script src="js/jquery.js" type="text/javascript"></script>
<!-- Jquery mobile library file -->
<script src="jquerymobile/jquery.mobile-1.4.2.min.js" type="text/javascript"></script>
<!-- DateBox -->
<link rel="stylesheet" type="text/css" href="css/jqm-datebox.css" />
<script type="text/javascript" src="js/datebox/jqm-datebox.core.js"></script>
<script type="text/javascript" src="js/datebox/jqm-datebox.mode.calbox.js"></script>
<script type="text/javascript" src="js/datebox/jqm-datebox.mode.datebox.js"></script>
<script type="text/javascript" src="js/datebox/jquery.mobile.datebox.i18n.en_US.utf8.js"></script>
<!-- Scripts (pre-load)-->
<script src="js/scripts.js" type="text/javascript"></script>
<!-- CSS Override -->
<link rel="stylesheet" type="text/css" href="css/override.css" />
<title>SNCTFY</title>
</head>
<body>
<!--there is some more <div> tags here unrelated-->
<!--------------------------------------------------------Login Page---------------------
-------------------------------------------->
<div data-role="page" id="login" data-theme="a" class="bPage">
<div data-role="content">
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
Register
<button onclick="showAlert()">Test</button>
<p id="testlog">Results</p>
</div>
</div>
<!-- more <div> pages -->
<!-- Scripts (post-load)-->
<script type="text/javascript" src="phonegap.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
EDIT2: Changed JavaScript to one of the answers to test
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "http://localhost/testerpage.php",
data: { "Username": username, "Password": password },
success: function (data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
};
Just try jquery Ajax
<body>
<form>
<p>Username: </p><input type="text" id="username" value="" />
<p>Password: </p><input type="text" id="password" value="" />
<input type="button" onclick="submitLogIn()" value="Log In" />
</form>
<script>
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var username =$('#username').val();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "http://localhost/testerpage.php",
data:{"Username":username,"Password":password},
success: function(data) {
if (data) {
alert(data);
}
else {
alert('Successfully not posted.');
}
}
});
}
</script>
</body>
</html>
in PHP
<?php
$Username=$_POST["Username"]; //Also tried _POST
$Password=$_POST["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
Try this:
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
//These are the names of the form values
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: dbURL,
type:'post',
data:'&username='+username+'&pass='+password,
success:function(response){
alert(response);
}
});
};
<?php
// VARS
$Username=$_POST["username"]; //Also tried _POST
$Password=$_POST["pass"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}
?>
try this code
script
<script>
function submitLogIn() {
alert("Submitting: " + $('#username').val() + $('#password').val());
var dbURL = "http://localhost/testerpage.php";
$.post(dbURL, {
//These are the names of the form values
Username: $('#username').val(),
Password: $('#password').val()
}, function (data,status) {
if (data == "Success")
{
alert("Success!"); //Won't fire
//testlog.innerHTML = "Success";
}
else
{
alert("Failure!");//Won't fire
//testlog.innerHTML = "Failure";
}
});
alert("Finished"); //Fires
};
</script>
PHP
// VARS
$Username=$_POST["Username"]; //Also tried _POST
$Password=$_POST["Password"]; //Also tried _POST
//VALIDATION
if(
$Username=="" ||
$Password==""
) {
echo "Error";
} else {
echo "Success";
}