.ajaxForm passing data to php - javascript

I'm struggling to pass data using ajaxForm to my PHP file so I can insert into a MySQL database.
Below is the JavaScript function which currently displays a progress bar during form submitting, the problem is the 'post' of name, phone and email don't work but the attachment upload does.
$(function() {
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var email = document.getElementById("email").value;
var percent = $('.percent');
var bar = $('.bar');
$('form').ajaxForm({
dataType:  'json',
data : {
name:name,
phone:phone,
email:email
},
beforeSend: function() {
document.getElementById("bar").style.backgroundColor="rgb(51,166,212)";
bar.width('0%');
percent.html('0%');
},
uploadProgress: function(event, position, total, percentComplete) {
var pVel = percentComplete + '%';
bar.width(pVel);
percent.html(pVel);
},
complete: function(data) {
document.getElementById("bar").style.backgroundColor="rgb(185,221,111)";
percent.html("Done!");
setTimeout(function(){
modal.style.display = 'none';
location.reload();
}, 2000);
}
});
});
Here is the code from the PHP file the values are to be passed to.
<?php
include("sql_connection.php");
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$sql = "INSERT INTO helpdesk (Name, Phone, Email) VALUES ($name, $phone, $email)";
mysqli_query( $conn, $sql);
$dir = 'uploads/';
$count = 0;
if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_FILES['files']))
{
foreach ( $_FILES['files']['name'] as $i => $name )
{
if ( !is_uploaded_file($_FILES['files']['tmp_name'][$i]) )
continue;
if( move_uploaded_file($_FILES["files"]["tmp_name"][$i], $dir . $name) )
$count++;
}
}
echo json_encode(array('count' => $count));
?>
Any advice?
Thanks

Change your SQL query to:
$sql = "INSERT INTO helpdesk (Name, Phone, Email) VALUES ('".$name."', '".$phone."', '".$email."')";
otherwise you need to change your include at the top where you start your database connection.
As I read in your comment the problem is that possibly the inputs doesn't contain any value. When are you launching the Ajax request? After a submit or on page load?
Maybe you can add the code where he should take his information from?

Missing type param in $.ajax
$('form').ajaxForm({
type: 'POST',
dataType: 'json',
data : {'name':name,'phone':phone,'email':email},
......................................

All, thanks for your help, the SQL query was in fact wrong but I also needed to use a function for each variable to return its current state before posting.
Thanks
$('form').ajaxForm({
type: 'POST',
dataType:  'json',
data : {
name:function () {
return name = document.getElementById("name").value;
},
phone:function () {
return phone = document.getElementById("phone").value;
},
email:function () {
return email = document.getElementById("email").value;
}
},

Related

ajax works, but it doesn't insert into my sql query (js/php)

I don't understand if ajax work this way, but data doesn't add into my mysql database. I checked network tab in my chrome browser and found data has been forwarded.
I had tried like this way
script.js:
$(".btn_ranking").click(function (e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { "name": name, "time": time }
})
});
file.php:
<?php
require_once "connect.php";
$polaczenie = #new mysqli($host, $db_user, $db_password, $db_name);
$name = $_POST['name'];
$time = $_POST['time'];
if ($polaczenie->connect_errno != 0) {
echo "Error: " . $polaczenie->connect_errno;
} else {
if ($rezultat = #$polaczenie->query("INSERT INTO ranking (id, name, time) VALUES (NULL, $name, $time)")) {
echo "ok";
}
}
?>
First,you had better use PrepareStatement to pass parameter instead of writing them directly into your sql.
For your current code,try change to below code
if ($rezultat = #$polaczenie->query("INSERT INTO ranking (id, name, time) VALUES (NULL, '".$name."', '".$time."')")) {
echo "ok";
}
You should try like as below
$(".btn_ranking").click(function (e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time } //Remove double quote
})
});

PHP post request unidentified index error

