Sending array from PHP script - php

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")

Related

How can i pass two values from select box using AJAX

Hi i have the following code but i am not able to access the values in my request.php file from this.
$(document).ready(function(){
$("select.location").change(function(){
var Did = $("input[name='district']").val();
var selectedLocation = $(".location option:selected").val();
$.ajax({
type: "GET",
url: "request.php",
data: {location : selectedLocation, Did:Did},
}).done(function(data){
$("#response").html(data);
});
});
});
and my request.php is calling the data like this
if(isset($_GET["location"]))
{
$i=0;
$bfrom = $_GET["location"];
$did= $_GET["Did"];
$sql = "SELECT distinct stopname FROM `route` WHERE `rfrom` LIKE '$bfrom' and did=$did";
$result = $conn->query($sql);
first off, and most importantly, for security you need to parameterize your query. See PHP: Prepared statements and stored procedures
Secondly, your LIKE argument needs to be preceded and followed by % - eg '%$bfrom%' - this enables "wildcard" data search MySQL Wildcards
Lastly, you need to echo a response in the AJAX call, in order for the receiving javascript to pick it up :)

$.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.

aJAX call to PHP file

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

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 Ajax return html AND json data

I'm not sure if there is any way to do this or not, but this would solve so many of my problems if there is a simple solution to this.
What I need/want to be able to do is return HTML and JSON in my success of ajax request. The reason being, I want to request a file and return all of that page, but I also want to be able to return a specified set of information from the page in json, so I can use it for other things.
This is what I'm doing now:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
}
});
This is what I'd like to be able to do:
$.ajax({
type: "POST",
url: "inc/"+page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html){
$("body > .container").html(html);
$("title").html(json.PageTitle)
}
});
on the page that is being returned, I would specify what I want the title to be. (For instance, if it's a profile, I would return the user's name)
HTML and data wrapped in JSON
You can do it by returning a 2 element JSON array.
The first element contains HTML and the second element contains another JSON array with the data inside. You just need to unwrap it carefully without breaking anything.
Serverside
$html = '<div>This is Html</div>';
$data = json_encode(array('page_title'=>'My Page'));
$response = array('html'=>$html, 'data'=>$data);
echo json_encode($response);
Clientside
//Ajax success function...
success: function(serverResponse){
$("body > .container").html(serverResponse.html);
var data = JSON.parse(serverResponse.data);
$("title").html(data.page_title)
}
Note 1: I think this is what #hakre meant in his comment on your question.
Note 2: This method works, but I would agree with #jheddings that its probably a good idea to avoid mixing presentation and data. Coding karma will come back to bite.
Trying to mix the retun value to contain presentation and data seems like a potential for confusion. Why not split it into two calls and fetch the data on success of the other?
Something like:
$.ajax({
type: "POST",
url: "inc/"+view_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(html) {
$("body > .container").html(html);
$.ajax({
type: "POST",
url: "inc/"+data_page+".php",
data: "id="+encodeURIComponent(pageID),
success: function(json) {
$("title").html(json.PageTitle);
}
});
});
You also have the option of including the data in html5 data attributes
For instance, if you're returning a list of Animals
<ul id="ZeAnimals" data-total-animals="500" data-page="2">
<li>Cat</li>
<li>Dog</li>
...
</ul>
You can then collect the data you require using
$('#ZeAnimals').data('total-animals')
Sometimes separating your request into two different ajax calls makes sense also.
You may use a library that does that automatically, like http://phery-php-ajax.net. Using
Phery::instance()->set(array(
'load' => function(){
/* mount your $html and $json_data */
return
PheryResponse::factory()
->json($json_data)
->this() // points to the container
->html($html);
}
))->process();
$(function(){
var $container = $('body > .container');
$container.phery('make', 'load'); // or $container.phery().make('load')
$container.bind('phery:json', function(event, data){
// deal with data from PHP here
});
$container.phery('remote');
});
You may, as well, use phery.views to automatically load a portion of the site automatically, without having to worry about client-side specific code. You would have to put a unique ID on the container, container in this example:
$(function(){
phery.view({
'#container': {}
});
});
Phery::instance()->views(array(
'#container' => function($data, $params){
/* do the load part in here */
return
PheryResponse::factory()
->render_view($html)
->jquery('.title')->text($title);
}
))->process();

Categories