Translating Ajax request from Javascript to jQuery - javascript

I'm working with Ajax for the first time and I'm trying to translate an ajax request from javascript to jquery and can't figure out how to do it.
Here is my javascript code:
function aaa(track_id) {
var req = new XMLHttpRequest();
req.open("get", "list.php?tr=" + track_id, true);
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.onreadystatechange = bbb;
req.send();
}
function bbb(e) {
if(e.target.readyState == 4 && e.target.status == 200) {
antwort = e.target.responseXML;
document.getElementById("title").firstChild.nodeValue = antwort.getElementsByTagName("ti")[0].firstChild.nodeValue;
document.getElementById("artist").firstChild.nodeValue = antwort.getElementsByTagName("art")[0].firstChild.nodeValue;
}
};
And here is the list.php:
<?php
header("Content-Type: text/xml; charset=utf-8");
$con = mysqli_connect("", "root", "", "music");
$res = mysqli_query($con, "SELECT * FROM tracks WHERE track_id = " . $_GET["tr"]);
$dset = mysqli_fetch_assoc($res);
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<data>";
echo " <tr>" . $dset["track_id"] . "</tr>";
echo " <ti>" . $dset["title"] . "</ti>";
echo " <art>" . $dset["artist"] . "</art>";
echo "</data>";
?>
Can anyone help me? Thanks in advance!

Whilst the other answers will "do the job", there are some refinements you can make.
jQuery has a specific get method which simplifies things, and in addition, you can put the data into an object passed to the get or ajax call instead of appending it to the url as in other answers:
function aaa(track_id) {
$.get( 'list.php',
{ tr: track_id },
function(data) {
var $antwort = $(data.responseXML);
$("#title").text($antwort.find("ti").text());
$("#artist").text($antwort.find("art").text());
}
);
}
Another improvement is to structure it as a Promise:
function aaa(track_id) {
$.get( 'list.php',
{ tr: track_id }
).done( function(data) {
var $antwort = $(data.responseXML);
$("#title").text($antwort.find("ti").text());
$("#artist").text($antwort.find("art").text());
});
}
The advantage of this is that you can chain error handling onto this relatively easily.
Turning to list.php, there are a few problems with it.
It would probably be better returning JSON instead of XML, as that would reduce the complexity of the success code, but obviously you can't do things like that if other applications expect an XML API.
<?php
// protect against MySQL injection by using parameters...
$query = '
SELECT track_id AS tr, title as ti, artist as art
FROM tracks
WHERE track_id=?';
$mysqli = new mysqli("", "root", "", "music");
// this needs more error checking...
$stmt = $mysqli->prepare( $query);
$stmt->bind_param( 's', $_GET['tr']);
$stmt->execute();
$result = $stmt->get_result();
$dset = $result->fetch_assoc();
// simpler to return JSON
header('Content-Type: application/json');
echo json_encode( $dset);
?>

jQuery.ajax() method is used to perform an AJAX (asynchronous HTTP) request.
function aaa(track_id) {
$.ajax({
url: "list.php?tr=" + track_id,
dataType: "json",
success: function (result) {
bbb(result);
}
});
}
function bbb(e) {
antwort = e;
document.getElementById("title").firstChild.nodeValue = antwort.getElementsByTagName("ti")[0].firstChild.nodeValue;
document.getElementById("artist").firstChild.nodeValue = antwort.getElementsByTagName("art")[0].firstChild.nodeValue;
};

The equivalent of making an AJAX in jQuery is $.ajax(). You can also put the XML in the response in to a jQuery object and traverse that to find the values you require. Given the logic you've shown, you could implement it like this:
function aaa(track_id) {
$.ajax({
url: 'list.php',
data: { tr: track_id },
success: function(data) {
var $antwort = $(data.responseXML);
$("#title").text($antwort.find("ti").text());
$("#artist").text($antwort.find("art").text());
}
});
}
This is assuming that the firstChild of the targeted elements is a textNode.

Related

Is there something special about the variables that are passed via AJAX?

I am trying to access a database and delete a review of a user, I have a method that I pass the user's ID and the ID of the review. This method functions properly using both the SQL command as well as when I call hard-coded variables, however, when I pass the code via AJAX my code says it completed successfully but does not actually do anything. Is there something special about the variables that are passed via AJAX?
This is my method:
public function deleteRating($userid, $reviewID)
{
echo "this is idUsers(IdUsers) = ".$userid." this is reviewID (ID)".$reviewID;
$conn = $this->connect("ratings");
$sql = "DELETE FROM ratedmovies WHERE IdUsers=? AND ID=?";
if(!$stmt = $conn->prepare($sql))
{
echo "False";
}
else
{
$stmt->bind_param("ss", $userid, $reviewId);
if(!$stmt->execute())
{
echo "Failed to delete";
}
else
{
echo "Sucessfull Deletion";
}
}
}
This is the code that calls the method:
<?php
session_start();
include "../Model/Includes/autoLoadCont.inc.php";
$reviews = new Review;
$ratingID = json_decode($_POST['ratingID']);
$user = $_SESSION['userId'];
$reviews->deleteRating($user, $ratingID);
?>
and this is the ajax that calls that function:
var deleteBtns = document.querySelectorAll(".deleteRating");
deleteBtns.forEach(function(button)
{
button.addEventListener("click" , function()
{
$.ajax({
type: "POST",
url: "Controller/deleteReview.php",
data: {ratingID:button.id},
success: function(result)
{
alert(result);
}
});
});
button.id;
});

