The javascript parameter "Step" should trigger a switch-case function in php. If Step is one than trigger this piece of code in php and return the output by JSON.
If I take a look in firebug the post string is: Step=one&inputFname=rick&inputLname=bovenkamp I think this is correct. So the problem must be in the php file and I think it's in the $_POST part...
What am I doing wrong? Any help would be very great!
javascript code:
$(document).ready(function() {
$("form#userForm").submit(function() {
var inputFname = $('#inputFname').attr('value');
var inputLname = $('#inputLname').attr('value');
var Step = "one";
$.ajax({
type: "POST",
url: "main.php",
data: {Step: Step,inputFname: inputFname,inputLname: inputLname},
dataType: "json",
contentType:"application/json; charset=utf-8",
success: function(data) {
$("p.succesText").html(data.jsCode);
$("form#userForm").hide();
$("div.success").fadeIn();
},
error: function(xhr, status, error) {
$("form#userForm").hide();
$("p.errorHead").html("Something went wrong.");
$("p.errorText").text("ResponseText: " + xhr.responseText
+ "Statuscode: " + xhr.status
+ "ReadyState: " + xhr.readyState);
$("div.error").fadeIn();
}
});
return false;
});
});
PHP file:
<?php header('content-type: application/json; charset=utf-8');
$log = array();
$varStep = htmlspecialchars(trim($_POST["Step"]));
switch($varStep) {
case "one":
$varFname = htmlspecialchars($_POST["inputFname"]);
$varLname = htmlspecialchars($_POST["inputLname"]);
//Make Database connection
$db = mysql_connect("192.168.178.254","root","852456");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("Ajax" ,$db);
//Generate code and check if code already exists in the database
do
{
$varCode = rand(10000, 99999);
$dbCheckCode = "";
$dbCheckCode = mysql_query("SELECT * FROM TableAjax WHERE code='$varCode'");
}
while (mysql_fetch_array($dbCheckCode) !== false);
//Save the Form data in the database
$sql = "INSERT INTO TableAjax (fname, lname, code) VALUES (".PrepSQL($varFname) . ", " .PrepSQL($varLname) . ", " .PrepSQL($varCode) . ")";
mysql_query($sql);
//Return code to frontend
$log['jsCode'] = $varCode;
break;
}
echo json_encode($log);
//Clean SQL statement
function PrepSQL($value)
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
Put Step in quotes data : {"Step" : Step,....
You are passing the value of the variable as the key in that case, that is to say you are actually passing data : {"one" : "one",.... You should do the same with inputLname and inputFname.
Edit - Explanation
If you look at what the contentType options does here at http://api.jquery.com/jQuery.ajax/, you will see that the default is application/x-www-form-urlencoded which is what you want. Essentially what your PHP error was indicating is that the $_POST array was empty because it did not know how to read your data due to the format. You want your return data to be json, the dataType option was all you needed.
You still would have needed to do what I indicated in the first part of the post, but essentially you had two errors that were tripping you up.
I hope this makes sense!
Related
I have read all the related questions that reference to this topic, but still cannot find answer here. So, php and ajax works great. The problem starts when i try to include json, between php and ajax, to passing data.
here is my ajax:
function likeButton(commentId, userId, sessionUserId) {
// check if the comment belong to the session userId
if(sessionUserId == userId) {
alert("You cannot like your own comment.");
}
else if(sessionUserId != userId) {
var like_upgrade = false;
$.ajax({
url: "requests.php",
type: "POST",
dataType: "json",
data: {
keyLike: "like",
commentId: commentId,
userId: userId,
sessionUserId: sessionUserId,
like_upgrade: like_upgrade
},
success: function(data) {
var data = $.parseJSON(data);
$("#comment_body td").find("#updRow #updComLike[data-id='" +commentId+ "']").html(data.gaming_comment_like);
if(data.like_upgrade == true) {
upgradeReputation(userId);
}
}
});
}
}
Note, that i try not to include this:
var data = $.parseJSON(data);
Also i tried with diferent variable like so:
var response = $.parseJSON(data);
and also tried this format:
var data = jQuery.parseJSON(data);
None of these worked.
here is requests.php file:
if(isset($_POST['keyLike'])) {
if($_POST['keyLike'] == "like") {
$commentId = $_POST['commentId'];
$userId = $_POST['userId'];
$sessionUserId = $_POST['sessionUserId'];
$sql_upgrade_like = "SELECT * FROM gaming_comments WHERE gaming_comment_id='$commentId'";
$result_upgrade_like = mysqli_query($conn, $sql_upgrade_like);
if($row_upgrade_like = mysqli_fetch_assoc($result_upgrade_like)) {
$gaming_comment_like = $row_upgrade_like['gaming_comment_like'];
}
$gaming_comment_like = $gaming_comment_like + 1;
$sql_update_like = "UPDATE gaming_comments SET gaming_comment_like='$gaming_comment_like' WHERE gaming_comment_id='$commentId'";
$result_update_like = mysqli_query($conn, $sql_update_like);
$sql_insert_like = "INSERT INTO gaming_comment_likes (gaming_comment_id, user_id, user_id_like) VALUES ('$commentId', '$userId', '$sessionUserId')";
$result_insert_like = mysqli_query($conn, $sql_insert_like);
$like_upgrade = true;
//json format
$data = array("gaming_comment_like" => $gaming_comment_like,
"like_upgrade" => $like_upgrade);
echo json_encode($data);
exit();
}
}
Note: i also try to include this to the top of my php file:
header('Content-type: json/application');
but still not worked.
What am i missing here?
Don't call $.parseJSON. jQuery does that automatically when you specify dataType: 'json', so data contains the object already.
You should also learn to use parametrized queries instead of substituting variables into the SQL. Your code is vulnerable to SQL injection.
I want to check if a user has favourited an item but I'm unsure how to return the result of a database query to ajax.
I will show different html depending on the result.
Php
$query = "SELECT itemID from favourites WHERE userid = '" . $user. "'";
$result = mysql_query($query);
echo json_encode($result);
Jquery
$.ajax({
url: "inc/functions.php",
type: "POST",
data: {--result--},
success: function () {
// if result found in database
$('favourite').hide();
// if result not found
$('favourite').show();
}
});
I can't figure out how to display $result in the jquery code.
Any help much appreciated.
$result in this case is a PHP object representing a result.
You will have to use a fetch() method in order to extract the result before sending it back to your JS.
See this link. There's a list of all fetch-family method right above the comments.
Also, you will need to make a connection with you database beforehand using mysqli_connect (or mysql_connect in your case).
As stated in the comments, you should however use mysqli* functions family instead of mysql*.
Thanks to the comments for info regarding mysqli. I updated the code and solved the ajax part.
For anyone else stuck, I got it working like this:
PHP
require ("../../connection.php");
$sql = "SELECT * FROM favourites WHERE userID = ? AND itemID = ?";
$user = $_POST['userID'];
$item = $_POST['itemID'];
$statement = $db->prepare($sql);
if($statement === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $db->error, E_USER_ERROR);
}
$statement->bind_param('ii',$user,$item);
$statement->execute();
$statement->bind_result($user,$item);
while($statement->fetch()){
echo 1;
}
$statement->close();
Jquery
$.ajax({
url: "inc/userList.php",
data: userList,
type: "POST",
success: function (result) {
if (result == 1){
$('#addItem').css('display', 'none');
$('#removeItem').css('display', 'inline-block');
} else {
$('#addItem').css('display', 'inline-block');
$('#removeItem').css('display', 'none');
}
}
});
i want to insert data to mysql database using php service and json but when i click nothing happens it shows no error no message and the data is not added to the data base help please
here is the save function
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url:"http://localhost:800/test/insert.php",
type: 'POST',
data: data,
dataType: 'json',
success: function()
{alert("success");}
error: function()
{alert("fail");}
});
}
and this my php file insert.php
<?php
$json = $_POST['data'];
$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ($new['email'],$new['mdp'])";
if (mysqli_query($conn, $sql)) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
You don't have "data" key in your $_POST array, you have "email" and "mdp", which you can access directly:
$email = mysqli_real_escape_string($_POST['email']);
$mdp = mysqli_real_escape_string($_POST['mdp']);
There is no json passed in this way, similarly when you have get string, you also don't need to parse it. Turn on error reporting, then you will see that $_POST['data'] is undefined.
BTW, use mysqli_real_escape_string to sanitize the input to prevent from injection.
"Insert.php" - > Not use for get data $json = $_POST['data'];
Only use this and try
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$email = $_POST['email'];
$mdp = $_POST['mdp'];
$new1 = json_encode($email);
$new2 = json_encode($mdp);
$sql = "INSERT INTO user ('email','mdp') VALUES ('".$new1."','".$new2."')";
$insert = mysqli_query($sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Your PHP code seems to be correct, but please try the jQuery AJAX code as follows:
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
error: function () {
alert('fail');
},
success: function (data) {
alert('success');
}
});
}
In your data section has to be passed as JSON String, secondly you missed to in include the data contentType. Here content type is set as application/json, therefore pass the data as JSON string.
I am new to php/ajax/jquery and am having some problems. I am trying to pass json to the php file, run some tasks using the json data and then issue back a response. I am using the facebook api to get log in a user,get there details, traslate details to json, send json toe the server and have the server check if the users id already exists in the database. Here is my javascript/jquery
function checkExisting() {
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.id );
var json = JSON.stringify(response);
console.log(json);
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
}
Here is my php file
if(isset($_POST['user']) && !empty($_POST['user'])) {
$c = connect();
$json = $_POST['user'];
$obj = json_decode($json, true);
$user_info = $jsonDecoded['id'];
$sql = mysql_query("SELECT * FROM user WHERE {$_GET["id"]}");
$count = mysql_num_rows($sql);
if($count>0){
echo 1;
} else{
echo 0;
}
close($c);
}
function connect(){
$con=mysqli_connect($host,$user,$pass);
if (mysqli_connect_errno()) {
echo "Failed to connect to Database: " . mysqli_connect_error();
}else{
return $con;
}
}
function close($c){
mysqli_close($con);
}
I want it to return either 1 or 0 based on if the users id is already in the table but it just returns a lot of html tags. . The json looks like so
{"id":"904186342276664","email":"ferrylefef#yahoo.co.uk","first_name":"Taak","gender":"male","last_name":"Sheeen","link":"https://www.facebook.com/app_scoped_user_id/904183432276664/","locale":"en_GB","name":"Tadadadn","timezone":1,"updated_time":"2014-06-15T12:52:45+0000","verified":true}
Fix the query part:
$sql = mysql_query("SELECT * FROM user WHERE {$_GET['id']}");
Or another way:
$sql = mysql_query("SELECT * FROM user WHERE ". $_GET['id']);
Then it's always better to use dataType in your ajax
$.ajax({
url: "php.php",
type: "POST",
data: {user: json},
dataType: "jsonp", // for cross domains or json for same domain
success: function(msg){
if(msg === 1){
console.log('It exists ' + response.id );
} else{
console.log('not exists ' + response.id );
}
}
})
});
Where is $jsonDecoded getting assigned in your PHP? Looks unassigned to me.
I think you meant to say:
$obj = json_decode($json, true);
$user_info = $obj['id'];
And your SELECT makes no sense. Your referencing $_GET during a POST. Maybe you meant to say:
$sql = mysql_query("SELECT * FROM user WHERE id = {$user_info}");
I'm trying to update my database on the event of a change in my select box. The php file I'm calling on to process everything, works perfectly. Heres the code for that:
<?php
$productid = $_GET['pID'];
$dropshippingname = $_GET['drop-shipping'];
$dbh = mysql_connect ("sql.website.com", "osc", "oscpassword") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("oscommerce");
$dropshippingid = $_GET['drop-shipping'];
$sqladd = "UPDATE products SET drop_ship_id=" . $dropshippingid . "
WHERE products_id='" . $productid . "'";
$runquery = mysql_query( $sqladd, $dbh );
if(!$runquery) {
echo "Error";
} else {
echo "Success";
}
?>
All I have to do is define the two variables in the url, and my id entry will be updated under the products table, ex: www.website.com/dropship_process.php?pID=755&drop-shipping=16
Here is the jquery function that is calling dropship-process.php:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
$('#drop_shipping').change(function() {
var pid = $.urlParam('pID');
var dropshippingid = $(this).val();
$.ajax({
type: "POST",
url: "dropship_process.php",
data: '{' +
"'pID':" + pid + ','
"'drop-shipping':" dropshippingid + ',' +
'}',
success: function() {
alert("success");
});
}
});
});
I'm thinking that I defined my data wrong some how. This is the first time I've ever used anything other than serialize, so any pointer would be appreciated!
Would it not be enough to define your URl like so:
url: "dropship_process.php?pID="+ pid +"&drop-shipping="+ dropshippingid
Your ajax code is not correct. replace your ajax code by below code:
$.ajax({
type: "POST",
url: "dropship_process.php",
dataType: 'text',
data: {"pID": pid,'drop-shipping': dropshippingid},
success: function(returnData) {
alert("success");
}
});