I'm a student who is doing an app with jQueryMobile and gonna be compiled with Phonegap. I want to posting data to a server using jQuery but I have problems loading my .php file in the server.
I have the last version of jQuery.
Here I put my script for post the data from a form:
$(document).ready(function() {
var postData = $('#registerForm').serialize();
$('#registerForm').submit(function() {
$.ajax({
type: 'post',
data: postData,
url: 'http://www.smartweb.cat/app/Habana/user_register.php',
success: function(data) {
alert('Usuari registrat correctament.');
},
error: function() {
alert('Hi ha algun problema amb el registre.');
}
});
return false;
});
});
Thanks a lot and sorry for my english wrinting.
Your post data are empty. You retrieve them directly when the DOM is loaded and not when the form is submit. You should move your var postData.
$(document).ready(function() {
//var postData = $('#registerForm').serialize();
$('#registerForm').submit(function() {
var postData = $('#registerForm').serialize(); // here
$.ajax({
//...
});
});
});
First of all I want to say that you should use prepared statements.
Althought you sanitize user input(GOOD) its still recommended using prepared statements.
Not only does it help with readability its also more secure.
Make sure your form sends following postdata:
{name:"YourName", surname:"Yoursurname",date:"<dateobject>",email:"sample#mail.com",user:"username",password:"password}
== THIS LOOKS OK ==
$name = mysql_real_escape_string($_POST["name"]);
$surname = mysql_real_escape_string($_POST["surname"]);
$date = $_POST["date"];
$email = mysql_real_escape_string($_POST["email"]);
$user = mysql_real_escape_string($_POST["user"]);
$pass = mysql_real_escape_string($_POST["pass"]);
enter code here
If the conditions above are the same the server should receive all your data. I do see a problem in your query that may be the problem.
What you are doing is inserting everything as string in the database. You have to make sure when you try to execute a query given values for a table that the given values correspond with the database.
$result = mysql_query("INSERT INTO $tableName (name, surname, date, email, user, pass) VALUES
('$name', '$surname', '$date', '$email', '$user', '$pass')"); //insert
Make sure everything is correct for example your date column in the database is it a string or a mysql date TYPE. Try to lose the '.
$result = mysql_query("INSERT INTO $tableName (name, surname, date, email, user, pass) VALUES
($name, $surname, $date, $email, $user, $pass)");
Related
I am trying to make my submit button send data to my PHP file without reloading, however, when I use this call it doesn't send any data and neither is saved in my database.
$('#formSubmitData').on('submit', function(event) {
event.preventDefault();
var msg = $('#textareaSubmitData').val();
$.ajax({
url: 'searchData.php', //this is ALSO how the text is being send to the database to be retrieved later on.
type: 'POST',
data: {message:msg},
success: function(data) {
console.log(data);
data = msg;
alert(data);
}
});
});
The alert shows the correct value, but in my database, the rows remain empty.
How the PHP code looks like:.
if (isset($_POST['submit']) && $_SERVER['REQUEST_METHOD'] === "POST") {
include_once 'dbConn.php';
$name = $_SESSION['userName'];
$msg = $_POST['textareaSubmitData'];
$stmt = $conn->prepare("INSERT INTO messages (name, message) VALUES (?, ?)");
$stmt->bind_param('ss', $name, $msg);
$name = $_SESSION['userName'];
$msg = $_POST['textareaSubmitData'];
$stmt->execute();
$conn->close();
$stmt->close();
} else {
header('Location: index.php?send=failure');
exit();
}
}
Think there are 2 issues, the first is that you need to make sure the data to send is an object and not just a value...
data: { textareaSubmitData: msg },
The second is that when you try and process the data, your first line is...
if (isset($_POST['submit']) && $_SERVER['REQUEST_METHOD'] === "POST") {
So this is looking for some POST data in 'submit' - which you don't send. So as you (now) just send 'textareaSubmitData' - check if that is set...
if (isset($_POST['textareaSubmitData']) && $_SERVER['REQUEST_METHOD'] === "POST") {
You are sending the value of submit button in data. You need to send the form data to your server.
$('#formSubmitData').on('submit', function(event) {
event.preventDefault();
var data = new FormData(this);
$.ajax({
url: 'searchData.php', //this is ALSO how the text is being send to the database to be retrieved later on.
type: 'POST',
data: data,
success: function(data) {
data = msg;
alert(data);
}
});
});
Also – definitively, "look at(!)" what is being sent, using the debugging features of your browser. When the AJAX call goes off, you can see an HTML POST being done – so, you can see exactly what the URL is, and exactly what data is (or, isn't) being supplied.
On the host side, you can also do things like print_r($_POST) so that you can once again see what PHP has received.
My experience is that, once you can see what's happening, debugging is very quick and easy. Whereas, guessing leads nowhere.
So my database does not add this data into the database when the button is pressed.
I have created a form, and all the id's are perfect and the email is a foreign key so it is taken from sessionStorage of the logged in user. I need help with why it is not working, I have no idea. The page alerts me "the order was successful" when I press submit but the data does not get stored in the database.
My SQL statement also works definitely, I tried it in my database.
Here are my php and js:
<?php
header("Content-Type: application/json; charset=UTF-8");
$servername = "localhost";
$username = "root";
$password = "leaf123";
$dbname = "laxmi";
// Create Connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
die("Connection failed:" . mysqli_connect_error());
}
else
{
// Obtain the contents
$request = file_get_contents('php://input');
// decode json so PHP can use it
$jsonRequest = json_decode($request);
// Query
$sql = "INSERT INTO checkout(email, ccName, ccNumber, month, year, cvc) VALUES ('$jsonRequest->email', '$jsonRequest->ccName', '$jsonRequest->ccNumber', '$jsonRequest->month', '$jsonRequest->year', '$jsonRequest->cvc')"
}
// Execute Query
$results = mysqli_query($conn, $sql);
echo json_encode("success");
mysqli_close($conn);
my javascript
$(document).ready(function () {
//When the submit button on the checkout form is pressed.
$("#SubmitOrder").on("click", function () {
//store each individual entry into a separate variable.
var email = sessionStorage.getItem("loggedInUser");
var ccname = document.getElementById("ccName").value;
var ccnum = document.getElementById("ccNumber").value;
var month = document.getElementById("month").value;
var year = document.getElementById("year").value;
var cvc = document.getElementById("cvc").value;
//create an array with the details in.
var checkout = {
email: email,
ccname: ccname,
ccnum: ccnum,
month: month,
cvc: cvc,
}
//direct the user to the login page and alert them that their registration was successful.
alert("Your order was successful.")
window.location.href = "../index.html"
//posts the JSON object to the php file so it can fill the database, and converts the checkout array into JSON so it can be read.
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout))
})
})
First off, you're displaying the success message before even trying to send the post request to your PHP file. So your first job is to re-order things
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout));
alert("Your order was successful.");
window.location.href = "../index.html";
Secondly, you're currently not checking for a response from the server as to whether the request was successful or not. I've modified the example from the jQuery docs https://api.jquery.com/jquery.post/
var jqxhr = $.post("../php/checkoutOrder.php", JSON.stringify(checkout))
.done(function() {
alert("Your order was successful.");
window.location.href = "../index.html";
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
Once you're done with that, you'll want to look into returning a response from PHP to say whether the query worked etc, but the above is at least enough to get you something that works for now :)
i'm trying to understand this error but i dont how to solve it
this is my JS code:
$.ajax({
url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php',
type: "POST",
data: ({Pname: Pname, Uname: Uname, email: email, Ename: Ename, Sigla: Sigla}),
complete:function(data)
{
resposta = data;
console.log(resposta);
}
});
this is my php code:
$serverName = $server;
$uid = $uid;
$pwd = $pass;
$connectionInfo = array( "UID" => $uid, "PWD" => $pwd,"Database"=>"Portal");
//$connectionInfo = array("Database"=>"Portal");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$Pname = $_POST["Pname"];
$Uname = $_POST["Uname"];
$email = $_POST["email"];
$Ename = $_POST["Ename"];
$Sigla = $_POST["Sigla"];
if( $conn )
{
$sqlCliente = "INSERT INTO Portal.dbo.Empresa VALUES ($Ename, $Sigla)";
if (mysqli_query($conn, $sqlCliente)) {
echo "New record created successfully";
} else {
echo "Error: " . $sqlCliente . "<br>" . mysqli_error($conn);
}
}
when i do console.log of data, give me this:
what is wrong with my code?
Try to change into $sqlCliente = "INSERT INTO Portal.dbo.Empresa VALUES ('$Ename', '$Sigla')";
I think problem with your sql insert statement.
$sqlCliente = "INSERT INTO Portal.dbo.Empresa(Ename,Sigla) VALUES ($Ename, $Sigla)";
OR
$sqlCliente = "INSERT INTO Portal.dbo.Empresa VALUES ($Ename, $Sigla,..... Add all parameters to here)";
url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php',
This line is incorrect.
PHP files need a server to get executed. By the looks of your path, it looks like you have hosted in IIS. IIS doesn't suppport PHP by default - so assuming you have installed PHP and configured properly, read below.
You don't post to the physical path of the PHP file, rather URL of the PHP.
Therefore, it should look something similar to:
url: localhost/VisionwareHelp/php/CriaUserEempresa.php',
Until you fix the URL to the correct one, none of your posting code will work correctly.
If you have not installed PHP on IIS, then you need to download and install a PHP-enabled server like 'WampServer' and host your PHP in that.
Also, read below articles - it will help to improve your knowledge.
Installing and Testing Wampserver
Beginner’s Guide to Ajax Development with PHP
In Ajax, The correct syntax of sending multiple data is: http://api.jquery.com/jQuery.ajax/
So, Replace
data: ({Pname: Pname, Uname: Uname, email: email, Ename: Ename, Sigla: Sigla}),
with
data: {'Pname':Pname, 'Uname':'Uname', 'email':email, 'Ename':Ename, 'Sigla':Sigla },
And this line url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php', is also incorrect.
replace
url: 'C:\\inetpub\\wwwroot\\VisionwareHelp\\Php/CriaUserEempresa.php',
with
url: 'Php/CriaUserEempresa.php',
Hope it will help you..
I use the following Ajax request to pass data:
var query = {
"username" : $('#username').val(),
"email" : $('#email').val(),
}
$.ajax({
type : "POST",
url : "system/process_registration.php",
data : query,
cache : false,
success : function(html) {
// output
}
});
My php-file (process-registration.php), in which the query is being processed, looks like this:
require_once 'db.php';
$username = $_REQUEST['username'];
$email = $_REQUEST['email'];
// Include new user into database
$db -> query("INSERT INTO users (username, email) VALUES ('$username', '$email');");
//Identify user id of this new user (maybe there is a faster way???)
$results = $db -> query("SELECT * FROM users WHERE username='$username'");
while ($result = $results->fetch_assoc()) {
$user_id = $result['id'];
}
// My output?
Now comes my question: How can I tell the Ajax command / the PHP script to return as a result two elements:
a HTML message: <p>You have registered successfully</p>
the $user_id that I have identified via the loop above
I need the user_id, because in the frontend I want to include it as a GET parameter into the href of the button "Go to admin area" that will appear AFTER the Ajax request will be completed.
Try this:
$response = array('user_id'=>$user_id,'message'=>'Success - user created');
echo json_encode($response);
This will give return a json object that you can access in JS.
$.ajax({
type : "POST",
url : "system/process_registration.php",
data : query,
cache : false,
dataType: 'json',
success : function(html) {
// output - do something with the response
console.log(html.user_id);
console.log(html.message);
}
});
I think it would be better to change the array in string by putting a special character(I use % or #)between different values. In your case just echo 'You have registered successfully%'.$user_id ;. Now explode the response string and use both.
This has been an ongoing issue for me. You all have already helped so much. However, I am stuck again. I cannot get my .ajax() to run. For some reason the .click() won't even work without if(field != text) above my .ajax() call, but I digress.
My question is: Why is my ajax() not functioning properly and if this gets fixed will the table is have displayed update after the query is sent to the database without a page refresh?
Here is my script:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_td").click(function()
{
$(this).children(".text").hide();
$(this).children(".editbox").show();
}).children('.editbox').change(function()
{
var id=$(this).closest('tr').attr('id');
var field=$(this).data('field');
var text=$(this).val();
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
alert("made variables");
if(field != text)
{
alert("in if");
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
</script>
Here is my table_edit_ajax.php
<?php
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo 'in table_edit';
$id = mysqli_escape_String($_POST['id']);
$table = "owners";
$field = mysqli_escape_String($_POST['field']);
$text = mysqli_escape_String($_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($query);
//close connection
mysqli_close($con);
?>
The first argument to all mysqli functions is the connection, statement, or result object.
$id = mysqli_escape_String($con, $_POST['id']);
$table = "owners";
$field = $_POST['field'];
$text = mysqli_escape_String($con, $_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($con, $query);
$field shouldn't be escaped, since it's not a string value. Therefore, you need to validate it carefully, to prevent SQL injection. Perhaps instead of allowing the client to submit the field name to update, have them submit an integer, which you look up in an array to convert to a field name.
In your AJAX call, you may have a problem due to not encoding your parameters properly. Change the dataString assignment to:
var dataString = { id: id, field: field, text: text };
Then jQuery will encode it for you.
you are sending a data string
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
and retrieving it through $_POST.
first check what is in $_POST
and use $_GET instead of $_POST
and change post in ajax to get
and what is first and last in success callback??