This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
In the code added here, I pass on value from PHP parameter to JS parameter:
Both parameters are called 'stv'.
I wonder how do I do the exact opposite?
Thanks!
<script>
var stv="<?php echo $stv; ?>";
</script>
send a request with ajax using jquery if using jquery already in document.
If you don't have Jquery added, you can add it ath the end of your html body using a script tag and getting the download adress from google:
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
function ajax(value) {
var x = {
'info': value //data to send can be json or something else
};
$.ajax({
url: 'index.php', //page where to send
type: 'POST', //type of request
data: x, // data to send
success: function(data) { //what happends when request is success
try {
getAjPromise(JSON.parse(data));
} catch (e) {
console.log("error");
}
}
});
}
in PHP you check if there is a $_POST['info'], get the value and do something
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 4 years ago.
I have php page which contains two javascript functions like this:
function PregledDokumenta(id)
{
var info = id.split('-');
var vrdok = info[0];
var brdok = info[1];
$.ajax({
type: "POST",
url: "../Php/Dokument/Pregled.php",
data: { vrDok: vrdok, brDok: brdok },
success: function(returnedData)
{
document.getElementById('Content').innerHTML = returnedData;
<?php
$_SESSION['vrDok'] = vrdok;
$_SESSION['brDok'] = brdok;
?>
<?php
$a = $_SESSION['vrDok'];
echo("alert($a);");
?>
}
});
}
function UnosNoveStavke()
{
var vrdok = <?php echo($_SESSION['vrDok']);?>;
var brdok = <?php echo($_SESSION['brDok']);?>;
<?php
$a = $_SESSION['vrDok'];
echo("alert($a);");
?>
$.ajax({
type: "POST",
url: "../Php/Dokument/IzborRobe.php",
data: {vrDok: vrdok, brDok: brdok},
success: function(returnedData)
{
document.getElementById('Content').innerHTML = returnedData;
}
})
}
So when i load page and press button i run PregledDokumenta(id) function. In there i pass some values from id of element and then i echo back some other text and buttons as you can see i alert $_SESSION['vrDok'] to see if it is assigned and it returns value. Then when i click button (about 10 sec after running first function) that i echoed back from first function i run second UnosNoveStavke function. There you can see I again alert to see if $_SESSION return value but it return undefined. Why is that happening?
You are very confused regarding how JavaScript and PHP communicate with each other!
For example, with the following code, you are effectively trying to assign JavaScript variables, which you get from an AJAX request, into PHP sections:
<?php
$_SESSION['vrDok'] = vrdok;
$_SESSION['brDok'] = brdok;
?>
This can't work, because all PHP expressions are evaluated before the page even loads.
If you need to save these values in PHP sessions, you have to do it either in the file the AJAX request is sent, in your case Pregled.php, or a PHP file that you include in it.
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
I'm trying to print through innerHTML some data got with the ajax call, but the global array elements it is not accesible in the done() promise.It is indeed undefined.
Why does that happen?
<html>
<head></head>
<body>
<script src ="jquery.min.js"></script>
<script>
$(document).ready(function(){
var elements = document.getElementsByClassName("wind");
for(i=0;i<elements.length;i=i+1){
$.ajax({
type:"GET",
url:"http://api.openweathermap.org/data/2.5/weather?q="+elements[i].innerHTML+"&appid=7876b25bdca1397553df39ef3ea05fd1",
dataType: "json"
}).done(function(data){
elements[i].innerHTML = data.wind.speed; //elements[i] is undefined
});
//elements[i].innerHTML here elements[i] is OK but I don't have access to "data"
}
});
</script>
<div class="wind">Venice,it</div>
<div class="wind">Rome,it</div>
</body>
Try using the success setting rather than done. This will activate when the request is successful and it returns the data.
$.ajax({
type:"GET",
url:"http://api.openweathermap.org/data/2.5/weather?q="+elements[i].innerHTML+"&appid=7876b25bdca1397553df39ef3ea05fd1",
dataType: "json",
success: (function(data){
elements[i].innerHTML = data.wind.speed;
}),
});
This question already has answers here:
How can I "reset" <div> to its original state after it has been modified by JavaScript?
(10 answers)
Closed 6 years ago.
I have a php file which contains a div element with id= containerbox.
<div id=containerbox>
<button id="buttonme" type="button">click me</button>
</div>
<script>
$("#buttonme").click(function(){
jQuery.ajax({
type: 'POST',
url: 'testone.php',
success: function (data) {
response = jQuery.parseJSON(data);
if (response.status == 'error') {
erroroccur(response);
}
}
});
})
function erroccur(abc) {
alert(error);
//here i want something that only Refreshes/Reloads the containerbox
}
</script>
testone.php
<?php
//...something
$response=Array(
"status"=>'error'
);
return json_encode($response);
?>
it contains one function which makes an ajax call and depending on the response recieved it decides if it is an error.Whenever it recieves an error in the response it fires a function which need to show an alert box and reset the Div element to the way it was when i first came to that page.Can this be achieved?
Note: I know nothing will change there but just for the sake of simplicity i have used this example
What about :
// keep a reference to the initial html in your div
var initialState = $("#containerbox").html()
/* ... */
function erroccur(abc) {
alert(error);
// revert the div content to its initial state
$("#containerbox").html(initialState)
}
This question already has answers here:
Send JavaScript variable to PHP variable [duplicate]
(3 answers)
Closed 9 years ago.
In my index.php, I have an update button as below.
<form action="update.php" method="post" >
<button type="submit">Update</button>
</form>
I have defined a javascript function to override the default form action. The javascript function is as below.
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
alert("HI");
$.ajax({
type: 'post',
url: 'update.php',
data: {
source1: "some text",
},
success: function( data ) {
console.log( data );
}
});
});
});
</script>
After I click on the update button, I am getting the alert. However, I am not redirected to update.php page as expected. I am trying to send some values in the ajax request which can be used for processing in the update.php page.
You are not redirected because PHP redirects do not affect the browser when run as an AJAX call. You'll need to specify a JavaScript redirect in the success function:
$.ajax({
type: 'post',
url: 'update.php',
data: {
source1: "some text",
},
success: function( data ) {
document.location.href = 'update.php'
}
});
However, I don't believe that this is what you want. You seem to want to add new form data on submitting the form, in which it might be better to prevent the default behaviour, add any additional data with hidden input fields, and then re-submit the form:
$(function ()
{
$('form').submit(function (e)
{
if ($(this).is(':not([data-submit="true"])'))
{
$('form').append('<input type="hidden" name="foo" value="bar">')
$('form').data('submit', 'true').submit()
e.preventDefault()
return false
}
}
)
}
)
</script>
This question already has answers here:
Javascript and PHP functions
(7 answers)
Closed 9 years ago.
In my index.php file, I have a php function "InsertTheRecord" which gets a parameter and insert it into the database. It return 1 if that parameter is inserted successfully otherwise 0.
I have following JavaScript function "InsertRecord" in same index.php from where I want to call php InsertTheRecord function. How can I call php function from JavaScript function?
My JavaScript function:
function InsertRecord() {
var myParameter = 40;
var result = ////call InsertTheRecord(myParameter) //I don't know how to do this?
if result == 1 { //do something}
else { //show error message}
}
php server side scripting language and javascript is client side scripting language
you can do this by ajax call(Jquery)
<div id="yourdiv"></div>
var data ="hello world";
var data2="hello all";
function run(){
$.ajax({ url: 'myscript.php',
data: {'q': data,'z':data2},
type: 'post',
success: function(output) {
alert(output);
document.getElementById("yourdiv").innerHTML += output; //add output to div
}
});
}
myscript.php
<?php
myfun();
function myfun(){
$myvar2 = $_POST['z'];
$myvar = $_POST['q']."how are you?";
echo $myvar."\n";
echo $myvar2;
}
?>
this alert "hello world how are you?"
Try
var result = <?php echo InsertTheRecord(myParameter); ?>
updated after OP's comment
$.ajax
function InsertRecord() {
$.ajax({
type: "POST",
url: "your_php_page.php",
data: "arg1=id&arg2=name",
success: function (data) {
var myParameter = 40;
var result = data;
if result == 1 {} else {}
}
});
}
PHP is serverside,
JS is clientside,
So the PHP works first, after that the JS works dynamically in the browser.
You cannot call the PHP function in runtime. But you can use AJAX which can do that. Check this out: http://www.w3schools.com/ajax/ajax_aspphp.asp
What if you echod the myParameter to a hidden input field and then grabbed it with javascript:
HTML/PHP file:
<input type="hidden" id="myParameter" value="<?php echo InsertTheRecord(myParameter); ?>"/>
In Javascript:
function InsertRecord() {
var myParameter = 40;
var result = document.getElementById("myParameter").value();
if result == 1 { //do something}
else { //show error message}
}
It is not possible
Javascript is client side scripting language where PHP is server side scripting language
But, you can try AJAX methods to get similar results where you can pass variables same as function
as function myfunction(var1, var2 ,....){return var1*var2}
using ajax, you can run a php script externally on button click
$.ajax({key:var},function(result){alert(result)});
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
http://www.tutorialspoint.com/ajax/