This is my code below for page.php file.
<?php session_start(); ?>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/jquery.colorbox.js"></script>
<script type="text/javascript" src="js/new-landing.js"></script>
<script type="text/javascript">
var ans1 = "home";
function aa(){
$.post("ajax.php", { "ans": "test" }, function(data){
alert("Posted");
}, "html");
};
</script>
<a href="#" id="q1" onClick="javascript:aa();" >click</a>
and this is where i want to see if my data is posted.
<?php
session_start();
$te = $_POST['ans'];
$_SESSION['demo'] = $te;
echo "<pre>".print_r($_SESSION,'/n')."</pre>";
?>
when i click the anchor tag. the alert box is shown. but when i refresh the ajax.php page. it shows an error..Notice: Undefined index: ans in ajax.php on line 3
and the print of session is also empty.
Array(
[demo] =>
)
but when i refresh the ajax.php page. it shows an error
It sounds like you want to set the session variable when a value is posted, and get the session variable otherwise:
<?php
session_start();
if (isset($_POST['ans'])) {
$te = $_POST['ans'];
$_SESSION['demo'] = $te;
}
echo "<pre>".print_r($_SESSION,'/n')."</pre>";
?>
$.post and $.get are just shorthand versions of the more structured $.ajax(), so I prefer using the latter. The additional structure keeps me straight.
Since you are using jQuery anyway, I would re-structure your code like this:
$('#q1').click(function() {
var test = "Hello there";
$.ajax(function() {
type: "POST",
url: 'ajax.php',
data: 'ans=' +test+ '&anothervarname=' + anothervarvalue,
success: function(recd_data) {
alert('Rec'd from PHP: ' + recd_data );
}
});
});
Note that the data: line is for example purposes and does not match with your code -- just showing you how to pass variables over to the PHP side.
Of course, the above includes removing the inline javascript -- never a good idea -- from your anchor tag HTML, thus:
<a href="#" id="q1" >click</a>
Also, on the PHP side, you can verify that things are working by adding a test at the top. Matching with the data: line in the example AJAX code, it would look like this:
ajax.php
<?php
$a = $_POST['ans'];
$b = $_POST['anothervarname'];
$response = '<h1>Received at PHP side:</h1>';
$response .= 'Variable [ans] has value: ' . $a . '<br>';
$response .= 'Variable [anothervarname] has value: ' . $b . '<br>';
echo $response;
Important: Note the use of echo, not return, to send values back to the AJAX script.
Also note that you must deal with the stuff returned from PHP in the AJAX success: function ONLY. If you need access to that data outside of the success: function, then you can stick the data into a hidden <input type="hidden" id="myHiddenInput"> element, like this:
success: function(recd_data) {
$('#myHiddenInput').html(recd_data);
}
Here are some additional examples of simple AJAX constructions:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
Related
I'm new into php and I am trying to call code from another file.
I try to use ajax to so, because later I would like to add parameters. But unfortunattely for me nothing appen when I click on my button.
I have a button in my file admin.php that is written like this:
<button onclick="clickMe()"> Click </button>
And in the same file I have my ajax code in script balise:
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: test() {
alert('ok');
}
error : test(){
alert("error");
}
});
}
</script>
And here is the code that I'm trying to call in my ajax, the function test in the file delete.php:
<?php
function test() {
echo "Hello the World! ";
}
?>
I wondering if I maybe need to put the code in delete.php in a function ?
Do you think I need to post the entirety of my admin.php file, even thought a lot of the code is not related to the question ?
EDIT: I forgot to mention; i have require delete file in my admin one:
require 'delete.php';
I don't know jQuery, but I think your code should look something like this:
<?php
// delete.php
// make somthing
return 'Helo Word';
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: response => {
alert(reponse);
},
error: error => {
alert(error);
}
});
}
</script>
let's assume that your js code is working(i'm bad with JQuery). The JS code and the PHP code are living in different worlds but can connect by HTTP requests(XML-AJAX) and some others.
You can do a request to a PHP page like my-domain.com/the-page.php?get_param_1=value(GET method), and you can pass the same params(and a little more) by POST method. GET and POST params are looking like :
param_name=param_value¶m_name=param_value¶m_name=param_value
You can't call directly PHP function(like var_dump('123);), but you can do this request with JS my-domain.com/the-page.php?call_func=myFunc123&printIt=HelloMate
to php page
<?php
function myFunc123($printText) { echo $printText; }
if (array_key_exists('call_func', $_GET)) {
$param_callFunc = $_GET['call_func'];
if ($param_callFunc == 'myFunc123') { myFunc123($_GET['printIt']); }
}
?>
Yes, you can pass any existing function name and call it, but it's not safe in future usage. Above, i use "page" word because you should do a request, not php file read or access.
Here is how I finally did it :
I gived an id to my button:
<button id="<?php echo $rows['id']; ?>" onclick ="deletedata(this.id)">Delete</button>
I give in deletedata the parameter this.id, it's a way to give the id of the button as parameter, then I use Ajax to call delete:
<script type="text/javascript">
// Function
function deletedata(id){
$.ajax({
// Action
url: 'admin',
// Method
type: 'POST',
data: {
// Get value
id: id,
action: "delete"
},
success:function(response){
}
});
};
</script>
Here is the tricky thing, I didn't use a fonction as I thought I needed. Instead I did this :
if (isset($_POST["action"])) {
echo "Hello the World! ";
// Choose a function depends on value of $_POST["action"]
if($_POST["action"] == "delete"){
mysqli_query($conn, "DELETE FROM bdd_sites WHERE id = " . $_POST['id'].";");
}
header('Location: '.$_SERVER['REQUEST_URI']);
}
?>
I have a PHP script which Edit and Delete cars on my website. Now I want to make Edit and Delete buttons inside a dropdown, and I did but its adding dropdown just to the first car from the row, since the ID is the same for every dropdown. Now I know how to get the unique ID from every car from PHP but how can I achieve it in JavaScript. I will show you my code.
PHP:
$id = $row["id"];
<div class='dropdown'>
<button onclick='myFunction()' class='dropbtn'>Settings</button>
<div id='myDropdown".$id."'class='dropdown-content'>
".($featured!=1 ? "<a title='Make ".$title." Featured'href='forms/addfeatured.php?id=".$id."'>Make Featured</a>" : "<a title='Remove ".$title."' href='forms/removefeatured.php?id=".$id."'>Remove Featured</a>")."
<a title='Delete ".$title."' href='forms/deletecars.php?id=".$id."'>Delete</a>
</div>
JavaScript:
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
So how can I have different ID in javascript so I can open dropdowns for each entry?
Only use , No need to technically learn AJAX or JSON !
You Just need to use the simple functions which has been prepared for use and has been put in the libraries. And set a few parameters that they need.
The important thing is that, You should know PHP runs on the server machine, not your browser or your PC.
So the PHP variables too.. They are not in your machine to easily put them in a JS variable.
At his point we need to communicate with the server to send them(using AJAX function) in a proper format(using JSON function) for us to use.
So, Your question :
How to add ID from PHP script to JavaScript code?
has the easiest solution just with these functions:
(At your browser page):
$.ajax({ .. some parameters .. });
$(document).ready(function() {
$.ajax({
type: 'post', //Transfer Protocol
url: 'serving.php', //Address of Server Page
dataType: 'json', //Data Structure
data: {action: 'demo'},
success: function(output) {
$variables = output;
}
});
});
and
(At your PHP page on the server)
json_encode(.. some data ..);
$variables = array("Chevy", "BMW", "Ford");
echo json_encode($variables ); // Encoded variable array
Unfortunately your codes and description are not clear for me to help directly in your project.
But I attach a simple practical Example :(in Jquery)
// carSelection.html page
<!DOCTYPE html>
<html lang="en">
<head>
<script
src="https://ajax.googleapis.com/ajax/libs
/jquery/2.1.1/jquery.min.js"> //jquery CDN
</script>
</head>
<body>
<div style="margin:2em">
<form id="myForm">
<select id="selectNumber">
<option>Choose a car</option>
</select>
</form>
</div>
<script>
var $cars = '';
$(document).ready(function() {
$.ajax({
type: 'post',
url: 'carServs.php',
dataType: 'json',
data: {action: 'demo'},
success: function(output) {
$cars = output;
var option = '';
for (var i=0;i<$cars.length;i++){
option += '<option value="'+ $cars[i] +
'">' +
$cars[i] + '</option>';
}
$('#selectNumber').append(option);
}
});
});
</script>
</body>
</html>
And
// carServs.php page
<?php
// ...
$cars = array("Chevy", "BMW", "Ford");
echo json_encode($cars);
//...
?>
just remeber to attach the jquery CDN at your code, In the head section or just before ending the body tag </body>
And if you insist to have it in JavaScript, It's possible just with a few changes in syntax.
I have two sites, site A is just html and javascript, and site B has php. What I need is to get variables from site B in site A.
EX:
site A is like
<html>
<head>
<script>
//this script has to get the values from siteB
</script>
</head>
<body>
<div><!-- here i will do something with the data of site B --></div>
</body>
</html>
Site b is like:
<?php
var1= "something";
var2= "somethingElse";
?>
I was thinking to use JSON or Ajax but i do not understand exactly how.
$(document).ready(function() {
$.ajax({
type: "GET",
url: "filename.html",
dataType: "json",
success: function(data) {
// data will contain var1 and var2
},
error: function(data) {
alert("Problem - perhaps malformed JSON?");
}
});
});
and change your PHP file to be something like:
{
"var1" : "something",
"var2" : "somethingElse"
}
Confirmed to work.
Make sure that your file is a well-formed JSON, otherwise "success" won't be fire.
Note - I am implying usage of JQuery here. Your HTML file should include:
<script type="txt/javascript" src="jquery-1.8b1.js"></script>
File B
<?php
$array[var1] = 'Something';
$array[var2] = 'else';
echo json_encode( $array );
File A (jQuery)
$.getJSON( $( 'file.php', function( data ) {
$( 'div' ).html( data.var1 + ' ' + data.var2 );
}
Edited -- As mentioned, can't do this cross domain without doing some other measures.
Javascript cannot use ajax cross site, for security reasons. The only way to make this happen is to have but one php file on site A that can redirect.
<?php echo file_get_contents($_GET["url"]); ?>
And the javascript can call the url:
/redir.php?url=http://siteb.com/valuetoget.php
There is no way that I know of to do this with no php on the calling website.
I have a link that looks like this:
<p class="half_text">
<?php echo $upvotes; ?>
<strong><a class="vote_up" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a></strong> |
<?php echo $downvotes; ?>
<strong><a class="vote_down" style="color: #295B7B; font-weight:bold;" href="#">Vote Down</a></strong>
</p>
and I have the jQuery code that looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.vote_up').click(function()
{
alert("up");
alert ( "test: " + $(this).attr("problem_id") );
// $(this).attr("data-problemID").
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(json)
{
// ? :)
}
});
//Return false to prevent page navigation
return false;
});
$('.vote_down').click(function()
{
alert("down");
//Return false to prevent page navigation
return false;
});
});
</script>
How can I get the parameter value which is problem_id ? If I add a url in the href parameter, I think the browser will just go to the url, no? Otherwise - how can I pack parameter values into the jQuery?
Thanks!
Because your $.ajax is defined in the same scope of the variable, you can use problem_id to obtain the variable value.
An overview of your current code:
var problem_id = "something"; //Defining problem_id
...
$.ajax(
...
success: function(){
...
//problem_id can also be accessed from here, because it has previously been
// defined in the same scope
...
}, ...)
....
If what you're trying to figure out is how to embed the problem ID in the link from your PHP so that you can fetch it when the link it clicked on, then you can put it a couple different places. You can put an href on the link and fetch the problem ID from the href. If you just do a return(false) from your click handler, then the link will not be followed upon click.
You can also put it as a custom attribute on the link tag like this:
<a class="vote_up" data-problemID="12" style="color: #295B7B; font-weight:bold;" href="#">Vote Up</a>
And, then in your jQuery click handler, you can retrieve it with this:
$(this).attr("data-problemID").
do you mean, getting variables from the php page posted?
or to post?
anyway here's a snippet to replace the $.ajax
$.post('/problems/vote.php', {problem_id: problem_id, action: 'up'}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
{problem_id: problem_id, action: 'up'} are the variables posted... use $_POST['problem_id'] and $_POST['action'] to process..
use simple variables names with jQuery.data and make sure you have latest jQuery..
let me try to round it up..
up
down
<script type="text/javascript">
$('.votelink').click(function() {
$.post('/problems/vote.php', {problem_id: $(this).data('problemid'), action: $(this).data('action')}, function(data) {
// data here is json, from the php page try logging or..
// console.log(data);
// alert(data.title);
}, 'json');
});
</script>
I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.