sending data from html to php page without leaving page - javascript

I already used huge time for this in stack overflow and googling.But none of it worked for me.
I have a form in html and i need to send the data to a php without leaving the page.I used ajax and javascript.I can POST data by leaving the page but i don't want to leave the page.
here is my html:
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<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" />
<link rel="stylesheet" type="text/css" href="css/topcoat-mobile-light.css" />
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<script src = "js/jquery.js"></script>
<script type="text/javascript" src = "js/index.js"></script>
<meta name="msapplication-tap-highlight" content="no" />
<title>Title</title>
</head>
<body>
<div class="topcoat-navigation-bar">
<div class="topcoat-navigation-bar__item center full">
<h1 class="topcoat-navigation-bar__title">Header</h1>
</div>
</div>
<div class = "content text-input">
<form id = "form" name = "form" action="http://localhost/index.php" method = "post">
<p>Please fill the details.
<p> Name</p>
<input type="text" class="topcoat-text-input" placeholder="text" value="" id = "name" name = "name">
<input id = "submit" type="submit" class="topcoat-button" value = "Submit">
</form>
<script type="text/javascript">
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</div>
</body>
</html>
I can access "name" in php through post by leaving page, So I am not posting php here. Any Help would be highly appreciated. if anybody needs clarification i am here.

While your inputs have an id, they don't have a name attribute. Serialize uses the name to create the key value pairs for the data.
See: http://api.jquery.com/serialize/
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
Change your inputs to:
<input type="text" class="topcoat-text-input" placeholder="text" value="" id="name" name="name"/>

you should put target attribute in youre form so it will look like that:
<form id = "form" name = "form" action="http://localhost/index.php" method = "post" target="some_name">
and to put "some_name" as an iframe
<iframe id="some_name" name="some_name" style="display:none position:absulote; z-index:-100"></iframe>
that should do the job

Change the script part with this piece of code.... you need to call ev.preventDefault(); before ajax call....
<script type="text/javascript">
var frm = $('#form');
frm.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
});
</script>

I think there may be some mistake in javascript file <script src = "js/jquery.js"></script>. I have tried your code. Its working when I changed the javascript file. plz try with <script src = "http://code.jquery.com/jquery-1.11.0.min.js"></script> It has been worked for me.

I don't know how but this worked for me.Thanks for answers.
the html form worked when i place it at the same directory where index.php resides(ie at localhost:/).
if it is at another place It didn't work.I don't know why but I am figuring it out.

What you need is in here
http://malsup.com/jquery/form/
It submits the whole form and won't leave the current page.

Related

How can I display a php response with a button click without leaving the page? [duplicate]

