I tried to insert data into database by using ajax and php. However, I have no idea why it is not working. I have tested the html file, all the itemName, category, price are valid and the php file return me "success" just the data inserted to database is empty.
$(document).ready(function(){
var url = "http://domain/addProduct.php?callback=?";
$("#addProduct").click(function() {
var itemName = $("#itemName").val();
var category = $("#select_category").val();
var price = $("#price").val();
var dataString = "$itemName=" + itemName + "&category=" + category + "&price=" + price + "&addProduct=";
if ($.trim(itemName).length > 0 & $.trim(category).length > 0 & $.trim(price).length > 0) {
$.ajax({
type: "POST",
url: url,
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {
$("#addProduct").val('Connecting...');
},
success: function(data) {
console.log(data);
if (data == "success") {
alert("Successfully add item");
} else if(data="failed") {
alert("Something Went wrong");
}
}
});
}
return false;
});
});
<?php
header("Access-Control-Allow-Origin: *");
require("config.inc.php");
$name = mysql_real_escape_string(htmlspecialchars(trim($_POST['itemName'])));
$category = mysql_real_escape_string(htmlspecialchars(trim($_POST['category'])));
$price = mysql_real_escape_string(htmlspecialchars(trim($_POST['price'])));
$date = date("d-m-y h:i:s");
$statement = $pdo->prepare("INSERT INTO product(name, category, price, date) VALUES(:name, :category, :price, :date)");
$statement->execute(array(
"name" => $name,
"category" => $category,
"price" => $price,
"date"=>$date
));
if($statement)
{
echo "success";
}
else
{
echo "failed";
}
?>
replace this code:
dataString="$itemName="+itemName+"&category="+category+"&price="+price+"&addProduct=";
to:
dataString="itemName="+itemName+"&category="+category+"&price="+price+"&addProduct=";
and replace this code too:
if($.trim(itemName).length>0 & $.trim(category).length>0 & $.trim(price).length>0)
to:
if($.trim(itemName).length>0 && $.trim(category).length>0 && $.trim(price).length>0)
Because & is a Bitwise Operator But && is Logical Operator, So in this condition we always use logical operator.
You can't use date as your table column. date is a predefined/reserved keyword. Change the name of your date column into your database and modify your sql query and try again.
Related
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'){
I am trying to get the results from the database whether username is available or not . But it is not giving any results i am not getting ajax response this is the html code
<form id="user_form">
<input placeholder="username here" type="text" name="ajax-data" id="ajax-data">
<input type="submit" name="btnSubmit" id="btnSubmit" Value="Submit">
</form>
<span class="php_responce_here"></span>
This is the ajax code which i have used
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: {ajax-data: textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result);
}
});
});
});
</script>
final code of php where i have used the validation and the query to find whether the username is available in the database or not the problem is that it is not giving any of the result
<?php
error_reporting(0);
require "config.php";// configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if($user_name)
{
$usernamecheck= mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check= mysql_fetch_row($usernamecheck);
if($check[0]==0)
{
if($user_name!=""){
if(strlen($user_name)>25){
echo "You have reached the maximum limit";
}
else{
echo "User name is valid";
}
}
else
{
echo "username is empty";
}
}
else{
echo "Username Already Taken";
}
}
?>
should be submit event not click:
$("form#user_form").submit(function(e) {
e.preventDefault();
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
data: { "ajax-data": textboxvalue },
success: function(result) {
$(".php_responce_here").html(result);
}
});
});
and as #Cyril BOGNOU pointed out;
data: { "ajax-data": textboxvalue }
You should too add data type to be returned with the parameter if you want to return JSON for example
dataType: 'JSON',
and Yes I think you should better write
data: { "ajax-data": textboxvalue }
So the update should be
$(document).ready(function()
{
$("form#user_form").click(function()
{
var textboxvalue = $('input[name=ajax-data]').val();
$.ajax(
{
type: "POST",
url: 'second.php',
dataType: 'JSON',
data: {"ajax-data": textboxvalue},
success: function(result)
{
$(".php_responce_here").html(result.message);
}
});
});
});
and return json string from PHP script
<?php
error_reporting(0);
require "config.php"; // configuration file holds the database info
$user_name = $_POST['ajax-data']; // textbox in the html
if ($user_name) {
$usernamecheck = mysql_query("SELECT count(*) FROM users WHERE username='$user_name'");
$check = mysql_fetch_row($usernamecheck);
if ($check[0] == 0) {
if ($user_name != "") {
if (strlen($user_name) > 25) {
$message = "You have reached the maximum limit";
} else {
$message = "User name is valid";
}
} else {
$message = "username is empty";
}
} else {
$message = "Username Already Taken";
}
echo json_encode(["message" => $message]);
}
?>
NOTE : mysql is deprecated. you should use mysqli or PDO
There are some mistakes in your code. check the below code. it should work.
<script>
$(document).ready(function () {
$("form").submit(function (event) {
var textboxvalue = $("#ajax-data").val();
$.ajax({
data: {ajaxdata: textboxvalue},
type: "POST",
url: 'second.php',
success: function (result)
{
$(".php_responce_here").html(result);
}
});
return false;
});
});
</script>
You can not create variable ajax-data with -.
PHP
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$user_name'");
$check = mysql_num_rows($usernamecheck);
you should use mysql_num_rows instead of mysql_fetch_row. it will auto calculate the rows.
Check working example
Empty page? Nothing prints out?
<?php
error_reporting(-1);
ini_set('display_errors', 1);
require "config.php";// configuration file holds the database info
if(isset($username = $_POST['ajax-data'])){
if($l = strlen($username) <= 25 && $l > 2){
$sql = "SELECT * FROM users WHERE username='$username'"; // wide open for SQL injections. use mysqli or PDO instead.
if($rsl = mysql_query($sql) != false){ // ALWAYS verify if your query's ran successfully.
if(mysql_num_rows($rsl) != 0){
echo 'Username already exists';
} else {
echo 'Username is available';
}
} else {
echo 'Query failed: ' . mysql_error();
}
} else {
echo $l > 25 ? 'Reached limit' : 'Needs to be longer';
}
} else {
echo "post['ajax-data'] not set<\br>";
print_r($_POST);
}
?>
Then there is your Javascript code that I have questions on. Yet you have a submit button but you want to check if its valid upon change?
$(document).ready(function(){
$("#user_form").submit(function(event){
event.preventDefault();
$.ajax({
url: "second.php",
type: "post",
data: $(this).serialize(),
success: function(result){
$(".php_responce_here").html(result);
}
});
});
});
I have an UI in which the user can add objects (stored as JSON in my database). So, when the user is clicking on a button, it calls the ajax wich calls my php to get the desired JSON code.
The problem is that my ajax returns me "success" but with no JSON code. I don't know where the problem is located.
Here's my JS/AJAX:
var object, objectJson;
var objectName = $(this).attr("attr-lib");
var objectId = $(this).attr("attr-id");
$.ajax({
url: 'scriptObject.php',
type: 'POST',
data: {objectId: objectId},
dataType: 'json',
success: function(response) {
console.log("success");
console.log(response);
}
});
Here's my scriptObject.php:
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result = mysql_query($query);
if($result)
{
if(mysql_num_rows($result) > 0)
{
$objJSON = mysql_fetch_array($result);
$res = array("status"=>"success", "objectJson" => $objJSON['objectJson']);
}
else
{
$res = array("status"=>"error", "message" => "No records found.");
}
}
else
$res = array("status"=>"error", "message" => "Problem in fetching data.");
echo json_encode($res);
[EDIT]
It answers me:
{"status":"error","message":"Problem in fetching data."}
Try following
<script type="text/javascript">
var object, objectJson;
var objectName = $(this).attr("attr-lib");
var objectId = $(this).attr("attr-id");
$.ajax({
url: 'scriptObject.php',
type: 'POST',
dataType : 'json',
data: { objectId: objectId },
success: function(response) {
var json = $.parseJSON(response);
if(json.status == 'error')
console.log(json.message);
else if(json.status == 'success')
console.log(json.objectJson);
}
});
</script>
and in scriptObject.php
<?php
// your database connection goes here
include 'config.php';
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result = mysql_query($query);
if($result)
{
if(mysql_num_rows($result) > 0)
{
$objJSON = mysql_fetch_array($result);
$res = array("status"=>"success", "objectJson" => $objJSON['objectJson']);
}
else
{
$res = array("status"=>"error", "message" => "No records found.");
}
}
else
$res = array("status"=>"error", "message" => "Problem in fetching data.".mysql_error());
echo json_encode($res);
?>
scriptObject.php
if(isset($_POST['objectId']))
{
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result=mysql_query($query);
echo json_encode($result);
die;
}
you are execution the php code inside a function.
how does the compiler or the interpreter know to execute a function inside your php file.
Add dataType to your ajax options
$.ajax({
url: 'scriptObject.php',
type: 'POST',
data: objectId,
dataType : 'json',
success: function(response) {
console.log("success");
console.log(response);
}
});
then your php code
function getObjectJson() {
$objectId = $_POST["objectId"];
$query = "SELECT objectJson FROM object WHERE objectId = ' $objectId '";
$result=mysql_query($query);
echo json_encode($result);
}
I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);
I do not understand because when the data were entered into the login are correct and I make this comparison response.success == "success" nothing happens, I check with firebug and the result is this:
Response
[{"ncontrol":"09680040","nombre":"Edgardo","apellidop":"Ramirez","apellidom":"Leon","tUser":"Admin","status":"success"}]
jQuery.ajax script to send data
// jQuery.ajax script to send json data to php script
var action = $("#formLogin").attr('action');
var login_data = {
ncontrol: $("#ncontrolLogin").val(),
password: $("#passwdLogin").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: login_data,
dataType: "json",
success: function(response)
{
**if(response.status == "success")** {
$("#status_msg").html("(+) Correct Login");
}
else {
$("#status_msg").html("(X) Error Login!");
}
}
});
return false;
And is PHP Script for processing variables from jQuery.ajax
$ncontrolForm = $_REQUEST['ncontrol'];
$passForm = $_REQUEST['password'];
$jsonResult = array();
$query = "SELECT * FROM users WHERE ncontrol = '$ncontrolForm' AND cve_user = SHA('$passForm')";
$result = mysqli_query($con, $query) or die (mysqli_error());
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if( $num_row >= 1 ) {
$_SESSION['n_control'] = $row['ncontrol'];
$_SESSION['t_user'] = $row['tUser'];
$jsonResult[] = array (
'ncontrol' => $row['ncontrol'],
'nombre' => $row['nombre'],
'apellidop' => $row['apellidop'],
'apellidom' => $row['apellidom'],
'tUser' => $row['tUser'],
'status' => 'success',
);
header('Content-Type: application/json');
echo json_encode($jsonResult);
}
You have an array, so do it this way:
if(response[0].status == "success") {
The object is the first item in the array.
EDIT:
Looking more closely at your PHP, it looks like you might be intending to loop through several rows in your query response and add them to your $jsonResult. Am I seeing it right?