parse return data from html to ajax - javascript

I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?

Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});

You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.

Related

How to get the value of title image and content in ajax php

How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.

AJAX response from PHP script not working

I am searching this and other sites for hours now, so I'm getting pretty desperate. No code from many questions with the same topic here works.
I need to insert data into the database and display a message after it is done. Also, I am using AJAX with jQuery so it would be asynchronous. It works just fine, the data gets inserted, but no response message shows.
I am a beginner at PHP and can't understend why this won't work. Relevant code below.
PHP function call:
if(isset($_POST["function"]) && !empty($_POST["function"]) && $_POST["function"] == "cl-add") {
$dbb->addMember("MyUsername", $_POST["name"]);
//$dbb is a DataBaseBroker instance
}
PHP function from the Broker:
function addMember($username, $ime) {
$query = "INSERT INTO clan";
$query.=" (username, ime) ";
$query.="VALUES ('".$username."','".$ime."');";
$result = $this->mysqli->query($query);
if ($result) {
echo("You added a member: ".$ime);
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: ".mysqli_error($connection);
echo $response;
}
}
JQuery function declarations:
var addMember = function(name, responseFn) {
if (name === "") {
alert("Please enter a name");
return;
}
$.ajax({
type : 'POST',
url: '../includes/layout/cl.php',
dataType : 'json',
data : {
'name' : name,
'function' : 'cl-add'
},
success : function(data) {
responseFn(data); //not working, should alert
}
});
}
var responseCallback = function(data) {
alert(data);
}
And inside $(document).ready():
$(document).on('click', '#cl-add', function(evt) {
var name = $("#cl_frm input").val();
addMember(name, responseCallback);
});
On your code:
dataType : 'json',
The Ajax request is waiting for a JSON response but you are giving a text response.
You should change the dataType: to text or html depending on your needs.
dataType : 'html',
or
dataType : 'text',
PHP changes:
<?php
function addMember($username, $ime)
{
$query = "INSERT INTO clan";
$query .= " (username, ime) ";
$query .= "VALUES ('" . $username . "','" . $ime . "');";
$result = $this->mysqli->query($query);
$response = null;
if ($result) {
$response = "You added a member: " . $ime;
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: " . mysqli_error($connection);
}
echo $response;
exit;
}
Change dataType parameter to 'text'. Also you can alert an object in JavaScript, actually you are not trying to alert an object but i just wanted to mention it.

Need a way to send URL variable to PHP with jQuery

So I'm trying to make a basic mockup shoe store for one of my classes, but I've been looking for a way to take a variable in the url and send it to my PHP...
This is my php:
<?php
// This block allows our program to access the MySQL database.
// Stores your login information in PHP variables
require_once 'studentdb.php';
// Accesses the login information to connect to the MySQL server using your credentials and database
$db_server = mysql_connect($host, $username, $password);
// This provides the error message that will appear if your credentials or database are invalid
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($dbname)
or die("Unable to select database: " . mysql_error());
if(isset($_GET['model_id']) && is_generic($_GET['model_id'])) {
$model_id = $_GET['model_id'];
$result = mysql_query('CALL shoes(`'.$model_id.'`);');
$row=mysql_fetch_array($result);
echo $row['size'];
}
?>
and I was trying to get it to work with JavaScript/jQuery/ajax, but I couldn't find a method to get model_id (which is in the form of a setup) and pass it back to the PHP.
<script>
$("a").click(function(e) {
e.preventDefault;
var shoePrice = $(this).attr('href');
history.pushState({}, '', $(this).attr("href"));
$("a").attr('data-title', shoePrice);
return false;
});
</script>
Example of my tag:
<a href="?model_id=1" data-largesrc="images/shoe1.jpg" data-title="Test" data-description="Shoe description here" data-price="Price here"><img src="images/thumbs/shoe1.jpg" alt="img01"/>
PS: This is all in the same file..
EDIT:
Old PHP loop -
$model_id = isset($_GET['model_id']) ? $_GET['model_id'] : 0;
if($_GET["model_id"] === "") echo "model_id is an empty string \n";
if($_GET["model_id"] === false) echo "model_id is false \n";
if($_GET["model_id"] === null) echo "model_id is null \n";
if(isset($_GET["model_id"])) echo "model_id is set \n";
if(!empty($_GET["model_id"])) echo "model_id is not empty \n";
if(isset($model_id)) {
$query = 'SELECT size, price, style FROM shoes WHERE model_id='.$model_id;
$search1 = 'SELECT * FROM shoes WHERE model_id='.$model_id;
$abc = mysql_query($search1);
$result = mysql_query($query);
// The mysql_num_rows function returns an integer representation of number of rows for the table passed as an argument
$number_of_requests = mysql_num_rows($result);
if(! $result) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "Shoe ID: {$row['model_id']} <br>".
"Shoes Size: {$row['size']}<br>".
"Shoe Price: {$row['price']}<br>".
"Shoes Style: {$row['style']}<br>";
}
while($row = mysql_fetch_assoc($abc)) {
$size = $row['size'];
}
}
Assuming you are sending request to same page as the href shows all you need is a $.get in the click handler
$("a").click(function(e) {
e.preventDefault;
var shoePrice = $(this).attr('href');
history.pushState({}, '', $(this).attr("href"));
$("a").attr('data-title', shoePrice);
$.get(shoePrice , function(serverResponse){
// do something here with response
})
});
$,get is a shorthand method for $.ajax.
If you are receiving json can replace $.get with $.getJSON
Here is what I've actually come up with, this is the final version that works... Thank you for your help, but I had to dig deeper to figure it out.
<script>
function parseData(html) {
var json = {};
$.each(document.getElementsByTagName("div"), function(index, value) {
json[value.id] = value.innerHTML;
});
return json;
};
$("a").click(function(e) {
e.preventDefault();
var href = $(this).attr("href");
history.pushState({}, '', $(this).attr("href"));
$.get("/~huntcki3/test.php"+$(this).attr("href"), function(data) {
var info = JSON.parse(data);
console.log(info);
console.log(href);
$("div.og-details h3")[0].innerHTML = info.name;
$("div.og-details p")[0].innerHTML = info.style+'<br>' + 'Size: ' + info.size+'<br>' + '$' + info.price+' USD';
});
});
</script>