I'm trying to write a page to make a POST request to a php script and I feel like I've done it right, it's worked everywhere else so it seems but I keep getting a "unidentified error" and it won't work, how can I get this to work?
Javascript:
$(document).ready(function() {
$("#x").click(function() {
var email = $("email").val();
var pass = $("password").val();
var confirmPass = $("confirmPassword").val();
var name = $("name").val();
var question = $("question").val();
var answer = $("answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "*********";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$email = $_POST["email"];
$pass = $_POST["pass"];
$name = $_POST["name"];
$question = $_POST["question"];
$answer = $_POST["answer"];
$sql = "INSERT INTO accounts (accountEmail, accountPassword, accountName, accountQuestion, accountRecover) VALUES ('$email', '$pass', '$name', '$question', '$answer')";
$conn->close();
if(mysql_affected_rows() > 0) {
$response = "Account added successfully!";
}
else {
$response = "Couldn't add account!";
}
$pre = array("Response" => $response);
echo json_encode($pre);
?>
You need to properly use jquery.
For example
var email = $("email").val(); //IS WRONG
Should be (if you have input id="email")
var email = $("#email").val();
If you have only name you can use
var email = $("[name='email']").val();
A bit offtopic:
If you are using form ajax submit consider jquery method serialize https://api.jquery.com/serialize/ for getting all form values (or some jquery ajaxform plugin).
And please! don't make insecure mysql statements. For gods sake use prepared statements.
If you need very basic stuff just use prepared statements or consider https://phpdelusions.net/pdo/pdo_wrapper
Also a small tip: before echo json make json header
<?php
header('Content-type:application/json;charset=utf-8');
I think you are mistaken with your jquery data, they should have identifier like id denoted by '#' and classes denoted by '.', do it this is you have id="name of the field" among the input parameters:
$(document).ready(function() {
$("#x").click(function() {
var email = $("#email").val();
var pass = $("#password").val();
var confirmPass = $("#confirmPassword").val();
var name = $("#name").val();
var question = $("#question").val();
var answer = $("#answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
OR like this is you have class="name of the field" among the input parameters:
$(document).ready(function() {
$("#x").click(function() {
var email = $(".email").val();
var pass = $(".password").val();
var confirmPass = $(".confirmPassword").val();
var name = $(".name").val();
var question = $(".question").val();
var answer = $(".answer").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
OR if you want to use the name directly follow this:
$(document).ready(function() {
$("#x").click(function() {
var email = $("input[name='email']").val();
var pass = $("input[name='pasword']").val();
var confirmPass = $("input[name='confirmPassword']").val();
var name = $("input[name='name']").val();
var question = $("input[name='question']").val();
var answer = $("input[name='answer']").val();
if(pass != confirmPass) {
alert("Passwords do not match!");
return;
}
var stuff = {email: email, pass: pass, name: name, question: question, answer: answer};
$.ajax({method: "POST", url: "addAccount.php", data: stuff, success: function(result) {
alert(result);
window.location.href = "../Dashboard";
}});
});
});
I hope this helps you
There are lots of reasons your code is not working. #AucT and #gentle have addressed your Javascript side issues so I'll focus on PHP. Your query code is:
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "...";
$conn->close();
Notice that:
you never execute you query. $sql is just a string held in memory.
you're mixing mysqli function with mysql_ function (mysql_affected_rows); that won't work
You're inserting POST data directly into your queries, so you are very vulnerable to SQL injection
At the end, you echo JSON, but you haven't told the browser to expect this format
Do this instead:
$conn = new mysqli(...);
//SQL with ? in place of values is safe against SQL injection attacks
$sql = "INSERT INTO accounts (accountEmail, accountPassword,
accountName, accountQuestion, accountRecover) VALUES (?, ?, ?, ?, ?)";
$error = null;
//prepare query and bind params. save any error
$stmt = $conn->prepare($sql);
$stmt->bind_param('sssss',$email,$pass,$name,$question,$answer)
or $error = $stmt->error;
//run query. save any error
if(!$error) $stmt->execute() or $error = $stmt->error;
//error details are in $error
if($error) $response = "Error creating new account";
else $response = "Successfully created new account";
//set content-type header to tell the browser to expect JSON
header('Content-type: application/json');
$pre = ['Response' => $response];
echo json_encode($pre);

Returning variables PHP, MySQL and JS

I'm developing an PHP-MySQL-JS platorm. I'm doing now the profile page and there the user can update his info.
My code is:
HTML
<form>
//rest of the form.
//The submit button.
<button id="profile_submit" style="margin-left: 500px; margin-top: 10px;" class="logout" type="submit"><b>Guardar cambios</b></button>
</form>
JavaScript
$( document ).ready(function() {
$('#profile_submit').click(function(){
var name1 = $('#name1').val();
var name2 = $('#name2').val();
var user = $('#user').val();
var email = $('#email').val();
if(name1 != '' && name2 != '' && user != '' && email != '' ){
$.ajax({
url: '../controller/updateuser.php',
method: 'POST',
data: {name1: name1, name2: name2, user: user, email: email},
success: function(msg){
if (msg == '1'){
//Error
alert("Another user is using this email already");
} else {
//Se registro
alert("Updated");
setTimeout(function(){location.href= "workspace.php"} , 1000);
}
}
});
}
});
});
PHP - general
public function update_user($name1, $name2, $user, $email){
$res = $this->conexion->query("select USR_EMAIL from usr_usuario where USR_EMAIL = '".$email."' and USR_DELETE = '0' and USR_ID <> '".$_COOKIE['USR_ID']."' ");
if(mysqli_num_rows($res)>0)
{
//Email used
echo '1';
}else{
//Update user
$this->conexion->query("UPDATE usr_usuario SET USR_USERNAME = '".$user."', USR_NAME = '".$name1."', USR_NAME2 = '".$name2."', USR_EMAIL = '".$email."' WHERE USR_ID = '".$_COOKIE['USR_ID']."' ");
}
}
PHP - update.php
<?php
require("../modelo/conexion.php");
$name1 = $_POST['name1'];
$name2 = $_POST['name2'];
$user = $_POST['user'];
$email = $_POST['email'];
$object = new conexion();
$object -> actualizar_usuario($name1, $name2, $user, $email);
$object -> cerrar();
?>
Well, when the user clicks on the button with id="profile_submit", the JS read the info in the inputs and sends it to update.php and it calls the update_user in general php file.
When the user insert an email used already it works perfectly, but, when all is okay, the sql UPDATE works but the rest of the code(PHP and JS) don't sends nothing to the user.
I don't know why this happens...
Help please.

Communication between JavaScript, PHP and MySQL

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'){

Post statement not returning a value

I have a javascript fucntion below
function loginsubmit() {
var url = "../php/loginsubmit.php";
var data = "";
ajaxRequest(url, "POST",data , true, insertNewBody);
}
Which then creates my ajax request to post to my php code which is
<?php
session_start();
require_once ("db.php");
$username = $_POST['username'];
$password = $_POST['password' ];
echo $username;
$query = "select * from logindetails where username='$username' and password='$password'";
$result = mysql_query($query);
if(mysql_num_rows($result) == 1) {
$row = mysql_fetch_assoc($result);
$_SESSION['logged_in'] = TRUE;
} else {
$_SESSION['logged_in'] = FALSE;
}
mysql_close();
?>
These two pieces of code below are returning a null value and i can't see why?
$username = $_POST['username'];
$password = $_POST['password'];
It's because you're actually never setting the post values username and password in your javascript.
Put data in your data variable:
function loginsubmit() {
var url = "../php/loginsubmit.php";
var data = {username: 'yourusername', password: 'yourpassword'};
ajaxRequest(url, "POST",data , true, insertNewBody);
}
As clarified by others already, you are not sending data.. here is how you should:
function loginsubmit() {
var url = "../php/loginsubmit.php";
var username = document.myLoginForm.username.value;
var password = document.myLoginForm.password.value;
ajaxRequest(url, "POST", {username: username, password: password}, true, insertNewBody);
}
replace "myLoginForm" with the actual name of your form. Also there are other ways too to retrive values from input fields such as using element IDs of those feilds.
An ajax suggestion based on what Ruben is saying, you need to pass the username and password up to PHP in your login call.
$.ajax({
url : "../php/loginsubmit.php",
type: "POST",
data : {username:"theUsernameString",password:"thePasswordString"},
success: function(data, textStatus, jqXHR)
{
//data - contains the response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
//handle the error
}
});

Categories

Resources