Okay my problem is the following:
I am trying to access a variable I defined with javascript in my executing php-script.
// CLIENT SIDE CODE
function deleteEntry() {
var action = '_includes/deleteEntry.php';
var method = 'post';
var data = '2';
$.ajax({
url: action,
type: method,
data: data
}).done(function(data){
$('.main').empty();
$('.main').append(data);
});
};
Now I want to make use of my data in a php-script (deleteEntry.php)
// SERVER SIDE CODE
<?php
// VERBINDUNG //
$connection = mysqli_connect('localhost', 'root', '', 'aufgabenplaner');
// if (!$connection){
// die('Verbindung nicht möglich : ' . mysql_error());
// }
// SQL-ABFRAGE //
$query = "DELETE FROM aufgaben WHERE job_nr =" ."DATA GOES HERE!!!";
$result = mysqli_query( $connection, $query );
include 'main-content.php';
?>
Where it says "DATA GOES HERE!!!" I want to make use of the data value, but I don't know how.
Normally you pass a JSON object as your POST
$.ajax({
url: action,
type: 'post', //put your declaration here for readability
data: {'var' : 2}
})
Then you would use $_POST['var'] in your PHP to get the value
You have to prepare data object so it has key - value pairs. This way you'll be able to access data in your PHP script. JavaScript:
function deleteEntry() {
var action = '_includes/deleteEntry.php';
var method = 'post';
var data = { number: '2'};
$.ajax({
url: action,
type: method,
data: data
}).done(function(data){
$('.main').empty();
$('.main').append(data);
});
};
PHP:
// SERVER SIDE CODE
<?php
// VERBINDUNG //
$connection = mysqli_connect('localhost', 'root', '', 'aufgabenplaner');
// if (!$connection){
// die('Verbindung nicht möglich : ' . mysql_error());
// }
// SQL-ABFRAGE //
$number = (int)$_POST['number']; // make sure it's no malicious input from user
$query = "DELETE FROM `aufgaben` WHERE `job_nr` = '" . $number . "'";
$result = mysqli_query( $connection, $query );
include 'main-content.php';
?>
Related
I'm trying to retrieve the latest video ID number from my database and then use that ID number to hashchange my URL and display the corresponding video. My PHP is working and returning a result but I'm not sure how to take that result and use it in jQuery so that I can use it for the hashchange. I haven't used jQuery much before so any detailed help would be amazing! Please find my current code below. The main question I have is how do I pass the $vidarray to jQuery so I can use that variable?
videoprocess.php
<?php
// Connect To DB
$hostname="localhost";
$database="MYDB";
$username="root";
$password="";
#$conn = mysqli_connect($hostname, $username, $password)
or die("Could not connect to server " . mysql_error());
mysqli_select_db($conn, $database) or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
// Display Error message if fails
echo 'Error, could not connect to the database please try again again.';
exit();
}
$query = "SELECT VIDEOID FROM JubileeTouchVideo ORDER BY ID DESC LIMIT 1";
$result = mysqli_query($conn, $query) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$vidarray = array();
while($row = mysqli_fetch_assoc($result))
{
$vidarray = $row;
}
echo json_encode($vidarray);
//close the db connection
mysqli_close($conn);
?>
videoprocess jquery
$.ajax({
url: "data.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//Not sure what to do after this
}
});
This is how you can pass data to ajax.
$.ajax({
type: "POST",
url: url,
data: <?php echo $vidarray["id"]; ?>,
dataType: "text",
success: function(result) {
//result downloaded so we call parseJSON function
//and pass downloaded result
var json = $.parseJSON(result);
//Not sure what to do after this
}
});
This question already has answers here:
jQuery AJAX cross domain
(15 answers)
Closed 8 years ago.
I'm starting developing an app and I'm having trouble with the login.
I have a form with an Ajax call to a PHP service to validate the user, I uploaded both files to my server and it works perfect. I input user and password, goes to the PHP file and validate the user, so far so good.
The problem is that these two files will be in different servers. Now I have the PHP file hosted on my server, and the form/ajax call localhost and it doesn't work.
Here's the code:
PHP:
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "****";
$password = "****";
$database = "*****";
$con = mysql_connect($server, $username, $password) or die ("Error: " . mysql_error());
mysql_select_db($database, $con);
$user = mysql_real_escape_string($_POST["user"]);
$pass = mysql_real_escape_string($_POST["pass"]);
$result = mysql_query("SELECT * FROM Usuarios WHERE IdUsuario = '" . $user . "' AND Clave = '" . $pass . "'");
$numResults = mysql_num_rows($result);
echo $numResults;
mysql_close($con);
?>
JS:
$( document ).ready(function() {
$('form').submit(function(event){
event.preventDefault();
var user = $(this).find("#user").val();
var pass = $(this).find("#pass").val();
$.ajax({
type: 'POST',
crossdomain: true,
data: 'user=' + user + '&pass=' + pass,
url: 'http://www.url.com/login.php',
success: function(data){
if(data == 1){
alert("YES!");
}else{
alert("NO");
}
},
error: function(){
alert('Error');
}
});
return false;
});
});
I have also tried with dataType: "json" and "jsonp"
You need to change
data: 'user=' + user + '&pass=' + pass,
to
data: {user : user, pass : pass},
I'm trying to use AJAX to send values to PHP file, which then updates mysql database on the server. But for some reason the values are not transferred to PHP file.
This is the JS I use:
function send_message()
{
var number = localStorage.getItem("number");
var message = prompt("Message:", "");
jQuery.ajax({ type: "POST",
url: serviceURL + "message.php",
data: 'number='+number+'&message='+message,
cache: false,
success: function(response)
{
alert("message sent");
}
});
}
And this is the message.php
<?php
include 'config.php';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$number = $_GET['number'];
$message = $_GET['message'];
// query
$sql = "INSERT into table
SET condition=0, change=1, change_time=NOW(), recieve=999,
number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));
?>
Everything else is inserted to mysql except the number and message are NULL. What could be the reason for this?
You're posting data with AJAX using POST. In order to listen for those values in PHP you need to...
Replace:
$number = $_GET['number'];
$message = $_GET['message'];
With:
$number = $_POST['number'];
$message = $_POST['message'];
To make things simpler just use a convenience method like $.post or $.get for ajax calls in jQuery:
function send_message()
{
var number = localStorage.getItem("number");
var message = prompt("Message:", "");
$.post(serviceURL + "message.php", {'number' : number, 'message' : message},
function(response){
alert("message sent");
}
);
}
Then in your php:
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
//if you used $.get you will also have to use $_GET here
$number = $_POST['number'];
$message = $_POST['message'];
// query
$sql = "INSERT into table
SET condition=0, change=1, change_time=NOW(), recieve=999,
number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));
?>
I can see that you're using prepared statements in PDO. But you may also want to add:
Filter Vars and Filter Input for additional security.
Use $_POST instead of $_GET.
Also, you can try to use $_REQUEST global array to forget about it. It has all the data you have sent to script.
You may change your php file to;
<?php
include 'config.php';
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$number = $_POST['number'];
$message = $_POST['message'];
// query
$sql = "INSERT into table
SET condition=0, change=1, change_time=NOW(), recieve=999,
number=?, message=?";
$q = $conn->prepare($sql);
$q->execute(array($number, $message));
?>
I want to return JSON data from a resulted SQL statement in a PHP script upon pressing Submit button, but I receive null instead.
I'll be using the returned JSON to filter-show markers on my Google Map, but for now I just want to get the data back across to my jQuery page from PHP script so I can manipulate/use it.
Submit button:
HTML
<input type="submit" id="filter" value="Filter" />
JS
$('#myform').on('submit', function(e) {
e.preventDefault();
var myData = $('#myform').serializeArray();
$.getJSON('myscript.php', myData, function(json){
alert(json);// actually filter for later
});
});
PHP script:
// action is a hidden form control I use to check if form was submitted
if(isset($_POST["action"])){
if(isset($_POST["color"]) && isset($_POST["zipcode"])){
// try to open a connection to a MySQL server
$connection = mysql_connect($host, $username, $password) or die("Could not connect" . mysql_error());
// select the active MySQL database to work with
$db_selected = mysql_select_db($database, $connection) or die("Can\'t use db:" . mysql_error());
$query = 'sql statement to return resutls based on what color and zipcode was provided';
$result = mysql_query($query) or die("Can\'t do that: " . mysql_error());
}
// close connection to the database
echo json_encode($result);
mysql_close($connection);
}
You can't return the result object of a mysql_query call directly. You first have to parse it with functions like mysql_fetch_array or alike (PHP docu).
...
$result = mysql_query($query);
if ( $result === false ) {
die("Can\'t do that: " . mysql_error());
}
$retVal = array();
while( $row = mysql_fetch_array( $result ) ) {
$retVal[] = $row;
}
...
echo json_encode( $retVal );
EDIT
According to the jQuery spec for getJSON (link), the data is sent using GET parameters and not using POST. So you would have to change all the $_POST appearances in your PHP code to either $_GET or $_REQUEST.
Besides this, you should return some error messages if your variables are not set. Right now (according to your code) just an empty document is returned.
Before the echo you should declare the returned content type:
header('Content-Type: application/json');
If you want to check for the receival of the data you can use:
$.ajax({
url: url,
data: myData,
success: function(json) {},
error: function(json) {} // this should allow you to check if data is received (but since the content type is set to text/html and $.getJSON expectr application/json it won't be a success)
});
I am working on a PhoneGap with Android project. I have designed a login page in which I want to show an alert box for a valid and invalid user. I am using PHP for database validation.
This is my php page:
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id, name,password FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
This is my java script function:
function onDeviceReady(){
var output = $('#output');
var id = document.getElementById('userid').value;
var pass = document.getElementById('password').value;
// webcam.set_api_url( 'test.php?filename=' + escape(filename));
$.ajax({
url: 'http://192.168.1.214/sample/dologin.php?id='+id+'&password='+pass,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
console.log('entered success============');
$.each(data, function(i,item){
var logi=item.id;
if(logi!=null)
alert("valid user");
else
alert("invalid user");
});
},
error: function(){
console.log('entered success====================');
output.text('There was an error loading the data.');
}
});
}
This is not working properly for an invalid user. Whenever I enter a valid user name and password then it displays the valid user message box. When I enter an invalid user name and password then it doesn't display anything.
Thank you in advance...
Try debugging this in a browser and perhaps send the returned jsonp data to the console from within your ajax's success call console.log(data).
It's quite possible that your jsonp is returning some data as opposed to null... even if it is simply undefined or an empty string. Your conditional is most likely the culprit.