ajax post to php and retrieve sql result [duplicate] - javascript

This question already has answers here:
How to pass parameters in $ajax POST?
(12 answers)
Closed 6 years ago.
im using ajax and php on my android app to query my database.
i am able to retrive all the results but dont know how to send a variable to my php so that i can use it as a custom query and retrive the results... something like this :
$id = $_POST['id'];
$sql = "SELECT * FROM mobile_app WHERE nome LIKE '{%id%}'";
but cant make my ajax post the variable and retrive the result...
this is my code :
my mobile app:
$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON", // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.setItem('myData', JSON.stringify(data));
}
});
my php:
$sql = "SELECT * FROM mobile_app";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$output[] = array (
"nome" => $row['nome'],
"status" => $row['status'],
"hentrada" => $row['hentrada'],
"evento" => $row['evento']
);
}
} else {
echo "0 results";
}
$conn->close();
echo json_encode($output);

ajax() have a parameter
data:
by using this you can send as many param you want lik:
data:{
param1 : value1,
param2 : value2,
// and so on
}
In your case it is like:
data:{
id : value
}
and you can get this param in your php code like:
$id = $_POST['id'];

You need to add the following additional options to your $.ajax object:
type: 'post'
and
data: {
id: whateverVariableHasID
}

Related

how to send this data from local storage to php online using jquery

This is my php codes to received and insert the data into the online database. I am very sure i these fabricated codes will not work but with you education and help i will get. thank you. insertdata.php
<?php
include 'connect.php';
include 'function.php';
//Create Object for DB_Functions clas
$db = new DB_Functions();
//Get JSON posted by Android Application
$json = $_POST["usersJSON"];
//Remove Slashes
if (get_magic_quotes_gpc()){
$json = stripslashes($json);
}
//Decode JSON into an Array
$data = json_decode($json);
//Util arrays to create response JSON
$a=array();
$b=array();
//Loop through an Array and insert data read from JSON into MySQL DB
for($i=0; $i<count($data) ; $i++)
{
//Store User into MySQL DB
$res = $db->storedata($data[$i]->callid,$data[$i]->pid,$data[$i]->pname,$data[$i]->medstay_amt,$data[$i]->med_amt,$data[$i]->imv_amt,$data[$i]->othermc_amt,$data[$i]->emtrans_amt,$data[$i]->outpden_am,$data[$i]->otherps_amt,$data[$i]->herb_amt,$data[$i]->medban_amt,$data[$i]->othermp_amt,$data[$i]->assist_amt,$data[$i]->code,$data[$i]->date);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->pid;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->pid;
$b["status"] = 'no';
array_push($a,$b);
}
}
//Post JSON response back to Android Application
echo json_encode($a);
?>
You can do something like this:
$(document).on("click", ".BTN_Submit_Task", function () {
var AllTasks = ls.GetAllArr(LocalstorageName);
var id = $(this).attr("rec_id");
var result = $.grep(AllTasks, function(e){ return e.rec_id === id; });
$.ajax({
url: "url/of/php/file.php",
type: 'post',
dataType: 'json',
data: {usersJSON: [result]},
done: function(response) {
console.log(response);
}
});
});
And BTW you probably want to make AllTasks variable global and assign it once, then you can call it from both functions.

How do I make use of JSON response from JQuery AJAX request? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I am using PHP and MySQL to swap out some content.
A click handler sends an AJAX request to the PHP script which performs a query, then encodes and prints the result as a JSON object.
All that seems to work, but I seem to be stuck on the most silly thing:
I can't work out how to actually use the result, as in set the individual values to JavaScript variables.
Edit: I added a couple more things I tried, to get a specific value to print out to the console, no luck thus far.
Edit: Found the correct syntax:
response[0].foo
javascript:
var listId = $(this).children('.hidden-id').html();
var options = new Object();
options.data = listId;
options.dataType = 'json';
options.type = 'POST';
options.success = function(response) {
console.log(response[0].foo);
};
options.url = './inc/change_list.php';
$.ajax(options);
the PHP script:
$list_id = $_POST['list_id'];
$q = "SELECT id, title, description, position FROM items WHERE list_id=$list_id ORDER BY position ASC";
$r = mysqli_query($dbc, $q);
if (mysqli_num_rows($r) > 0) {
$result = array();
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
$add_result = [
'id' => $row['id'],
'title' => $row['title'],
'description' => $row['description']
];
$result[] = $add_result;
}
$result = json_encode($result);
echo $result;
} else {
echo '{"result":"failure"}';
}
The JSON response will automatically be parsed to a Javascript object. So you can just do:
options.success = function(response) {
console.log(response.foo); // logs "bar"
// or
var foo = response.foo; // foo now holds "bar" as it's value
};

PHP Not passing variables through to ajax

