aJAX call to PHP file - php

I have a need to use the $.ajax method to call a PHP file. I have to pass in a driver id to the PHP file, which then retrieves the id, executes a query to get the driver's name and return that name back to the form so I can autopopulate the appropriate textbox. Here is the ajax method:
var id=$('#DriverID').val();
$.ajax({
url: 'drivername.php',
data: {driverid: id},
type: 'POST',
success: function(data) {
$.('#DriverName').val(data);
}
});
Here's the PHP:
$driverid=$_POST['driverid'];
$host="Host to database";
$user="user"
$password="password";
$db="database";
$driver="";
$query="SELECT driver_name FROM drivers WHERE driver_id=$driverid";
$cn=mysqli_connect($host, $user, $password, $db);
$result=mysqli_query($cn, $query);
while($data=mysqli_fetch_array($result))
{
$driver=$data['driver_name'];
}
echo $driver;
How do I configure the PHP file to return the driver's name, and also, is the ajax method syntax correct?

It looks like your PHP script is already returning the "driver's name" variable that you're setting up with your SQL. If your return value was larger or more complex (e.g., multiple values, an array/object/etc), you could JSON encode it and use jQuery to JSON decode it. To update CSS id "DriverName" with the return data, I think you just have an extraneous ".":
success: function(data) {
$('#DriverName').val(data);
}
This question is quite similar: jQuery ajax - update div

Related

Posting data from ajax to php

Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});

Sending array from PHP script

