I have seen many posts close to this but not this specifically so I will still ask it. I have a simple webpage that I am using to pass a value from to a server and then based on the value pass a response to the original webpage. Right now for testing purposes I am just using an alert for the final value.
My client side code is as follows submitAjax.php:
<!DOCTYPE html>
<html>
<head>
<script src="./jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$("#thisForm").submit(function () {
processData();
});
function processData() {
$.get('ajaxSubmit.php', function(data) {
alert(data);
});
}
});
</script>
</head>
<body>
<form method="get" id="thisForm">
<tr>
<td><input type=text name=box ></td>
<td><input type=submit value=Add></td>
</tr>
</form>
</body>
</html>
Server side ajaxSubmit.php:
<?php
$value=$_GET["box"];
if ($value==2){
echo "This is the returned text.".$value;
}else{
echo "not sent";
}
?>
As you can see from the code, I am trying to print the text "This is the returned text.2" as the output but when I enter "2" into the textbox my failure case of "not sent" is returned.
Any help would be great. I am very very new to all things javascript so please point out anything else I am doing incorrectly as well.
You're not passing anything when you're requesting ajaxSubmit.php.
$.get('ajaxSubmit.php?box=' + $("[name='box']").val(), function(data) {
alert(data);
});
So you want to request, ajaxSubmit.php?box=value, where value is the value of the html element named box.
Related
I've looked up a lot of tutorials and poked around on here but haven't found anything that addresses my specific issue. I am guessing I have a syntax error or logic error somewhere in my code. My issue is that whenever I submit the form, I get directed to the test.php page. The php is working correctly as it is returning the correct result but I just want that to run and display the submitted form information underneath. Any help would be greatly appreciated.
index.html
<html>
<head>
<title>Computer swap form</title>
</head>
<body>
<form method = "post" action = "test.php" id="computerForm">
Serial Number: <br>
<input name="serialnumber" type="text">
<button id = "sub"> Submit </button>
</form>
<!--display the response returned after form submit -->
<span id ="result"></span>
<script type="text/javascript" src = "https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>
test.php
<?php
$sn = $_POST['serialnumber'];
if(!isset($sn))
{
echo "error serial number not set";
}
else {
echo "$sn successfully saved";
}
?>
my_script.js
$("#sub").click( function() {
$.post( $("#computerForm").attr("action"),
$("#computerForm").serialize(),
function(info){ $("#result").html(info);
});
});
$("#computerForm").submit( function() {
return false;
});
To achieve what you require put all your logic in the submit handler, and call preventDefault() on the event argument provided to the handler function:
$("#computerForm").submit(function(e) {
e.preventDefault();
$.post(this.action, $(this).serialize(), function(info) {
$("#result").html(info);
});
});
In the below Javascipt code I am sending data to a page named "book.php".It is succesfully sending the data through post method(because I am getting the alert) but when I open book.php to display the recieved data,It is not showing anything.
<script type="text/javascript">
$(document).on("click", ".open-AddBookDialog2", function (f){
var train_date=$(this).data('id');
$.ajax({
type: 'post', // the method (could be GET btw)
url: 'book.php', // The file where my php code is
data: {
'train_date': train_date // all variables i want to pass. In this case, only one.
},
success: function(data) { // in case of success get the output, i named data
alert("success"); // do something with the output, like an alert
}
});
});
</script>
Book.php is showing output as nothing.
Is there any way I can open the same page while sending post data to it?I want to use that $_POST variable to sql.
book.php-
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<style>
body {
background-image: url("rail.jpg");
background-color: #cccccc;
background-size: 100% auto;
background-repeat: no-repeat;
}
</style>
</head>
<body>
<p>
<?php
if(isset($_POST['train_date'])) { //if i have this post
// print it
echo $_POST['train_date']; }
else{
$var="nothing";
echo "nothing";
}
?>
</p>
</body>
</html>
Don't use XHR/Ajax. A simple solution is to create a hidden <form method="post"> element, create likewise hidden input fields for your data (in this case just train_date) fill it with values and then trigger the form submission using javascript. The browser will then be redirected as you request.
Example:
JS:
$(document).on("click", ".open-AddBookDialog2", function (f){
var train_date=$(this).data('id');
var hidden_form=$("#hidden-form");
var hidden_input=$("#hidden-form-input");
hidden_input.val(train_date)
hidden_form.submit()
});
HTML:
<form method="post" id="hidden-form" style="display:none" action="book.php">
<input id="hidden-form-input" name="train_date" />
</form>
Use ajax to send variable to php. In php stock that variable in a session (search around, is simple) then in your ajax success do a redirect: How to redirect to another webpage? . In php you will have now your var stocked in $_SESSION. Do what you need with it, manipulate the flow of execution with some if(isset()).
Before getting stuck here, I had a look at the implementation of question asked here
I tried implementing the code and wish to insert data at checkbox click inside MySQL database. It might have been done already if I was supposed to insert data on form submission but I have to individually insert 8 bit data by turning their flag ON/OFF at checkbox tick.
I tried doing it, but don't know where exactly I am going wrong.
Below are the code snippets :
PHP CODE insertIntoAbbaa.php :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$updateCon = mysqli_connect("192.168.0.7", "uzer", "password", "remondb");
if (!$updateCon) {
die("not able to cconnect" . mysqli_error());
}
if(isset($_POST['firstOutputData'])){
$firstData = mysqli_escape_string($updateCon, $_POST['firstOutputData']);
if(!$firstData){
echo "nopes !";
}
$updateValue = mysqli_query($updateCon, "INSERT INTO update_abbaa(rfu_id, upadate_index, update_value) values(1,'$firstData',1)");
if(!$updateValue){
echo "nopes !";
}
mysqli_close($dbget);
echo "Saved !";
}
else{
echo " nothing happened ! ";
}
?>
</body>
Below is the onclick event I am calling on checkbox tick :
HTML onclick code snippet :
<span class="toggle">
<input type="checkbox" onclick="onOffFunction1()" id="onoff1">
<label data-off="Off" data-on="On"></label>
</span>
Now, I am trying to call the above mentioned function in javascript as follows :
function onOffFunction1() {
var firstCb = document.getElementById("onoff1");
if (firstCb.checked) {
document.getElementById("firstBitData").innerHTML = "1";
document.getElementById("firstBitData").style.backgroundColor = "green";
var firstOutputData = "1";
$.ajax({
url: "insertIntoAbbaa.php",
type : "POST",
data : "firstOutputData"+firstOutputData,
success: function(data)
{
alert("success !" + data);
}
});
}
The output shows me "nothing happened" message as I have written in PHP script
Please go easy on me I am a beginner !
The error message 'Nothing happened' is caused because this check:
if(isset($_POST['firstOutputData']))
is false. That means there is no value inside $_POST with index 'firstOutputData'. The first place you need to look for an error like that is your AJAX call and if you pass the parameter correctly, which you don't.
This:
data : "firstOutputData"+firstOutputData,
should be:
data : {firstOutputData: firstOutputData}
I'm learning how to post data to server.I want to click on a link and post its data to the server in the same page, do I need to have a form to do that? is it possible to post data without having a form? I cannot see the result in php should I have any success or done function here to have the results? I also have tried Last example of Jquery manual and there is no content div to see any results and so I couldn't figure it out.
I do not want to show data and append it in the html I want to see it in $_POST and if it is not possible to show it in the same page I am ok with that all I want is to see $_POST can have the data from JQUERY
<?php
if(isset($_POST["name"]))
echo $_POST["name"];
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(){
$.post("newfile5.php",
{
name: $("#link").val()
}
});
$('form#myform').submit();
});
</script>
</head>
<body>
<form id="myform" action="newfile5.php" method="POST">
<a id="link" href="" value="A">Send</a>
</form>
</body>
</html>
PS:I updated upon answers, and still not result:
<?php
if(isset($_POST["name"]))
echo $_POST["name"];
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(e){
e.preventDefault();
$.post("newfile5.php",
{
name: $("#link").data("value")
},
function(data)
{
// Whatever is returned by newfile5.php
}
});
});
</script>
</head>
<body>
<a id="link" href="" data-value="A">Send</a>
</body>
</html>
I expect to see $_POST['name'] having the value A, just this
Use data-attr to store data.
<a id="link" href="" data-value="A">Send</a>
Use
console.log($("#link").data("value"));
to fetch it.
So your code becomes
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(e){
$("#disp_name").html($("#link").data("value"));
e.preventDefault();
$.post("newfile5.php",
{
name: $("#link").data("value")
},
function(resp)
{
console.log(resp); // Whatever is returned by newfile5.php
}
});
});
</script>
</head>
<body>
<div id="disp_name"></div>
<form id="myform" action="newfile5.php" method="POST">
<a id="link" href="" data-value="A">Send</a>
</form>
</body>
</html>
and dont use $('form#myform').submit();
and to fetch data in PHP, use
$name = $_POST["name"];
I want to click on a link and post its data to the server in the same page, do I need to have a form to do that?
No. You can post the data without having a form.
EDIT
To answer the question after edit (if I well understand it):
Seems to me actually like a X-Y problem but the answer is - No .
PHP isn't able to interfere with the client browser. The AJAX is only a "bridge" between the server (PHP) and the page that has been fully rendered.
(you may want to read about WebSockets)
Fully rendered page have no access to the PHP variables anymore (doesn't matter if it's jQuery or any other client-side language). When connection to the server is completed (page fully rendered), all the PHP named variables and methods cease to exist. They could be set only at the time when the page is being rendered (and that's the only way to get these two languages to work together at the same time), eg:
<script>
var myData = "<?php echo 'something'; ?>";
</script>
Basically, the $.post is used to communicate with the server. If that's not required, you can access the data within the page itself and $.post is not even necessary.
You have an trigger event (click). You set the event to determine when an action should be taken and what is supposed to happen then. Whether it's an AJAX request or anything else.
If the AJAX is required:
var myData = '';
$("#link").click(function(e){
$.post(
"newfile5.php",
{name: $("#link").attr('value')},
function( data ) {
myData = data;
doSomething();
// do something else with the data here. ...
}
);
});
If there's no need to post any data:
var myData;
$("#link").click(function(e){
myData = $("#link").attr('value');
doSomething();
});
The method:
function doSomething(){
if(myData){
alert(myData);
}else{
// ...
}
}
in php access the $_POST variable
Edit:
First of all, you are combining two different ways and doing them wrong at the same time. You are making an AJAX request, and then sending a normal HTTP request without a value. Both wrongs, try this example, it will make an Ajax Post Request and show you the result in an Alert.
<?php
if(isset($_POST["name"]))
echo $_POST["name"];
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(){
$.post("newfile5.php",
{
name: 'Some Name'
}, function(data) {
alert(data)
}
});
});
</script>
</head>
<body>
<form id="myform" action="newfile5.php" method="POST">
<a id="link" href="" value="A">Send</a>
</form>
</body>
</html>
<?php
if(isset($_POST["name"])) {
echo $_POST["name"];
exit; //So we don't show the HTML in $.post response
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#link").click(function(){
$.post("newfile5.php",
{
name: $("#link").attr('data-value');
}).done(function(response) {
//Handle the response, just alerting for testing
alert(response);
});
//No need
//$('form#myform').submit();
//Event to see the response
});
});
</script>
</head>
<body>
<!--anchors don't have value attributes, use data- attribute-->
<a id="link" href="" data-value="A">Send</a>
</body>
</html>
What I am trying to do is retrieve JSON data from an online web service that searches and finds a certain string in a MySQL database and display it using Javascript on an HTML page.
What I am struggling with is actually displaying the resulting data.
The relevant areas of my HTML page looks like this:
<form onSubmit="results()">
<fieldset>
<label for="area">First digits of postal code:</label>
<input name="area" type="text" maxlength="4" placeholder="AB12" required />
<input type="submit" value="Search" name="search" />
</fieldset>
</form>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="cordova-2.3.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
function results(){
$.ajax({
url: 'http://www.foobar.com/cp/index.php?area=AB12',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<h1>'+item.location+'</h1>'
+ '<p>'+item.id+'</br>';
output.append(place);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
};
</script>
<div id="place">
<h3>Places near your location</h3>
</div>
The page for the GET data is http://www.foobar.com/cp/index.php with the search variable 'area'. Test sample is ?area=AB12.
It seems that this service is not correctly wrapping the JSON object in parentheses so it doesn't work as JSONP.
See: http://www.entertainmentcocktail.com/cp/index.php?area=AB12&jsoncallback=TEST
It returns:
TEST[{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]
while it should return:
TEST([{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]);
You won't be able to use it because it is not valid JSONP.
UPDATE:
Answering more info from the comment - if you control the server-side script then try changing:
while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . json_encode($records);
to:
while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
and see if that works.
UPDATE 2:
Answering another comment. Do you actually initialize the output variable? For example with something like this at the beginning:
var output = $('#place').append('<div/>');
Do you actually call your results function? It must be called with:
results();
or registered somewhere as an event handler, using the jQuery way:
$('form').submit(results);
but then add:
return false;
to the end of the results function to prevent the page from being reloaded.
See this demo: http://jsbin.com/uziyek/1/edit - it seems to work.
Another problem:
There seems to be another problem with your code, that the area=AB12 parameter is hardcoded into your URL. What you should do instead is get the value from the form and send that.
You implemented JSONP incorrectly. You need to generate a function call, i.e. the response should be foo(<json here>); not foo<json here>.
It is trivial to fix:
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
Another problem is that you are not preventing the form submission, i.e. when you submit the form, the page refreshes. You have to prevent that. Better bind the event handler with jQuery and don't use inline event handlers:
<form id="myForm">
and
$(function() {
$('#myForm').submit(function(event) {
event.preventDefault(); // <-- prevent form submission
// Ajax call here
});
});
DEMO