Textbox and AJAX data from mySQL

Hello I have a textbox and when I type something in it should update the page with the mySQL data via AJAX.
So Im trying to get live updated database results whenever you type something in the textbox. The goal is to get a textbox that is getting data from the mySQL database.
I have written the code so far, hopefully someone can advise me in this mather, thank you.
$select = 'SELECT *';
$from = ' FROM overboekingen';
$where2 = ' WHERE naam_klant LIKE % . $val . % ';
$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
$val = (isset($_POST['txt']) ? $_POST['txt'] : FALSE);
if (is_array($opts) || $val) {
$where = ' WHERE FALSE';
if (in_array("naam_klant", $val)){
$where2.val;
}
}
else {
$where = false;
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
AJAX
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {text: val},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
You must define the PHP $val variable before.
The correct sytax:
$where2 = " WHERE naam_klant LIKE %$val% ";

JSON Encode Failure

PHP PAGE:
<?php
include "linkpassword.inc";
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_assoc($showresult);
}
function addVote()
{
$sql= "UPDATE mms SET votes = votes+1 WHERE color = '".$_POST['color']."'";
$result= mysql_query($sql) or die(mysql_error());
return $result;
}
addVote();
showVotes();
?>
I am trying to get the output of the array to load into a JavaScript page where I can break up the array into seperate divs that have IDs assigned to them. Here is what I tried
<script>
$(document).ready(function () {
$('.answer').click(function (e) {
var color = $(this).attr("data-color");
$.ajax({
type: 'POST',
url: 'mm.php',
data: { color: color},
dataType: 'json',
cache: false,
success: function(showVotes) {
$('#rvotes').html(showVotes[0]);
},
error: function (jqXHR) {
}
})
})
});
</script>
Where am I going wrong??
From what you've posted in comments, what you have is an array of objects.. not html, as your function seems to indicate. Depending on what you want done, the answer would be either of the following, to access that object's properties:
showVotes[0].votes
Or
showVotes[0]['votes']
Eg:
$('#rvotes').html(showVotes[0].votes);
Or etc.
Second attempt:
Firstly, change your current 'showVotes' function to this:
function showVotes()
{
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_assoc($showresult)) {
$response[] = $row;
}
return json_encode($response);
}
Secondly, remove your 'connected successfully' text from the page, as well as any other text generated by anything else(aka, the other function which returns a result pointer). I may be wrong, but it would seem to me that the generation of this other text is causing the returned json to be interpreted as malformed.
Quick explanation on PDO:
try {
$dbh = new PDO("mysql:host=localhost;dbname=dbname", "user", "password");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (\PDOException $e) {
echo "Error! Could not connect to database: " . $e->getMessage() . "<br/>";
die();
}
Connecting to the database.. This is how I've learned to do it, though I've been warned(and downvoted) to not check for errors this way, though it was never explained why.
Database interaction:
$stmt = $dbh->prepare("UPDATE mms SET votes = votes+1 WHERE color = :color");
$stmt->bindParam(":color",$_POST['color']);
$stmt->execute();
Result use:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$response[] = $row;
}
And so on and so forth. PDO escapes the values for you, so you don't have to worry about injection attacks.

Categories