Here's the values I am sending to the PHP script from the Javascript:
$('.verdi_knapp').click(function() {
$(this).siblings().removeClass("aktiv_verdi"); // ta vekk aktiv på de andre alternativene
$(this).addClass("aktiv_verdi"); // sett denne til aktiv
var min_id = $(this).attr('id').split("_")[1];
var aktuelle_verdier = []
$('.aktiv_verdi').each(function() {
aktuelle_verdier.push($(this).attr('id').split("_")[1]);
})
console.log("disse verdiene skal vi spørre etter", aktuelle_verdier)
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier},
dataType: "json",
success: function(result){
console.log(result);
}});
This is the PHP script which queries a set of values from an SQL database and prints them to the console in the javascript:
$ids = $_GET['aktuelle_verdier'];
$value = implode(", ", $ids);
$antall = count($_GET);
$sql = "SELECT `art_id`
FROM `art_has_verdi`
WHERE `verdi_id` IN (".$value.")
GROUP BY `art_id` HAVING COUNT(*)=".$antall.";";
$result = mysqli_query($conn, $sql);
$arter_igjen = array();
while($row = mysqli_fetch_array($result)){
array_push($arter_igjen, $row['art_id']);
}
echo json_encode($arter_igjen);
What I am trying to find out next is how to send this array: $arter_igjen, which contains a set of IDs, to another page where I can run a query to the database for all the data containing these IDs and print them out in a list.
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
console.log(result);
}});
Please check data Paramter in ajax call. You forgot to pass key in JSON.
If I understand you right you like after ajax return you clone the window and in new one window you will make some new searches, but on the current one will be generate a log. In cas I'm understand you right, then why don't try to generate form on fly by with returned data end post it to the _blank window.
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier},
dataType: "json",
success: function(result){
// Here you have to generate the form on fly
// Include hidden fields, containing your result data
// and finally send form with action some new.php on blank_ target
console.log(result);
}});
If the other page contains code like in this one (not in a class or function), you can just include it (include_once "..."), but it is not recommended that you just keep scripts like that.
Instead, encapsulate your code (put it within functions and classes). This will allow you to freely insert your scripts (include_once "...") and call these functions or create classes that will work.
Also, try to avoid too many http requests. If that list of ids won't be needed, do all of the work in the php scripts and return the needed result.
There are a few issues with your code. If you are just starting with PHP I would suggest you read:
PDO: Creating a connection
PDO with prepared statements (prevents SQL injections)
User-defined functions (I don't have enough reputation to put the link. Search: "w3schools php 5 functions")

$.ajax query not posting to PHP

I've spent the better part of today trying to send a jQuery variable to my PHP file and use it in a SQL search. My first issue is that can't even get the variable into PHP properly. I am also getting an error about some of my SQL code which I've included as well.
What I want: the variable in jQuery called name sent to the PHP file where it is used in an SQL Query to find the real name of musicians. the real name would then be sent back to the HTML file where it is displayed on the webpage. MyPHPAdmin and my database has already been setup.
jQuery:
$('li').click(function () {
var name = $(this).text();
$('#prf').attr("class",name);
$('#pic').attr("class",name);
$('#info').attr("class",name);
JSON.stringify (name);
$.ajax({
type: "POST",
url: "ajax-name.php",
data: {name: name}
})
PHP:
$rname = $_POST['name'];
var_dump($rname);
try {
$db = new PDO('mysql:dbname=dbname;host=myhost;charset=utf8', 'user', 'pass');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query="SELECT realname FROM artistmaster WHERE stagename = :name";
$stmt = $db->prepare($query);
$stmt->execute(array("name"=>$rname));
var_dump($rname);
echo 'Success';
$result=$stmt->fetchAll();
print "<pre>";
print_r($result);
print "</pre>";
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
OUTPUT:
NULL NULL
I've read the documentation on $.ajax() and still can't figure out what I'm doing wrong. I appreciate any help on this, it's been giving one hell of time.
To evaluate the output of the PHP script from the AJAX request add a return handler to your request:
$.ajax({
type: "POST",
url: "ajax-name.php",
data: {name: name}
}).always(function( html ) {
console.log(html); // this will show the content of the php script in the developer console of your browser
});
The function defined in .always() is called every time an AJAX request finishes. When you made sure that your code works you can change it to .done(), which is only called when the AJAX call is successfull. You can also add a .failure() function to handle errors gracefully.
Also note this from the documentation:
The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use.
I'd suggest to use the $.post function instead:
$.post("ajax-name.php", {name: name}, function( html ) {
$('#outputdiv').html(html);
// this will replace the content of a <div id="outputdiv"></div> with the output of the AJAX request
});
Try this:
$.ajax({
type: "POST",
url: "ajax-name.php",
data: {name: name},
success : function(html) {
// html code, do something with it here
}
});
then
$rname = $_POST['name'];
$query="SELECT realname FROM artistmaster WHERE stagename = :name";
$stmt = $db->prepare($query);
$stmt->execute(array("name"=>$rname));
You get your result with
$stmt->fetchAll();
You don't retrieve PDO driver results with mysqli
alert variable name in javascript and make sure it is not null.you may use exit;
echo $_POST['name'] in the php file.receive the processed data in javascript with the success:function(result) and alert it.
store every data in a single variable in the php file. and finally echo them.

POST data through AJAX and set as variable

I am not very familiar with javascript especialy when it comes to functions and ajax. I am trying to get some data from another php page and have it put into a div. When I ever i load the page nothing comes up.
My ultimate goal is to get the data into a php or javascript but first need to figure out how to get / receive data.
here is the php code of feedupdate.php
<?php
require "dbc.php";
$function = $_POST['function'];
switch($function)
case('initiate'):
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$mostrecent= mysql_fetch_array($request);
$mostrecentid = $mostrecent['id']
echo json_encode($mostrecentid);
break;
case('update'):
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
echo json_encode($updateid);
break;
?>
here is the ajax
<div id="datacheck"></div>
<script>
$(document).ready(function() {
$.ajax({
type: 'POST'
url: 'feedupdate.php'
data: {'function': 'initiate',},
datatype: "json"
success: function(msg) {
$('#datacheck').html(msg);
}
});
}); // document ready
There is a typo in the ajax jquery code
success: fuction(msg) {...
it should be spelled "function".This typo might be the problem , plus there should be switch case for
getState
in your php code.
You are passing getState in data from JavaScript while in PHP you do not have a similar case to match in switch statement. Instead of getState pass update or initiate.
If you just want to check either AJAX call is working or not write
echo "something message"; exit();
In your AJAX you are passing data back to the PHP script:
data: {'function': 'getState'},
But in your php script you don't have a case statement that matches getState you only have initiate and update. So you can either write code to support getState or you can pass in either initiate or update to the data parameter.
Also watch out for trailing comma's. They won't work in IE. You should remove the comma after 'getState' on the data line.
You are also missing a comma after type, url, and datatype
$(document).ready(function() {
$.ajax({
type: 'POST', // add comma
url: 'feedupdate.php', //add comma
data: {'function': 'initiate'}, // remove comma
dataType: "json", // add comma
success: function(msg) {
$('#datacheck').html(msg);
}
});
});
Alos you can look at using the shorthand method $.post docs

JQuery to PHP function and back Ajaxed

i have a set of php function that i want to call on different events mostly onclick with jquery async (ajax).
The first function is called on load
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
success: function(html)
{
$("#div1").show('slow').html(html)
}
});
The Data: {'func':'1'} --> is a switch statement on the php side
switch($_POST['func'])
{
case '1':
getParents();
break;
case '2':
getChilds(params);
break;
case '3':
getChildObjects(params);
break;
default:
}
"This functions are calls to a soap server" <-- irrelevant.
So when that function finishes i get an array which contains IDs and Names. I echo the names but i want the ID for reference so when i click on the echoed name i can call an other php function with parameter the ID of the name...
How do i get rid of the switch statement?? How do i call properly php functions and pass params to it??? How can i save this IDs so when i click on an item with that id an other php function is called??
Plz feel free to ask any question, any answer is welcome :)
``````````````````````````````EDIT``````````````````````````````````````````
$(document).ready(function()
{
$("#div2").hide('slow');
$("#div1").empty().html('<img src="ajax-loader.gif" />');
$.ajax(
{
type: 'post',
async: true,
url: "Parents.php",
data: {'id' : 12200},
dataType: "json",
cache: false,
success: function(json_data)
{
$("#div1").empty();
$.each(json_data, function(key, value)
{
$("#div1").append('<p class="node"><b>['+key+']</b> => '+value+'</p>');
$(this).data('id', key);
});
}
});
$("p.node").click(function()
{
var id = $(this).data('id');
alert('The ID is: ' + id);
});
});
I got json communication working but my problem is the data stuff,
when i click on a node the id is undefined... it gets printed but when i click on it oupsss.. so the problem is how can i properly attach the ID to each corresponding .. .
You can avoid the switch statement by using an MVC framework that routes your request to the proper function. For example, using CodeIgniter REST Server, you might have the following URL's to your functions:
http://myserver/my_api/parents
http://myserver/my_api/children
http://myserver/my_api/childObjects
You can then POST the parameters along with each AJAX request.
You would probably also want to return the ID you pass as part of the response, so it will be available when you make a request for the next function.
One solution for managing your ID's would be to encode your data as JSON. This will allow you to pass the whole PHP array to Javascript, and have it natively understand and read the ID's and Names.
To encode your PHP array as JSON, try this:
echo json_encode($my_array);
(You'll need PHP 5.2+ for this to work)
This will print out JSON data when the page is requested. Next, in your JavaScript add a "dataType" argument to your Ajax function call. Something like this:
// Get JSON Data and Save
$.ajax({
type: "POST",
url: "WebFunctions.php",
data: {'func':'1'},
dataType: "json",
success: function(json_data) {
$("#div1").data(json_data);
}
});
// Display the ID when clicked
$("#div1").click(function(){
var id = $(this).data('id');
alert('The ID is: ' + id);
});
This tells the Ajax function to expect JSON back.
When the success function is called you can access the "json_data" variable and find all the ID's and Names just as you had them in PHP. You'd then need to write some code to appropriately save those ID's and Names. They can then be used later on (ie. when you click on the button etc).
EDIT: I've updated the code above. The JSON data is now associated with the HTML element "#div1", so you can refer back to it in the future. I've also added a simple click event. Whenever the element is clicked, it's ID will be displayed.

Categories