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>
Related
I'm unable to retrieve the q parameter sent from the PHP.
When I run my code, null values get inserted in my database.
Here are the concerning parts of my code:
My JavaScript function:
function load_now(str){
//alert(str);
var id = str.split("+")[0];
var r = confirm("Start load process for scooter " + str + "?");
if (r == true) {
var xmlhttp = new XMLHttpRequest();
//console.log(str);
xmlhttp.open("GET", "load_scooter_action.php?q=" + str, true);
xmlhttp.send();
}
}
and my load_scooter_action.php file:
<?php
require "checkUserModel.php";
require "databaseController.php";
$databaseController = new DatabaseController();
$databaseController->startConnexionToDatabase();
$conn = $databaseController->getConn();
$dateObject = new DateTime();
$startTime = $dateObject->format('Y-m-d H:i:s');
$user = $_SESSION['user-id'];
// get the q parameter from URL
$q = $_REQUEST["q"];
//forme:(scooter, lat, lng, chg);
$val = explode("+",$q);
$scooter = val[0];
$lat = val[1];
$lng = val[2];
$chg = val[3];
echo "<script type='text/javascript'> console.log(".$q.")</script>";
$sql = "UPDATE `scooters` SET `disponible` = '0' WHERE `scooters`.`numero` = '$scooter';";
if ($conn->query($sql) === TRUE) {
$add = "\nScooter Taken";
} else {
$add = "Error Taking scooter" . $conn->error;
}
$sql = "
INSERT
INTO Reloads(scooter, user, initialLoad, finalLoad, sourceX, sourceY,destinationX, destinationY, startTime,endTime)
VALUES ('$scooter','$user','$chg',null,'$lat','$lng',null ,null, '$startTime', null)";
if ($conn->query($sql) === TRUE) {
//echo "\nNew record created successfully";
//echo '<script>window.location.href = "../php/scooterMapIndex.php";</script>';
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Could you help me have a clear understanding of my mistake?
Thanks in advance.
EDIT
str is has the following form 599+50.8037+4.32782+4
Two mistakes:
The first one is a quick fix. Replace val with $val
The second one is that, although str is of the form 599+50.8037+4.32782+4 in the .js file, $q gets retrieved without the + characters in the .php file. Therefore it has to be split appropriately.
Can you show me that what is passed in str or which value is passed in str load_now function. Do you get value when you alert(str)?
If yes then try below function
$.ajax({
type: 'GET',
url: 'follow_user.php?user_id='.urlencode($user_id),
success: function(data) {
alert('done');
}
});
Thanks
I have created a search using ajax and php, however when I click the search button nothing happens. There are no errors, however when I look at the network in the console it doesn't seem to be reaching searching.php as this file doesn't show up in the network. I want to be able to put the returned data from the search into seperate divs, although at the minute it isn't returning any data at all and I have no idea why.
This is my php
require_once('config1.php');
$output = '';
if(isset($_POST['search']) === true && empty($_POST['search']) === false){
$query = "SELECT a.attraction_name, a.lat, a.long, a.cost, a.image FROM zz_attractions a INNER JOIN zz_city c ON a.city_id = c.city_id WHERE c.city_name = '" . mysqli_real_escape_string(trim($_POST['search'])) . "' ";
$result = mysqli_query($conn, $query);
$count = mysqli_num_rows($result);
if ($count == 0) {
$output = 'there was no search results';
} else {
while ($row = mysqli_fetch_array($result)) {
$attraction_name = $row['attraction_name'];
$lat = $row['lat'];
$long = $row['long'];
$cost = $row['cost'];
$image = "<img src='{$row['image']}' height='100' width='100'>";
$output .= '<div>'.$attraction_name.' '.$lat.' '.$long.' '.$cost.' '.$image.'</div>';
}
}
}
This is my ajax
$('#submit').on('click', function() {
var search = $('#search').val();
if ($.trim(search) != '') { //if search is not equal to nothing - using trim allows users to type in blank space and it won't return anything
$.post('searching.php', {search: search}, function(data) {
$('#return').text(data);
});
}
});
Within the html the div id is #return. If someone could help me find out why no data is returning that would be great.
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.
we have a form that we can click on a number at the top of the form in order to load the according data, to be more specific i can have 4 inputs in my table in the database and when I click on number 2 which is the id of the data then it loads the data. We did that but now we want to update the clicked data and until now we cant find a way to GET the correct number(id) and place it in the UPDATE statement.
Below is the code of the clicked functions and of the UPDATE statement.
//Education Scripts
$("#updateEdu").click(function () {
$("#idE").css("display", "none");
var r = parseInt($("#idE").val(), 10) + 1;
$("#idE").val(r);
});
$('[data-row-ide]').click(function (e) {
e.preventDefault();
var fileName = 'addCV.php?idEdu='; //"addCV.php" the name of this file in your project, the "?" starts the GET parameters, idWork= sets the key for the GET parameter
var id = $(this).data('row-ide'); // this gets the id that we stored in the link's data attribute
var url = fileName + id; // then we add that id as the value for the "idWork" key
window.location = url; // esentially refresh this page with the id set as a GET parameter and make use of the logic we already have to load the info
});
<?php
$username = $_SESSION["username"];
if(isset($_POST['updateEdu'])){
$parts = parse_url($url);
parse_str($parts['query'], $query);
$id = $query['idEdu'];
$username = $_SESSION['username'];
$school = mysql_real_escape_string($_POST["school"]);
$degree = mysql_real_escape_string($_POST["degree"]);
$website = mysql_real_escape_string($_POST["website"]);
$start_date = mysql_real_escape_string($_POST["start_date"]);
$end_date = mysql_real_escape_string($_POST["end_date"]);
$start_year = mysql_real_escape_string($_POST["start_year"]);
$end_year = mysql_real_escape_string($_POST["end_year"]);
$degree_description = mysql_real_escape_string($_POST["degree_description"]);
if($start_year > $end_year){
echo 'The Start Year must be smaller than the End Year!';
$id=$id-1;
$good = false;
}
else{
$good = true;
}
if($good == true){
$query="UPDATE education
SET school = '$school', degree = '$degree', website = '$website', start_date='$start_date', end_date='$end_date', start_year='$start_year', end_year='$end_year', degree_description='$degree_description'
WHERE id='$id' AND username='$username'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>0){
echo "<p>Record Updated<p>";
echo "<script type='text/javascript'>;
/window.location='addCV.php';
</script>";
}
else{
echo "<p>Error Updating Record<p>";
echo "<script type='text/javascript'>;
</script>";
}
}
}
else if(isset($_GET['idEdu'])){
// user clicked on one of oue id links to get here
// set the id the the value of the GET parameter for key "idWork"
$id = $_GET['idEdu'];
}
else{
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT school,degree,website,start_date,end_date,start_year,end_year,degree_description,id FROM education
WHERE username='%s' ORDER BY id LIMIT 1",
mysql_real_escape_string($username));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
}
}
To get the value of an elements attribute in jquery you use the attr() function like so:
$(element).attr('attributeName')
So you should change:
var id = $(this).data('row-ide');
into
var id = $(this).attr('row-ide');
in your function $('[data-row-ide]').click(function (e) {};
Hi I have a PHP file with data. The value is passed on to another php file which process it successfully. But the first php file does not refresh to update the new result. It have to do it manually. Can any one tell me where I'm wrong or what needs to be done. Please find my code below.
PHP code (1st page, index.php)
function display_tasks_from_table() //Displayes existing tasks from table
{
$conn = open_database_connection();
$sql = 'SELECT id, name FROM todolist';
mysql_select_db('todolist'); //Choosing the db is paramount
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
echo "<form class='showexistingtasks' name='showexistingtasks' action='remove_task.php' method='post' >";
while($row = mysql_fetch_assoc($retval))
{
echo "<input class='checkbox' type='checkbox' name='checkboxes{$row['id']}' value='{$row['name']}' onclick='respToChkbox()' >{$row['name']} <img src='images/show_options.gif' /><br>";
}
echo "</form>";
echo "<label id='removeerrormsg'></label>";
close_database_connection($conn);
}
Javascript code which finds the selected value:
var selVal; //global variable
function respToChkbox()
{
var inputElements = document.getElementsByTagName('input'),
input_len = inputElements.length;
for (var i = 0; i<input_len; i++)
{
if (inputElements[i].checked === true)
{
selVal = inputElements[i].value;
}
}
}
jQuery code which passes value to another page (remove_Task.php):
$(document).ready(function() {
$(".checkbox").click(function(){
$.ajax({
type: "POST",
url: "remove_task.php", //This is the current doc
data: {sel:selVal, remsubmit:"1"},
success: function(data){
//alert(selVal);
//console.log(data);
}
});
});
});
PHP code (2nd page, remove_task.php);
session_start();
error_reporting(E_ALL);ini_set('display_errors', 'On');
$task_to_remove = $_POST['sel'];
function remove_from_list() //Removes a selected task from DB
{
$db_connection = open_database_connection();
global $task_to_remove;
mysql_select_db('todolist');
$sql = "DELETE FROM todolist WHERE name = "."'".$task_to_remove."'";
if($task_to_remove!='' || $task_to_remove!=null)
{
mysql_query($sql, $db_connection);
}
close_database_connection($db_connection);
header("Location: index.php");
}
if($task_to_remove != "") {
remove_from_list();
}
The selected value is getting deleted but the display on index.php is not updated automatically. I have to manually refresh to see the updated result. Any help would be appreciated.
By calling header("Location: index.php"); you don't redirect main page. You sent an ajax request - you can think about it as of opening a new page at the background, so this code redirects that page to index.php.
The better way to solve your task is to return status to your success function and remove items which were deleted from the database.
success: function(data){
if(data.success){
//remove deleted items
}
}