I've input some code so that I can measure the current temperature of a location. I have the script which allows my user to check the location but the alert is not working.
<h3> Weather Data </h3>
<form method="POST" action="about.php">
<input type="text" name="city" value= 'city'/>
<input type="submit" name="submit" value="submit" />
</form>
<?php
$city=$_POST['city'];
var_dump($city);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/5e8af95dbdebbd73/geolookup/conditions/forecast/q/UK/<?php echo $city; ?>.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
?>
</script>
The alert should be appearing but nothing is am I doing something wrong.
You have an unnecessary closing php tag before your closing script tag:
}
});
});
?> // this is a problem!
</script>
Related
I'm working on a footer generator.
Which looks like this:
This "preview" button has 2 functions function 1 is posting the values that the user entered in the black box like this :
and the second function is to show me a button(which is hidden by default with css) called "button-form-control-generate" with jquery like this:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Now here comes my problem:
If i click on preview it refreshes the page.. so if i click on preview it shows the hidden button for like 1 second then it refreshes the page and the button goes back to hidden. So i tried removing the type="submit" but if i do that it wont post the entered data like it did in image 2 it will show the hidden button though, but because the submit type is gone it wont post the entered data on the black box.
Here is my code:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" action="">
<option></option>
<option>©</option>
<option>™</option>
<option>®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate"name= "submit">
Generate
</button>
</form>
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
The jquery:
$("button.form-control").click(function(event){
$("button.form-control-generate").show();
});
Already tried prevent default but if i do this the users entered data doesnt show in the preview box. Looks like preventdefault stops this bit from working:
<!-- script for the preview image -->
<div id = "output">
<?php
function footerPreview ()
{
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["companyName"];
$date = date("Y");
echo "<div id='footer_date'>$trademark $date $company </div>";
}
footerPreview();
?>
I heard this is possible with ajax, but i have no idea how in this case i already tried to look on the internet..
if you have a type="submit" inside a form, it will submit the form by default. Try to use <input type="button" instead. Then you can use ajax on the button action, that will run without refreshing the page.
Here's an example of how to use ajax:
function sendAjax() {
var root = 'https://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
$(".result").html(JSON.stringify(data))
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="button" onclick="sendAjax()" value="callAjax" />
<div class="result"></div>
</form>
Add
return false;
to your jQuery-function at the end. With this you can avoid the submit.
Then you need to add an ajax-function, which sends the data from your form to the php-script you already use.
This is just an example:
$.ajax({
url: "YOUR-PHP-SCRIPT"
}).done(function (content) {
// ADD HERE YOUR LOGIC FOR THE RESPONSE
}).fail(function (jqXHR, textStatus) {
alert('failed: ' + textStatus);
});
So you have to do $.ajax post request to the php. Something like this:
<script>
$('.form-control').click(function() {
$.post(url, {data}, function(result) {
footerPreview();
}, 'json');
});
</script>
So footerPreview will be called when your php returns result.
//add in javascript
function isPostBack()
{
return document.referrer.indexOf(document.location.href) > -1;
}
if (isPostBack()){
$("button.form-control-generate").show();
}
you can create an index.php:
<form class ="form" method="post">
<h3>Select your trademark</h3>
<select class="form-control" name="trademark" id="tm">
<option val=""></option>
<option val="©">©</option>
<option val="™">™</option>
<option val="®">®</option>
</select>
<h3>Your company name</h3>
<input class="form-control" type="text" name="companyName" id="cn" placeholder="Your company name" />
<br/>
<br/>
<button class="form-control" type= "submit" name="submit">
Preview
</button>
<br/>
<button class="form-control-generate" name= "submit" id="generate">
Generate
</button>
</form>
<div class="output" id="output">
</div>
<script type="text/javascript">
$('#generate').on('click', function(e){
e.preventDefault();
var companyname = $('#cn').val();
var trademark = $('#tm').val();
$.ajax({
url: 'process.php',
type: 'post'.
data: {'company':companyname,'trademark':trademark},
dataType: 'JSON',
success: function(data){
$('#output').append("<div id='footer_date'>"+data.trademark + " " + data.date + " " + data.company + " </div>");
},
error: function(){
alert('Error During AJAX');
}
});
})
</script>
and the process.php:
<?php
date_default_timezone_set('UTC');
$trademark = $_POST["trademark"];
$company = $_POST["company"];
$date = date("Y");
$array = array(
'trademark' => $trademark,
'company' => $company,
'date' => $date
);
echo json_encode($array);
?>
Be sure that the index.php and the process.php will be under the same folder.. ex.public_html/index.php and public_html/process.php
When the user submits the form, the result should be displayed without page refreshing. The PHP script is also in the same HTML page.
What is wrong withe $.post jQuery?
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#btn").click(function(event) {
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $("#testform").serialize()
);
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform">
<!-- $_SERVER['PHP_SELF'] array -->
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
You need to use event.preventDefault in your javascript
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $( "#testform" ).serialize()
);
});
Yes, you need e.preventDefault. Also, I think these var myname and myage variables are unnecessary since you're serializing the entire form in $.post.
Try this:
$(document).ready(function() {
$("#btn").click(function(e) {
e.preventDefault();
$.post(
"23.php", $("#testform").serialize()
);
});
});
Hope this helps.
Peace! xD
This is my finalized complete code after following your all suggestions. But it is still refreshing when getting results. Let's see if I have made any further error in the code. Thanks for your all helps.
UPDATE! - All these HTML and PHP scripts resides in the same file called 23.php
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform"> <!-- $_SERVER['PHP_SELF'] array -->
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
<input type="submit" name="submit" id="btn"/>
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { //was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
i have created a simple html form with one field and it post to the server side php and the value of the field is saved to a text file.
This is the parts of the code:
Html:
<form action="videorefresh.php" method="POST">
<input name="videolink" type="text" size="70" />
<input type="submit" name="submit" value="Save Data">
</form>
php:
<?php
$open = fopen("video.txt","w+");
$txt = "video.txt";
if (isset($_POST['videolink'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['videolink'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
here everythink works fine!
I want to drive all this through Ajax so the main html form wont refresh.
so here is the html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="./JS/videolink.js"></script>
</head>
<body>
<div id="mainform">
<div id="form">
<div>
<input name="videolink" type="text" id="videolink" size="70">
<input id="submit" type="button" value="Submit">
</div>
</div>
</div>
</body>
</html>
And here is the js:
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#videolink").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'videolink1='+ videolink ;
if(videolink=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "./videorefresh.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
What i do wrong here and it doesnt work?
Please help
I think you want to do is:
var dataString = '?videolink='+ name;//typo videolink
// or better put an id on the form and use serialize()
// var dataString = $('#myform).serialize();
NOT
var dataString = 'videolink1='+ videolink ;
You have the value of the input in name, videolink is undefined
How can I get the results of the result.php into the welcome div using ajax or any other method to prevent loading a new page?
<div id="welcome">
<form action="result.php" method="post">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="">Anyplace</option>
.
.
.
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="">Anything</option>
.
.
.
</select>
<input type="submit" class="button" value="Ok Go!"/>
<input id="current" name="current" type="hidden"/>
</form>
</div>
If you are doing this through AJAX, then there is no need for the <form> codes. The <form> codes are only useful if you are posting to a different page and expecting the view to change/refresh anyways.
Also, using <form> codes in this example will cause the page to refresh (and values inserted by jQuery to be lost) for the additional bit with the "Set value for hidden field CURRENT" button. Not that it likely matters in your real world app, but just FYI.
Ajax goes in your javascript code, and looks like this:
$('#mySelect').change(function() {
var sel = $(this).val();
//alert('You picked: ' + sel);
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'theOption=' + sel,
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END dropdown change event
Note that the data ECHO 'd from the PHP file comes into your HTML document in the success function of the AJAX call, and must be dealt with there. So that's where you insert the received data into the DOM.
For example, suppose your HTML document has a DIV with the id="myDiv". To insert the data from PHP into the HTML document, replace the line: alert('Server-side response: ' + whatigot); with this:
$('#myDiv').html(whatIgot);
Presto! Your DIV now contains the data echoed from the PHP file.
Here is a working solution for your own example, using AJAX:
HTML MARKUP:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').on('click', function(e){
e.preventDefault(); //prevent default action
var ct = $('#city').val();
var dt = $('#date').val()
var ty = $('#type').val();
var curr = $('#current').val();
$.ajax({
url: 'result.php',
type: 'POST',
data: 'ct=' +ct+ '&dat=' +dt+ '&t=' +ty+ '&curr=' +curr,
success: function(response){
$('#welcome').html(response);
}
});
});
$('#mycurr').click(function(){
var resp = prompt("Please type something:","Your name");
$('#current').val(resp);
});
}); //END $(document).ready()
</script>
</head>
<body>
<div id="welcome">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="sumwhere">Anyplace</option>
<option value="anutherwhere">Another place</option>
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="sumthing">Anything</option>
<option value="anutherthing">Another thing</option>
</select>
<input type="submit" id="mybutt" class="button" value="Ok Go!"/>
<input type="submit" id="mycurr" class="button" value="Set value for hidden field CURRENT"/>
<input id="current" name="current" type="hidden"/>
</div>
</body>
</html>
PHP Processor file: result.php
$ct = $_POST['ct'];
$date = $_POST['dat'];
$typ = $_POST['t'];
$cu = $_POST['curr'];
if ($date == '') {
$date = 'Some other date';
}
$r = '<h1>Results sent from PHP</h1>';
$r .= 'Selected city is: [' .$ct. ']<br />';
$r .= 'Selected date is: [' .$date. ']<br />';
$r .= 'Selected type is: [' .$typ. ']<br />';
$r .= 'Hidden field #CURRENT is: [' .$cu. ']<br />';
$r .= '<h2>And that\'s all she wrote....</h2>';
echo $r;
You can do something like this using jQuery Ajax
Use following code inside your head tag or footer
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type='text/javascript>
$('document').ready(function(){ //after page load
$('.button').on('click', function(e){
e.preventDefault(); //prevent default action
$.ajax({
'url': 'result.php',
'type: 'POST',
'success': function(response){
$('#welcome').html(response);
}
});
});
});
</script>
valit's the action="result.php" who makes your page reload
You shloud try to give an id to your form, and using a simple ajax call :
$("#formId").submit(function() {
$.ajax({
url: 'result.php',
success: function(response) {
$("#welcome").setValue(response); // update the DIV
}
});
return false; // prevent form submitting
});
Cheers
me again, i'm really getting into php now i just need to know a few things first. First of all i'm trying to do a postback to a the server without reloading the client page. Here's an example of what i want to do: I have to textboxe, now when the user enters a number into both textboxes and clicks the add button, the total value should be calculated and displayed in the third textbox without reloading the page, i've read a bit on ajax but i'm having trouble implementing it.
<?php
if (isset($_POST["add"]))
{
$val1 = $_POST["val1"];
$val2 = $_POST["val2"];
$result = $val1 + $val2;
}
?>
<html>
<head>
<title></title>
<script src="jquery-1.9.1.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
if ($("#btn").click)
{
var request = $.ajax({
url: "postback.php",
type: "POST",
data: {
val1 : "what goes here?",
val2 : "what goes here?"
}
});
request.done(function(msg) {
$("#log").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
});
</script>
</head>
<body>
<input type="input" name="val1">
<input type="input" name="val2">
<input type="input" name="result" value="<?php echo $result ?>">
<input type="submit" id="btn" name="add">
</body>
</html>
Don't mix your JavaScript and your PHP logic. Separate them.
You need your jQuery POSTing to another file, and in this file, echo out the result of your PHP.
This result will then be placed in the .done() method (although I would use .success(), and you use jQuery / JavaScript to update the contents of your HTML).
By the end of this you should have no PHP whatsoever in your HTML / JS file.
Your PHP Code in test.php
From this, we can see you need to post a val1 and a val2 through, so here is a really basic script.
if (isset($_POST))
{
$val1 = isset($_POST["val1"]) ? $_POST["val1"] : 'No value 1 passed through';
$val2 = isset($_POST["val2"]) ? $_POST["val2"] : 'No value 2 passed through';
if (is_int($val1) && is_int($val2))
{
// They're integers, add them
$result = $val1 + $val2;
}
else
{
// They're strings, append them
$result = $val1 . $val2;
}
echo $result;
}
That is all you need in your PHP.
Your HTML / JS
$(document.ready(function() {
$("#add").click(function(e) {
e.preventDefault();
$.ajax({
url: 'test.php',
type: 'POST',
data: {
'val1' : $("#val1").val(),
'val2' : $("#val2").val()
},
success: function(data, status) {
$("#result").html(data)
}
});
});
});
<div id="result">Result should appear here</div>
<form>
<input type="text" id="val1" name="val2" />
<input type="text" id="val2" name="val2" />
<input type="submit" id="add" name="add" />
</form>
And that's it. Pretty simple. Note, untested, so give it a try.
If you don't want to separate your JS and PHP follow this:
1. You should set your input type as button <input type="button" id="btn" name="add">
2. You should also post add in your ajax call
3. You should get the values from textboxs $('#val1').val()
4. You should stop the code after echoing two values because if you don't, ajax returns the rest of html codes and page contents.
5. And at last you should add the new value to the third input by JavaScript, not php because it's ajax and the page is not going to reload.
Try this:
<?php
if(isset($_POST["add"])){
$val1 = $_POST["val1"];
$val2 = $_POST["val2"];
$result = $val1+$val2;
echo $result;
die();
}
?>
<html>
<head>
<title></title>
<script src="jquery-1.9.1.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btn").click(function(){
var request = $.ajax({
url: "postback.php",
type: "POST",
data: {
val1 : $('#val1').val(),
val2 : $('#val2').val(),
add : "ok"
}
});
request.done(function(msg) {
console.log(msg);
$("#result").val( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
</head>
<body>
<input type="input" id="val1">
<input type="input" id="val2">
<input type="input" id="result" value="">
<input type="button" id="btn" name="add">
</body>
</html>
You need to return the result of
$result = $val1 + $val2;
use
echo $result;
exit;