Ajax Get results from sql query - javascript

I'm fairly new to web development and php.
I have a js file with all my functions. In one of the functions I make an ajax call to create a new database record that person A is making a challenge to person B.
JS
var challengeeId = document.getElementById('Challengee').value;
$.ajax({
type:"post",
url: baseUrl+"/site/challenge",
data:{"challengeeId":challengeeId},
cache:false,
success: function(html){
}
});
PHP
$model = new Challenge();
$model->challenger_id = Yii::app()->user->id;
$model->challengee_id = $_POST['challengeeId'];
$model->date_created = date("Y-d-m H:i:s");
$model->status ="pending";
$model->save();
This is fine and saves in table correctly. The table also creates an id for every challenge. I want to know how to return that id so that I can store it as a variable in my JS file for later use. I have an SQL query which returns the ID for me, I just don't know how to return it from the PHP to JS.

Use this sure you get the last id
If using postgresql
$lastID = Yii::app()->db->getLastInsertID('table_sequence');
return $lastID;
If using mysql
$lastID = Yii::app()->db->getLastInsertID();
return $lastID;
since getLastInsertID is accessor method you also call like this too
$lastID = Yii::app()->db->lastInsertID;
return $lastID;

You'll need to return that value back either as a string or maybe a json return and then that becomes the "html" var in your "success" case of the ajax call. You then handle the rest in javascript

You could echo the id in php. the variabele html will then contain the id.

Related

How do I transfer the PHP variables to another javascript file?

So my goal is to use PHP to get data from a PostGreSQL database. I want to use this data in a separate javascript file so I can display it on the screen a certain way that I have my website configured. All the tutorials that I have seen online just puts a script tag inside the PHP file but I cannot do that because my website display javascript code is in the separate file. I just need the numbers to be in the javascript file that I got from the PHP file that got its data from the PostGreSQL database. How can I do this?
I just need help with the means to get to the ends because I have researched on my own but it is always not exactly what I want.
PHP:
<?php
$myPDO = new PDO('pgsql:host=myHost; dbname=myDBName', 'myUsername', 'myPassword');
?>
$result = $myPDO->query("SELECT * FROM table WHERE id = 'someID'");
Now I want to use this row's values in another javascript file. How can I do this?
You could use Ajax for this.
You could so something like this in your JS file:
$.ajax({
type: "GET",
url: 'FILENAME.php',
success: function(data){
alert(data);
}
});
and then in your FILENAME.PHP just return the values.
Your JS should then pull through whatever has been returned, in this case, your database query.
Your JS file needs to request the data from your PHP controller, via an AJAX request. You can then manipulate the returned data object whichever way you like.
We have mainly two methods to pass php value to javascript variable
Simple variable method at the time of first page load
<script>
var js_variable = <?php echo $data_php_variable; ?> ;
//this is working only at the first time of the page load
//you can also parse the data to any format
</script>
Use AJAX call to trigger a PHP request and manipulate return PHP value in JS
$.ajax({
type: "GET", //get or post method
url: 'FILENAME.php', //php request url
data :{}, //optional ,you can send data with request
success: function(res){
// this 'res' variable is the php return data in the form of js data
console.log(res);
}
});
ajax method is more dynamic ,it can use any time request handling
use the javascript ajax to call a php api
pass your data at php in your view file , use something like:
var phpData = JSON.parse("<?php echo json_encode($data)); ?>");

How to pass resource from php to javascript

So I have three different separate files:
functions.php (all functions for the database)
main.html (my main program)
main.js (all javascript functions)
Now, I want to call a function in PHP through AJAX. To do that, I need to pass $conn.
$conn = sqlsrv_connect($serverName, $connectionInfo);
It's a resource, so I can't use json_encode.
The way I set the everything up now is that the php-file is required in the html so I can use the functions and when I change the
value of a dropdown, the js is called.
How can I pass the $conn variable to Javascript?
Regards
It doesn't work like that.
You should never be directly making calls to the database from the front-end.
Think of it as three separate levels. Your HTML/JS is the front-end, your PHP is your server, and your Database is on its own level.
So when the user does something on the front-end, say changes the value of a field and you want to update that in the database the following actions should happen:
Event triggers on JS
AJAX is called as a result of the event being triggered
PHP server receives the AJAX request and executes code to modify database
(optional) PHP server sends something back to the front-end to tell it that the request was successful
Read up on the concept of MVC: https://developer.mozilla.org/en-US/docs/Web/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture
Try this in php code as I assume functions.php
$conn = sqlsrv_connect($serverName, $connectionInfo);
echo $conn;//Don't try echo anything other
In Javascript
$.ajax({
type: "POST",
url: "functions.php",
success: function(data)
{
var conn = data; // here is your conn which comes from php file
}
});
First of all include jquery latest version from cdn
Create an API Url, and use POST method
site.com/api/insert.php // to insert into table
Use $.post() api of jquery to send data
var url = ""; // enter your URL HERE
var postData = {}; // object of post data with table name, cols and values
$.post(url, postData, function(data, status) {
// do what ever you want with data
})
ps: you can also create diff insertion / selection / update / delete api for different table. (recommended)
Read more about $.post() here

