I have a button in my PHP file, and when I click on that button, I want another PHP file to run and save some data in a MySQL table. For that I am using AJAX call as suggested at this link (How to call a PHP function on the click of a button) which is an answer from StackOverflow itself.
Here is my show_schedule file from which I am trying to execute code of another PHP file:
$('.edit').click(function() {
var place_type = $(this).attr("id");
console.log(place_type);
$.ajax({
type: "POST",
url: "foursquare_api_call.php",
data: { place_type: place_type }
}).done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
});
});
here 'edit' is the class of the button and that button's id is being printed in the console correctly.
here is my foursquare_api_call.php file (which should be run when the button is clicked):
<?php
session_start();
include('connection.php');
if(isset($_POST['place_type'])){
$city = $_SESSION['city'];
$s_id = $_SESSION['sid'];
$query = $_POST['place_type'];
echo "<script>console.log('inside if, before url')</script>";
$url = "https://api.foursquare.com/v2/venues/search?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&v=20180323&limit=10&near=$city&query=$query";
$json = file_get_contents($url);
echo "<script>console.log('inside if, after url')</script>";
$obj = json_decode($json,true);
for($i=0;$i<sizeof($obj['response']['venues']);$i++){
$name = $obj['response']['venues'][$i]['name'];
$latitude = $obj['response']['venues'][$i]['location']['lat'];
$longitude = $obj['response']['venues'][$i]['location']['lng'];
$address = $obj['response']['venues'][$i]['location']['address'];
if(isset($address)){
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude, address) VALUES ($name, $latitude, $longitude, $address)");
$result = $statement->execute();
}
else{
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude) VALUES ($name, $latitude, $longitude)");
$result = $statement->execute();
}
}
}
?>
none of the console.log is logged in the console and also the 'temp' table is not updated. Can anyone tell me where I am making mistake? Or is it even possible to execute the code of a PHP file like this?
Your JavaScript is making an HTTP request to the URL that executes you PHP program.
When it gets a response, you do this:
.done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
}
So you:
Alert something
Show a model
At no point do you do anything with data, which is where the response has been put.
Just sending some HTML containing a script element to the browser doesn't cause it to turn that HTML into a DOM and execute all the script elements.
You'd need to do that explicitly.
That said, sending chunks of HTML with embedded JS back through Ajax is messy at best.
This is why most web services return data formatted as JSON and leave it up to the client-side JS to process that data.
to return the contents of php code you can do something like this
you can use any call to this function
function check_foursquare_api_call(place_type) {
var place_type= encodeURIComponent(place_type);
var xhttp;
//last moment to check if the value exists and is of the correct type
if (place_type== "") {
document.getElementById("example_box").innerHTML = "missing or wrong place_type";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("example_box").innerHTML = xhttp.responseText;
$('#userModal_2').modal('show');
}
};
xhttp.open("GET", "foursquare_api_call.php?place_type="+place_type, true);
xhttp.send();
}
this will allow you to send and execute the code of the foursquare_api_call file and return any elements to example_box, you can return the entire modal if you want,
you can use any POST / GET method, monitor the progress, see more here
XMLHttpRequest
Related
Is it possible to get data php with Ajax without display them ? Simply stock data in JS variable?
I need this data to manipulate dates but no show it.
When I tried to simply return data without echo, etc. Data ajax in JS is empty
Ps : sorry my English is bad
try it this way
File *.php
<?php
$var_1 = null;
$var_2 = null;
/** ... */
$response = new stdClass;
$response->var_1 = $var_1;
$response->var_2 = $var_2;
echo json_encode($response);
?>
File *.html or *.js
<script>
var state = {};
$.ajax({
url: 'getData.php',
type: 'post',
dataType: 'json',
success: function (response) {
console.warn(response);
state = response;
}
});
</script>
Assuming you are trying to pass data from a PHP file to HTML/JS where it happens that your PHP file is also included in the HTML that's why it's displaying the echo (if I understood correctly!)
Using AJAX PHP example from w3school.
HTML sample file:
<?php include "PHP_SAMPLE_FILE.php" ?>
<header>
<meta name="temp_files" content="<?= htmlspecialchars($jsonData) ?>">
<!-- The rest of HTML content -->
JS sample file:
if (str.length == 0) {
// do something if there was nothing entered
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText.includes('{')){
result = JSON.parse(this.responseText);
// do something if response is JSON
} else {
// do something if response is null
}
}
}
xmlhttp.open("GET", "PHP_SAMPLE_FILE.php?q="+str, true);
xmlhttp.send();
}
PHP sample file:
$q = $_REQUEST["q"] ?? $_POST["q"] ?? "";
$sql = "GET SOMETHING FROM DATABASE";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$json[] = $row;
}
}
$jsonData = json_encode($json ?? null);
if($q != ""){
echo $jsonData;
}
What happens exactly is that once the page loads initially it won't display the output of the PHP query as we have surrounded the echo with an if statement that requires to have query value (q) to search and it shouldn't be empty (""). Of course, assuming that once the page is loaded the data is shared with the client-side through defined PHP variables using various approaches, using a meta tag in the header for instance.
Once the data is received from the PHP file through echo, we use the JSON.parse function to parse it as in this scenario JS receives it as a string.
Hope that helped :)!
From the selected value (from the form) I create a variable (var parcela).
var parcela;
$(document).ready(function(){
parcela = localStorage.getItem("parcela");
if (parcela !== '') {
$('#parcela').val(parcela);
}
$("#parcela").on('change',function() {
selectBoxVal_1 = $('#parcela').val();
if (typeof(Storage) !== "undefined") {
localStorage.setItem("parcela", selectBoxVal_1);
} else {
alert('Sorry! No Web Storage support..');
}
location.reload();
});
});
From the created variable (parcela), I create a session variable in PHP.
$.post("phpscripts/session.php", {"parc_id": parcela});
PHP (session.php)
<?php
session_start();
$parcela = $_POST["parc_id"];
$parcela_int = (int)$parcela;
if($_POST){
$_SESSION['parcela_id'] = $parcela_int;
}
?>
After that, the created session variable urge to another php script
query.php
<?php
session_start();
require("common.php");
$user_id = htmlentities($_SESSION['user']['id_korisnika']);
$parc = $_SESSION['parcela_id'];
try
{
$stmt = $db->prepare("SELECT y_cent, x_cent FROM parcele WHERE id_korisnika='$user_id' AND id_parcele='$parc' ");
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
....
This all works perfectly!
However, when I call a php script with query (query.php) in javascript, there is a problem. JS takes the previous session variable instead of the last selected.
$.ajax({
url: 'phpscripts/query.php',
type: 'GET',
success : function(data) {
chartData = data;
//console.log(chartData);
...
Does anyone know what the problem is? I'm trying for two days to solve this ...
Note: The javascript code is contained in a single script.
I solved the problem. I had to extract part of javascript code that calls the php script into a separate script. I called the new JS script with jQuery getScript() Method.
Thank you #knets.
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am not very experienced in web programming and am attempting to run a script which updates my database.
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts)
<?php
include_once 'accounts/config.php';
$text = ...;
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
}
</script>
I have no idea what to put in the $text section as shown with $text = ...; in order to get the variable texts from above.
EDIT
I have updated my code but the function does not seem to be accessing the PHP file. I am using a button to call the function and I have also tested it so i know the function is being called. My file is called update.php and is in the same directory as this file.
<button onclick="myFunction()">Click This</button>
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: "update.php",
type: "POST",
data: {texts:texts},
success: function(response){
}
});
}
</script>
you can post your $texts value to other php page using ajax and get the variable on php page using $_POST['texts'] and place update query there and enjoy....
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: 'update.php',
type: "POST",
data: {texts:texts},
success: function(response)
{
}
});
And your php file will be named as update.php
<?php
include_once 'accounts/config.php';
$text =$_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE `enemies` SET `text`='".$text."' WHERE `id`=1";
$result = mysql_query($query) or die(mysql_error());
?>
PHP runs on the server and then generates output which is then returned to the client side. You can't have a JavaScript function make a call to inlined PHP since the PHP runs before the JavaScript is ever delivered to the client side.
Instead, what you'd need to do is have your function make an AJAX request to a server-side PHP script that then extracts the data from the request body and then stores it in the database.
PHP: "/yourPhpScript.php"
<?php
include_once 'accounts/config.php';
$text = $_POST['data'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text='".$text.'" WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
JavaScript:
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts);
// append data as a query string
var params = 'data='+texts;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
// when server responds, output any response, if applicable
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
// replace with the filename of your PHP script that will do the update.
var url = '/yourPhpScript.php';
xmlhttp.open("POST", url, true);
xmlhttp.send(params);
}
A word of caution: This is not a safe, production-friendly way of updating data in your database. This code is open to SQL injection attacks, which is outside the scope of your question. Please see Bobby Tables: A guide to preventing SQL injection if you are writing code that will go into production.
You are wrong in approach
You should use ajax to post 'texts' value to your php script
https://api.jquery.com/jquery.post/ and create separate php file where you will get data from ajax post and update DB
javascript:
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
type: "POST",
url: "update.php",
data: "texsts=" + texts,
success: success
});
}
</script>
update.php
<?php
include_once 'accounts/config.php';
$text = $_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
i will use PDO if i was you, what you do mysql_query are outdated, if you use my framework https://github.com/parisnakitakejser/PinkCowFramework you can do the following code.
<?php
include('config.php');
$text = $_POST['text'];
$query = PinkCow\Database::prepare("UPDATE enemies SET text = :text WHERE id = 1");
$bindparam = array(
array('text', $text, 'str')
);
PinkCow\Database::exec($query,$bindparam);
$jsonArray = array(
'status' => 200
);
echo json_encode($jsonArray);
?>
place this code in jsonUpdateEnemies.php file and call it width jQuery
<script>
function myFunction(yourText) {
$.post( 'jsonUpdateEnemies.php', {
'text' : yourText
}, function(data)
{
alert('Data updated');
},'json');
}
</script>
its a little more complex then you ask about, but its how i will resolved your problem, :)
I am trying to check the result from a function and determine where on my page it should go by using the Session Variable "alernativeRD". It goes to the correct element on the first try, but after that it keeps going only to the first element regardless of whether its right or not. After some testing I've found that "alernativeRD" does get changed every time in the PHP function, but it doesn't change in the Javascript part.
PHP PART
function firstSignInDefault(){
global $con;
$clubUsername= $_SESSION['clubUsername'];
$_SESSION['alternativeRD']='false'; //sets it back to false to avoid having alternativeRD be true for next user
$lastName= mysqli_real_escape_string($con, $_POST['lastNameF']);
$firstName= mysqli_real_escape_string($con, $_POST['firstNameF']);
$memberID= mysqli_real_escape_string($con, $_POST['idNumberF']);
if(!(is_numeric($memberID))){
die("<h3> Student ID must be a number </h3>");
}
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
if(mysqli_num_rows($getMemberRow)==0){
$sql="INSERT INTO memberstable (MemberMadeID,FirstName,LastName,Club)
VALUES ('$memberID','$firstName','$lastName', '$clubUsername')";
$test=false; //checks to make sure sql statement runs fine
if(mysqli_query($con,$sql))
$test=true;
else {
echo "<h3> Error running sql </h3>";
}
$date=date("Y-m-d h:i:sa");
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
$memberRowArray=mysqli_fetch_array($getMemberRow);
$memberPanID=$memberRowArray['UniquePanDBID'];
$sql2="INSERT INTO signinstable (TimeOfSignIn, UniquePanDBID, ClubUsername, FirstName, LastName) VALUES ('$date','$memberPanID','$clubUsername', '$firstName', '$lastName')";
//THE FOCUS OF THIS QUESTION IS BELOW THIS COMMENT
if(mysqli_query($con, $sql2) && $test==true){
$_SESSION['alternativeRD']='true';
echo " <h2 id='signedInPeople' >".$date. " ".$firstName ." ". $lastName ."</h2>";
}
}
else {
echo "<h3> ID Number already in use</h3>";
}
}
JAVASCRIPT/AJAX PART
function processFSIF(){
var xmlHttp= makeXMLHTTP();
// Create some variables we need to send to our PHP file
var url = "signInDataPlace.php";
var idNumberF = document.getElementById("idNumberF").value;
var lastNameF = document.getElementById("lastNameF").value;
var firstNameF = document.getElementById("firstNameF").value;
var typeSignIn="first";
var vars = "idNumberF="+idNumberF +"&lastNameF="+lastNameF +"&firstNameF="+firstNameF +"&typeSignIn=" +typeSignIn;
xmlHttp.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var return_data = xmlHttp.responseText;
//AREA OF PROBLEM BELOW
<?php
if($_SESSION['alternativeRD']=='true'){ ///YOU ARE HERE, alternativeRD is acting stupid
?>
document.getElementById("serverInputList").innerHTML = return_data;
<?php
}else{
?>
document.getElementById("serverInputFSIF").innerHTML = return_data;
<?php
}
?>
}
}
// Send the data to PHP now... and wait for response to update the status div
xmlHttp.send(vars); // Actually executes the request
document.getElementById("serverInputFSIF").innerHTML = "processing...";
}
Your Javascript was printed only once, before you use AJAX. You can return the session value together with response, or you can set the cookie in PHP, than use it in javascript.
So on this website I'm making (who knows if i'll actually finish it lol) when someone opens up the new user page, php echos into a javascript script all the usernames from the database to create an array.
<script type="text/javascript">
var allUsers = ['!' <?php
$result = mysql_query("SELECT username FROM users ") or die("error " .mysql_error());
$usersArray = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$usersArray[] = $row['username'] or die("error ". mysql_error());
}
foreach ($usersArray as $name) {
echo ',' . json_encode($name );
}
?> , ];
the point of this is to have a live checker so if you type in a username that already exists, red text shows up next to the username input. But let's say I get 1,000,000 users (completely theoretical). Fortunately, the array only gets created at the beginning of the web page load. But will the function that checks if the username already exists in the huge array and gets called everytime someone changes the text in the username input put too much stress on the script and crash the website? If so, is there a better way to do what I'm describing?
Here's the rest of the code
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
function onUserChange() { //gets called onkeypress, onpaste, and oninput
if(contains(allUsers, str)) {
div.innerHTML = "Username already exists";
div.style.color = "red";
userValid = false;
}
}
</script>
Something along these lines. ( with jQuery and PDO ) - note - code is not tested.
var keyTimer, request;
$('namefield').blur(function(){
onUserChange();
});
$('namefield').keyup(function(){
onUserChange();
});
function onUserChange() { //gets called onkeypress, onblur
keyTimer = setTimeout(function(){
if(request && request.readystate != 4){
//cancel a previous request if a new request is made.
request.abort();
}
request = $.post(
'http://yoursite.com/location/of/username/script.php', //post data to server
{username : $('namefield').val()},
function(data){
if(data == 0 ) { //might be a string here
alert( 'the name is ok to use.' );
}else{
alert( 'someone has this name already.' );
}
}
);
}, 500); //overwrite previous timeout if user hits key within 500 milliseconds
}
Then in the backend
$sql = 'SELECT id FROM users WHERE username = :username';
//insert from post username but we are good programers and are using PDO to prevent sql injection.
//search for the username in the db, count the number of users or rows should be 1 someone has it 0 no one has it assuming its unique.
$stmt = $Pdo->prepare($sql);
$stmt->execute(array(':username', $_POST['username']));
echo $stmt->rowCount();
exit();
etc.....
Do not do it. My counsel is to use ajax to load the php file that will make a query asking only for the user that was typed in the input and retunr only a boolean value(exists=true / notexists=false)
Code example:
HTML(yourFile.html):
<script>
jQuery(document).ready(function(){
//When the value inside the input changes fire this ajax querying the php file:
jQuery("#inputUser").change(function(){
var input = jQuery(this);
jQuery.ajax({
type:"post",
url:"path/to/file.php",
data:input.val(),
success: function(data){
//if php returns true, adds a red error message
if(data == "1"){
input.after('<small style="color:#ff0000;">This username already exists</small>');
//if php returns false, adds a green success message
} else if(data == "0"){
input.after('<small style="color:#00ff00;">You can use this username</small>');
}
}
});
});
});
</script>
<input id="inputUser" type="text" name="username" value="">
PHP(path/to/file.php):
<?php
$username = $_REQUEST['username']; // The value from the input
$res = mysqli_query("SELECT id FROM users WHERE username='".$username."'"); // asking only for the username inserted
$resArr = mysqli_fetch_array($res);
//verify if the result array from mysql query is empty.(if yes, returns false, else, returns true)
if(empty($resArr)){
echo false;
} else{
echo true;
}
?>
As I can see you need to load the PHP code when your website is loading.
First, I recommend you to separate the code. The fact that you can mix Javascript with PHP doesn't mean it is the best practice.
Second, yes, it's not efficient your code since you make Javascript load the result so you can search into it next. What I suggest you is making the search in the server side, not in client side, because as you say, if you have 100 elements maybe the best is to load all the content and execute the function, but if you have 1,000,000 elements maybe the best is to leave the server to compute so it can make the query with SQL.
Third, you can do all this using Ajax, using Javascript or using a framework like jQuery so you don't have to worry about the implementation of Ajax, but you only worry about your main tasks.