I am passing through The continent to the PHP file from a js file. Basically I need to insert the data to the database (put the continent in) and get the ID of it, but no matter what I do, it returns either an empty string or a 500 Internal Service Error.
Here is the PHP Code:
$continent = $_POST['continent'];
$sql = "INSERT INTO location_continent (`name`) VALUES ('". $continent ."')";
if(!$result = mysqli_query($con, $sql)){
die('There was an error running the query [' . $db->error . ']');
}
$sql = "SELECT id FROM location_continent WHERE `name` = '". $continent ."'";
$result2 = $con->query($sql);
if(!$result2){
die('There was an error running the query [' . $con->error . ']');
}
return $result2->num_rows;
Here is the JS Code:
$.ajax({
url: 'process.php?section=continent',
type: 'POST',
data: 'continent='+key,
success: function(res) {
continentid = res;
console.log(res);
},
error: function(res) {
console.log(res);
}
});
The Key that is passed through would be something like Africa.
I have tried the following in the php file:
return mysqli_insert_id($conn);
return $result;
$result = mysqli_query($con, $sql);
I have struggled for around 2 hours now. I cannot seem to find the error.
Note
Please note that the information is being inserted to the database just fine, just that I cannot get the ID.
In ajax you need to print/echo output for return data rather return statement so try to replace
return $result2->num_rows;
to
echo $result2->num_rows;
also you can send your query string like:-
$.ajax({
url: 'process.php',
type: 'POST',
data: {'section':'continent','continent':key},
success: function(res) {
continentid = res;
console.log(res);
},
error: function(res) {
console.log(res);
}
});
Then check your post data by echo if correct something wrong with query executing can't find $con and $db defined on posted code
You are returning but you are not in a function, so try echoing instead (echo mysqli_insert_id($conn);)

.post javascript with PHP to enable select statement return

.post javascript with PHP to enable select statement return
Okay I got this script that is working
$.post('2.php', { id: 12345 }, function(data) {
// Increment vote count, etc
});
This is what my 2.php looks like
$data = $_POST['id'];
$file = fopen("test.txt","w");
echo fwrite($file, $data);
fclose($file);
So I did a test, I run 1.php and saw test.txt was created with the data.
this prove the connection was successful.
Now is the difficult part.
I need to send id:12345 to 2.php, and 2.php need to
"select * from account where account_id='$data'";
And then the return result, I think of using MYSQL_ASSOC or MYSQL_BOTH
I not sure which is best.
Then get the result, be it 1 row result or many row result.
Return as an array and then use 1.php to perform
alert( ArrayReturnResult );
Assuming that my account table have this value
account_id, account_name, account_phone, account_email
How do I accomplish this?
Assuming you know how to establish a database connection (using PDO, of course), you could do something like this in 2.php:
if(!empty($_POST)) {
$data = (int) $_POST['id'];
// query the table
$stmt = $pdo->prepare("SELECT * FROM account WHERE account_id = :id");
$stmt->bindValue(":id", $data, PDO::PARAM_INT);
$stmt->execute();
// fetch results
$buffer = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$buffer[] = $row;
}
// output JSON string
echo json_encode($buffer);
}
Of course, this isn't tested... and probably isn't secure if dealing with personal details.
Don't forget to update your $.post method so that it can expect JSON-encoded data:
$.post('2.php', { id: 12345 }, function(data) {
console.log(data); // this will now be a JS object, from 2.php
}, 'json');

jQuery $.getJson call not returning value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am trying to make a site that dynamically creates information using the jQuery ajax call $.getJson and the jQuery template plugin. In my index.html page, I have some of the following code:
$(document).ready(function() {
var jsonData ="string";
$.getJSON("load.php", function(data) {
jsonData = data;
console.log(jsonData);
});
console.log(JSON.stringify(jsonData));
// Load template from our templates folder,
// and populate the data from the post object.
$("#test").loadTemplate('#template', jsonData);
});
The ajax call executes the load.php, which has some of the following code:
//extract user ratings and respective movies
$_SESSION['username'] = $username;
$user_query = mysqli_query($link, "SELECT * FROM Client WHERE Username = '$username'");
$user_row = mysqli_fetch_array($user_query);
$user_id = $user_row['ID'];
$query = mysqli_query($link, "SELECT * FROM Ratings INNER JOIN Movie ON Ratings.Movie_ID = Movie.MovieID WHERE Client_ID = $user_id ORDER BY Rating DESC");
//adding movies to array list
$result = array();
while ($row = mysqli_fetch_array($query))
{
$movie = $row['MovieURL'];
$rating = $row['Rating'];
array_push($result, array('moviePicture' => $movie, 'movieRating' => $rating));
}
//converting array list to json and echoing it
echo json_encode($result);
I have tested the $result and it does create a json object with all of the data that it is supposed to. However, when the javascript is run in the index.html page, jsonData does not change its value from 'string'(when I check the console log). I believe the problem is with the function(data), since it does not log the console command I have in there. Any help would be appreciated.
Proper code:
$(document).ready(function() {
var jsonData ="string";
$.getJSON("load.php", function(data) {
jsonData = data;
$("#test").loadTemplate('#template', jsonData);
});
});
The problem with your code is, that you call loadTemplate before you got reply from load.php

Categories

Resources