Mysql Insert Query via Ajax

I've searched the internet and found something about using ajax for setting information in my database. I found this page, but it shows how to GET info from your database.
Is it also possible to SET information in the database?
I use this for a schedule.
in my DB I have a table that contains the following columns:
Startdate
Enddate
Productdescription
Expected production
actual Production
Difference
When they create the schedule they only know the first four. The other two need to be filled in automatically. I do this when the production is finished:
I've made a small start about checking if the production is done:
setInterval(function()
{
var currentTime = new Date();
var endProductionTimeMachine1 = <?php echo json_encode($TempomaticRow1[0]['Einddatum']) ?>; // get the enddate from the database via php
var ActualProductionToday = 2100; //just an example value
//Convert mysql date to javascript date
var t = endProductionTimeMachine1.split(/[- :]/);
var endProdTimeMachine1 = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
if(currentTime == endProdTimeMachine1)
{
//set information in the DB
}
},1000);
So I would like to know if I can call a php page that inserts information into my database with a parameter from this page.
Yes, you can.
You can do it with jquery using a post method through ajax.
So, now that you have your vars you have to add a code like this:
$.ajax({
method: "POST",
url: "some.php", //the endpoint in php where your save method is
data: { currentTime: currentTime, endProductionTimeMachine: endProductionTimeMachine1 ...and so on}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
and at your php just do this...
if(isset($_POST['currentTime']){
$currentTime =$_POST['currentTime'];
}
... and so on
After you get all your vars be sure you use (if you are not using a framework) a mysql injection cleanup.
I suggest using mysqli_real_escape_string , after having all your variables and all at your PHP side, you can create your query to set/update info at your db.
More info of Ajax here
Use that page and modify the AJAX call so that it triggers a PHP script which will then update your database. Send all information necessary to the server. In order to change the database, make use of "prepared statements" either via MySQLi or PDO.
Never send a SQL query from a client to a server! Always only send the values and have the server build the query!
For a complete example, you can also take a look at this: http://www.plus2net.com/php_tutorial/display-record-edit.php

Ajax after success, how to pass data to a variable to php

I have script like this
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
I don't know how I can pass data response to php code ?
For Example: if I alert response, it's show 123 .so I want pass value 123 to a variable in php
$id = 123
response is the result passed BY php, not TO php. What's passed to php is the id and the task.
In your tab.php, you can access these two values :
<?php
$id = $_POST['id'];
$task = $_POST['task'];
//do anything you want with it...
?>
This is not the right workflow. PHP executes on runtime, so every time the page has finished loading you can't really put variables back into PHP (unless you reload the page). This is where AJAX comes in, so you can call PHP scripts from JavaScript / jQuery and don't have to reload the page every time.
The right thing to do is to either store the variable you have generated in the tab.php script in a database, $_SESSION, $_COOKIE or something similar like so:
//put this at the top of all your php scripts you want to use the variable in
session_start();
//now store the variable you wanted to pass (in tab.php)
$_SESSION['returnValue'] = $myValue;
Now if you want to use the variable in other pages just echo it like so (remember to add session_start() at the top of the PHP script.
echo $_SESSION['returnValue'];
First of all, start by reading this
To answer your question,
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
The result from id and task are sent via $_POST (type:"POST") to the page tab.php (url:"./tab.php"). If you want to do that on a different page, just change the url in your ajax call: url:"./any_other_page.php" and the posted values will be sent there
Finally, read THIS post as well. It is greatly written and very well explained.
Hope it helps!
Keep on coding!
Ares.

How to pass data in DOMDocument object inside PHP script to JavaScript file?

My PHP script creates and saves a file to local hard disk using DOMDocument's ->load and ->save methods successfully.
<?php
$dom = new DOMDocument();
$dom->load($data);
$dom->save($filename);
return $dom; // am I passing data to JavaScript here wrongly?
?>
This PHP script is called upon with jQuery's $.ajax from another file:
$.ajax({
url: 'script.php',
type: 'GET',
data: parameters,
success: function(resp) {
//var data = new Blob([resp], {type: 'text/xml});
//textFile = window.URL.createObjectURL(data);
//return textFile;
console.log(resp);
}
});//ajax
I don't see anything in console. How to pass DOMDocument data from PHP script to JavaScript's AJAX call?
I also tried using file_get_contents() and returning it's result but same problem.
I think you will need to echo the result, not return it.
<?php
$dom = new DOMDocument();
$dom->load($data);
$dom->save($filename);
echo $dom->saveXML();
?>
You have two mistakes in your script.
First, you have to turn
$dom->save($filename);
into
$dom->saveHTML($filename);
As stated in the documentation, the save() method return an integer while saveHTML() return the content generated.
Then, you have to turn
return $dom;
into
echo $dom;
Indeed, if you want Javascript to get the content, you have to write it in the output (via the echo function), not return it; "return" doesn't write anything

Categories

Resources