This question already has answers here:
Update div with jQuery ajax response html
(3 answers)
Closed 3 years ago.
How can I echo the response of a php script on my current page when I click on a button? I know how I can run a php script without leaving the page. The problem is that the response (echo) is not shown on the page where the user is. My current solution is to call the current site from a form and handle the response like that but is it possible to do that without refreshing the page?
<?php
if (isset($_POST['message'])) {
echo $_POST['message'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sandbox</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<form class="form" action="index.php" method="post">
<input type="text" class="textfield" name="message" id="message">
<input type="submit" class="button" value="send">
</form>
</body>
</html>
Normally I would use Javascript for tasks like that but in this case I have to use php. I also tried to make a JS post request against a php file but this solution felt not "clean".
You can use Ajax form submit script using PHP like.
<?php
if (isset($_POST['message'])) {
echo $_POST['message'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sandbox</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles/style.css">
</head>
<body>
<div class="alert-msg"></div>
<form class="form" id="myForm" action="index.php" method="post">
<input type="text" class="textfield" name="message" id="message">
<input type="submit" class="button submit-btn" value="send">
</form>
// you can use add this script in body tag
<script type="text/javascript">
// ------- Mail Send ajax
$(document).ready(function() {
var form = $('#myForm'); // contact form
var submit = $('.submit-btn'); // submit button
var alert = $('.alert-msg'); // alert div for show alert message
// form submit event
form.on('submit', function(e) {
e.preventDefault(); // prevent default form submit
$.ajax({
url: 'index.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alert.fadeOut();
submit.html('Sending....'); // change submit button text
},
success: function(data) {
alert.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
submit.attr("style", "display: none !important");; // reset submit button text
},
error: function(e) {
console.log(e)
}
});
});
});
</script>
</body>
</html>
The only way to get a response from PHP (or anything else that executes on the server) is to make an HTTP request to it.
If you don't want to leave the current page then your options are:
Set target="_blank" in the form to open the response in a new tab or window
Add an iframe to the document and set target="name_of_iframe" to open the response in the iframe
Make the HTTP request with JavaScript and display the response using DOM manipulation. This technique is known as Ajax and the Internet is awash with tutorials on it.
You can use the Ajax for this.
Add jquery library in your code and than write below ajax code:
$('body').on('click', '.button',function(){
$.ajax({
type: 'POST',
url: 'post.php',
})
.done(function (response) {
$('.message').html(response);
});
return false;
});
In post.php file write below code:
<?php
if (isset($_POST['message'])) {
echo $_POST['message'];
}
Using Jquery and its ajax function and without form :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<input type="text" class="textfield" name="message" id="message">
<button id="btn_callajax">Envoyer</button>
<p id="getajaxresponse"></p>
<script>
$document).ready(function(){
$("#btn_callajax").click(function(){
var my_msg = $("#message").val();
$.ajax({
url : 'getajaxcall_respback.php',
type : 'POST',
data : 'my_msg='+my_msg,
dataType : 'html',
success : function(htmlresponse, statut){
$("#getajaxresponse").html(htmlresponse);
},
error : function(responses, statut, error){
}
});
});
});</script>
In the getajaxcall_respback.php file :
if( isset($_POST['my_msg'])
{
$mesg = $_POST['my_msg'];
//get your database request ?
echo "send your html code back to your index.php";
}

how to redirect other url from form action

I have created a form in which on submitting name my url is getting redirected but i want after form action it should get redirect to my mobile validation page. after putting the code, i want it to show the offer page. I am not able to write ajax. my function is not getting called. here is what i have tried till now
http://plnkr.co/edit/3DA7YGb58BgcVcD0d10f?p=preview
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form name="msform" action="another.html" method="post" id="msform">
<input name="name" type="text" placeholder="First Name" />
<input class="bl" id="submitbl" type="submit" value="Submit" />
</form>
<script type="text/javascript">
$("#submitbl").click(function(){
if($("#msform").valid() === true) {
var name = $('input[name|="name"]').val();
//use ajax to run the check
$.ajax({
type : 'POST',
url : 'mobile.html',
success: function(responseText){
resp = responseText.trim().substring(14);
if(resp == 'qualified') {
url_redirect({url: "offer.html",
method: "post",
data: { "fname": name }
});
}
}
});
}
});
</script>
</body>
</html>
For this you can do something like:
write a jQuery onsubmit function and trigger click event for submit button.
$("#msform").on('submit',function(){
$("#submitbl").trigger('click');
});
Or
submit your form through ajax and in success function redirect to mobile.html

Use JQuery to get data from JSON file

Overflow!
I'm currently working on a little application I have to finish for school monday. I didn't have a lot of time to make something big. So I decided, why not retrieve information of Steam's Web Api and get the stats of players.
The url to the steam api:
http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=76561198263871727
The last parameter &steamid= represents the id of the player. Now I have found out how to get the steamid into a variable, but when trying to add the id to the rest of the url (http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=id should be here and fetching the data with the Ajax.getJson method.. It just doesn't work.. I'm for very experienced with JSON btw.. Can someone help me out with this?
My Web Page:
<!DOCTYPE html>
<html lang="en">
<head>
<!--Meta Information-->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--JQuery Mobile-->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!--FontAwesome-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<!--Custom Styles-->
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div data-role="page" id="index">
<div data-role="header">
<h1>CS:GO Stats</h1>
</div>
<div data-role="main" class="ui-content">
<div class="search">
<label for="search">Enter SteamID:</label>
<input type="search" name="search" id="inputSearch" />
<input type="submit" id="butSearch" data-inline="true" value="Search SteamID">
</div>
<div id="result">
</div>
</div>
</div>
<!--getSteamUserId function-->
<script src="js/getSteamUserId.js"></script>
</body>
</html>
My Javascript Code:
$(document).ready(function() {
$('#butSearch').click(function(event) {
var input = $('#inputSearch').val();
$.getJSON( "http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=" + input, function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "#result" );
});
})
})
Now what I want is to get the stats data from the JSON file into my web page. Would anyone know how to do this? I can also see the JSON is not only a flat JSON file.. Like it has different layers (if that's a good explenation)..
Thanks in advance!
Work with jsonP like here:
$.ajax({
url: url,
dataType: 'JSONP',
type: 'GET',
jsonp: 'jsonp',
success: handler
});
Working example here
I'm not entirely sure about the first part. It gives me an error which after googling led me to "No 'Access-Control-Allow-Origin' header is present on the requested resource" which advises using CORS. Error:
XMLHttpRequest cannot load http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=&76561198263871727. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.
Once you have the JSON it's easier. If it's stringified you can turn it into a javascript object with
steamObject = JSON.parse(steamJsonData);
and then navigate through it like a normal javascript object. Cycle through playerstats.stats[i] with a for loop and you can add the data to your page using normal DOM manipulation.

Cannot access scripts when return to main page of Jquery site

Ok I'm reposting this from the start. I'm just so frustrated with this I'm about to just give up on JQM all together. This shouldn't be this hard.
My site structure:
OUI/
index.php
js/
pages/
images/
On my index.php page I have just a two line form for login I'm at http://localhost/~me/OUI/:
<? session_start();
?><!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=false,initial-scale=1;">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="stylesheet" href="js/jquery.mobile-1.4.0.min.css">
<link rel="stylesheet" type="text/css" href="css/jqm-datebox.min.css" />
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="js/jquery.mobile-1.4.0.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jqm-datebox.comp.datebox.min.js"></script>
<script src="js/mainsite.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/main.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>OUI CHEF</title>
</head>
<body style="background-image:url(media/kitchen.jpg)">
<div data-role="page" id="loginarea">
<div data-role="content" id="maincontentarea2">
<img src="media/OUIChef.png" style="margin-top:75px" id="mainimage">
<div data-role="fieldcontain" class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" style="text-align:center" placeholder="Username"/><BR>
<label for="username">Password:</label>
<input type="password" name="password" id="password" value="" style="text-align:center" placeholder="Password"/>
</div>
<div style="text-align:center">
DO LOGIN
</div>
</div><!-- /page -->
</div>
</body>
</html>
So when I hit the login button it take me to my options.php page vi the following function:
function doLogin(){
$.ajax({
type: "POST",
url: "functions/checklogin.php",
data: {
usrnm: $('#username').val() , passwd: $('#password').val()
}
})
.done(function( msg ) {
if(msg.match(/YES/)){
$('#username').val('');
$('#password').val('');
$("body").pagecontainer("change","pages/options.php",{ });
}
else
{
alert(msg);
}
});
}
In the URL bar I now have http://localhost/~me/OUI/pages/options.php and everhthing in the page is working well. I have the signout button. in the code which calls
OPTIONS.PHP:
<div data-role="page" id="optionspage">
<div data-role="header">
Sign Out
<h1>MAIN</h1>
</div>
<div data-role="content" id="options1">
<? if($_SESSION['role']=='A'){?>
ADMIN PAGE
ORDER SETUP PAGE
<? } ?>
PRODUCTION
MENU / RECIPE PAGE
</div><!-- /content -->
</div>
this calls the JS:
function doSignout(){
$.ajax({
type: "POST",
url: "../functions/signout.php",
data: { }
})
.done(function( msg ) {
$('body').pagecontainer( "change", "#loginarea",{});
});
}
I can never get the link to the signout page to link correctly. If I put the double dots which should be correct from the "pages" folder I get it trying to link to
http://localhost/~me/functions/signout.php
and if I remove the double dots I get
http://localhost/~me/OUI/pages/functions/signout.php
both which are 404 errors.......this is BUNK in my book. the ".." is actually removing two directories..not just one.
What is happening? PLease help
As we don't see you log-in function, I'm assuming it looks something like the following?
$.ajax({
type: "POST",
url: "../functions/signin.php",
data: {}
})
If that is the case how does "../functions/signin.php" find it's mark when you are residing at /OUI/ initially — surely it would need to be "functions/signin.php" when you are on your home page.
Simply put I'm guessing your sign-in code is different on the homepage initially, and then after loading subsequent pages via ajax your sign-in code is getting overwritten or modified with code that is designed to work with a "../" prefix on deeper pages... and this isn't getting rectified when you switch back to the home page.
Basically you need to rewrite your code to detect how many folders deep the current URL is at and request your ajax files accordingly... either that or set one global variable (that is easily updatable) that keeps a full domain path to prefix all ajax urls with. i.e.:
var ROOT_URL = 'http://localhost/OUI/';
Depending on what you want to use this path can be generated by either PHP or JavaScript, PHP is more reliable — as in the end user does not require JavaScript — but it can be confused when hosted behind proxies and shared hosts.
var ROOT_URL = 'http://<?php echo $_SERVER["HTTP_HOST"]; ?>/OUI/';
var ROOT_URL = 'http://' + window.location.host + '/OUI/';

jQuery/AJAX execution of PHP not working

I am trying to use jQuery/AJAX to run a PHP file on a server. This PHP simply adds a row with some constants to a database. Here is my code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Submit Application</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("http://.../submitApp.php");
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="javascript:doSomething()">
<p>
<label for="programName"></label>
<input type="text" name="programName" id="programName" />
</p>
<p>
<label for="greQuant"></label>
<input type="text" name="greQuant" id="greQuant" />
</p>
<p>
<label for="greVerbal"></label>
<input type="text" name="greVerbal" id="greVerbal" />
</p>
<p>
<input type="submit" name="submitApp" id="submitApp" value="Submit" />
</p>
</form>
</body>
</html>
Upon pressing the submit button on the above form, nothing seems to happen. I should mention I am running this locally via DreamWeaver. I know for a fact that the code is reaching the JavaScript method and that the PHP code is functional. Anyone know what's wrong?
Use POST instead of GET to do this work.
function doSomething() {
var programName = $('#programName').val();
var greQuant = $('#greQuant').val();
var greVerbal = $('#greVerbal').val();
$.ajax({
type: "POST",
url: "submitApp.php", //URL that you call
data: { programName: programName, greQuant:greQuant, greVerbal:greVerbal } //var in post: var from js
}).done(function(msg) {
alert(msg);//change to something to indicate action
}
});
and with your php, handle like this
<?php
$programName = $_POST['programName'];
$greQuant = $_POST['greQuant'];
$greVerbal = $_POST['greVerbal'];
//do something important
?>
this is just a simple example, you need apply some security to this php code

Categories

Resources