Ajax MySQL query does not return current data

I want to write an Ajax request that Returns data from a MySQL-database. But it does not work properly, because the Ajax request does not return the current values of the mysql database, if data has changed. Instead it always returns the old data of the database. The php-file is working properly, if I open it in a browser, it shows the correct current data values. I found out, that the Ajax request only shows the correct current data values, if I first open the php-file manually in a browser. If I then again use the ajax request, it returns the correct current data. What am I doing wrong?
This is the code for the Ajax request:
var scannedTubes = (function() {
var tmp = null;
$.ajax({
async: false,
url: "ajaxtest.php",
success: function(response) {
alert("RESPONSE: " + response);
tmp = response;
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
return tmp;
})();
The code of the ajaxtest.php file is the following:
<?php
$con = mysqli_connect("", "root");
if(mysqli_connect_errno()){
echo "FAIL: " . mysqli_connect_error();
}
mysqli_select_db($con, "multitubescan");
$queryStr = "SELECT code FROM scan WHERE row = 0 AND code <> 'EMPTY'";
$res = mysqli_query($con, $queryStr);
$num = mysqli_num_rows($res);
$scannedTubes = "";
while($data = mysqli_fetch_assoc($res)){
$scannedTubes = $scannedTubes . " " . $data["code"];
}
$scannedTubes = $num . " " . $scannedTubes;
mysqli_close($con);
echo $scannedTubes;
?>
I suppose data is cached by your browser.
Make the url unique:
url: "ajaxtest.php",
to
url: "ajaxtest.php?rnd=" + Math.random() ,

Communication between JavaScript, PHP and MySQL

I'm trying to learn JavaScript to code for Cordova.
I read many tutorials, but none of them helped me with the folowing problem.
My cordova app is for testing very simple. Just a textbox and 2 buttons. Both Buttons calls a PHP script on my server. One button sends data to the PHP script to insert the value of the textfield in a MySQL database, the second button calls the same script and should write the values of the database to my cordova app.
Here is my
<?PHP
$response = array();
require_once __DIR__ . '/db_config.php';
$db_link = mysqli_connect (
DB_SERVER,
DB_USER,
DB_PASSWORD,
DB_DATABASE
);
mysqli_set_charset($db_link, 'utf8');
if (!$db_link)
{
die ('keine Verbindung '.mysqli_error());
}
if(isset($_POST['action']) && $_POST['action'] == 'insert'){
$name = $_POST['name'];
$sql = "INSERT INTO test.testTable (name) VALUES ('$name')";
$db_erg = mysqli_query($db_link, $sql);
if (!$db_erg){
echo "error";
}else{
echo "ok";
}
}
if(isset($_POST['action']) && $_POST['action']=='read'){
$sql = "SELECT * FROM testTable";
$db_erg = mysqli_query( $db_link, $sql );
if (!$db_erg )
{
$response["success"] = 0;
$response["message"] = "Oops!";
echo json_encode($response);
die('Ungültige Abfrage: ' . mysqli_error());
}
while ($zeile = mysqli_fetch_array( $db_erg, MYSQL_ASSOC))
{
//$response["success"] = $zeile['pid'];
//$response["message"] = $zeile['name'];
$response[]=$zeile;
}
echo json_encode($response);
mysqli_free_result( $db_erg );
}
?>
and here are my 2 functions in the cordova app:
function getNameFromServer() {
var url = "appcon.php";
var action = 'read';
$.getJSON(url, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
function sendNameToServer() {
console.log("sendNameToServer aufgerufen");
var url2send = "appcon.php";
var name = $("#Name").val()
var dataString = name;
console.log(dataString);
if ($.trim(name).length>0) {
$.ajax({
type: "POST",
url: url2send,
data: { action: 'insert', name: dataString },
crossDomain: true,
cache: false,
beforeSend: function () {
console.log("sendNameToServer beforeSend wurde aufgerufen");
},
success: function (data) {
if (data == "ok") {
alert("Daten eingefuegt");
}
if (data == "error") {
alert("Da ging was schief");
}
}
});
}
}
My Questions/Problems:
The sendNameToServer funtion works in that case, that the data will be inserted in my Database. But I never get the alert (the success: never called).
How can I pass "action = read" to the PHP script in the getNameFromServer() function?
The third question is a bit off topic, but is this art of code "save" or is it simple to manipulate the data between the cordova app and the server? What's the better way or how can I encrypt the transmission?
Here is one part answer to your question.
$.getJSON has a second optional parameter data that can be an object of information you want to pass to your script.
function getNameFromServer() {
$.getJSON("appcon.php", { action: 'read' }, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
Edit: Since you are using $.getJSON(), the request method is a GET, which means you have to use $_GET in your third if statement in your PHP script.
if(isset($_GET['action']) && $_GET['action'] == 'read'){

Ajax returns success but doesn't change the database

I'm developing a small script of js to edit a profile in the way facebook used to be (click a button, edit and save without reloading the page). The problem is that when I run it, the ajax function returns sucess but akes no changes on the database. The function os js is this:
$('.savebtn').click(function(){
var editdata = $(".editbox").val();
var parameter = $(this).closest("td").find("#parameter").text();
var datastring = "data="+editdata+"&parameter="+parameter;
var $t = $(this);
console.log(datastring);
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function()
{
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
});
});
(Ignore the $t thing, somehow this works like this, but not if I use $(this))
Ajax executes the code for sucess but doesn't update anything on the database.
The PHP code for the database is:
<?php
include_once("../../config/connect_db.php");
include_once("../../database/cliente.php");
$parameter = $_POST['parameter'];
$data = $_POST['data'];
$id = $_SESSION['id'];
var_dump($_POST);
try {
updateProfile($parameter, $data, $id);
}
catch (PDOException $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users
SET ? = ?
WHERE id = ?");
$stmt->execute(array($parameter, $data. $id));
}
EDIT: As pointed out, this could be a problem with trying to pass a column name as a parameter. Changed the code to the following, but with no sucess:
function updateProfile($parameter, $data, $id)
{
global $conn;
$query = "UPDATE biofood.users
SET $parameter = $data
WHERE id = $id";
$stmt = $conn->prepare($query);
$stmt->execute();
}
This line:
$stmt->execute(array($parameter, $data. $id));
I think should be
$stmt->execute(array($parameter, $data, $id));
(notice the comma after $data)
This might not solve your problem, but it might give you a better indication on where your problem is.
First, you are not checking whether it works or not as your updateProfile function returns nothing.
Modify your updateProfile function, so that it returns the number of rows affected. (BTW this is a safer way to write your function. If you can check or limit the value of $parameter prior to calling this function, it will be less prone to SQL injection.)
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users SET $parameter = ? WHERE id = ?");
$stmt->execute(array($data, $id));
return $stmt->rowCount(); // # of rows affected
}
In the script that calls this function, get the value and send it back as a response. We'll send back a JSON.
$response = array();
try {
$response['success'] = updateProfile($parameter, $data, $id);
} catch (PDOException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
header('Content-Type: application/json');
echo json_encode($response);
In your JavaScript file, make the following change:
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function (data) {
if (data.success) {
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
},
dataType: 'json'
});

best option to get php array variable in Javascript produced by php script that requested through an ajax call

Currently I am trying to create a live search bar that only produce 5 results max and more option if there is over 5 results. So what I have done so far is a jquery ajax script to call a php script that runs asynchronously on key up in textbox I have.
I want to get the php array then I will code it further using javascript.
This is my code now:
Javascript code
<script type="text/javascript">
function find(value)
{
$( "#test" ).empty();
$.ajax({
url: 'searchDb.php',
type: 'POST',
data: {"asyn": value},
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
});
}
</script>
SearchDb PHP code:
<?php
function searchDb($abc, $limit = null){
if (isset($abc) && $abc) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$abc%'";
if($limit !== null){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
$lists = array();
while ( $row = mysql_fetch_assoc($result))
{
$var = "<div>".$row["testa"]."</div>";
array_push($lists, $var);
}
}
return $lists;
}
$abc = $_POST['asyn'];
$limit = 6;
$lala = searchDb($abc);
print_r($lala);
?>
How can I get $lala
Have you considered encoding the PHP array into JSON? So instead of just echoing the array $lala, do:
echo json_encode($lala);
Then, on the Javascript side, you'll use jQuery to parse the json.
var jsonResponse = $.parseJSON(data);
Then you'll be able to use this jsonResponse variable to access the data returned.
You need to read jQuery .ajax and also you must view this answer it's very important for you
$.ajax({
url: 'searchDb.php',
cache: false,
type: 'post'
})
.done(function(html) {
$("#yourClass").append(html);
});
In your searchDb.php use echo and try this code:
function searchDb($str, $limit = null){
$lists = array();
if (isset($str) && !empty($data)) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$data%'";
if(0 < $limit){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
while ( $row = mysql_fetch_assoc($result))
{
$lists[] = "<div>".$row["testa"]."</div>";
}
}
return implode('', $lists);
}
$limit = 6;
$data = searchDb($_POST['asyn'], $limit);
echo $data;
?>
If you dont have or your page searchDb.php dont throw any error, then you just need to echo $lala; and you will get result in success part of your ajax function
ALso in your ajax funciton you have
//you are using data here
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
you must try some thing like this
success: function(data) {
var lala = data;
$( "#test" ).html($lala);
}

Categories

Resources