Phonegap, AJAX - PHP Array Issue - php

I am in trouble while pass user's input value via array from HTML (Using AJAX) To php page (In fetching Array) .
Is method I use is correct ? I didn't get value in my PHP page.
First I assign user's value to variable
var first_name = $("[name='first_name']").val();
var last_name = $("[name='last_name']").val();
Then Create Its array.
var MyArray = {"firstname": first_name, "lastname": last_name};
And Here How I pass value to external server's php file
$.ajax({
type: "POST",
url: GolbalURL+"updategeneralinformation.php",
data: "userarray="+ MyArray,
dataType:'json',
success: function(response){
if(response.success) {
navigator.notification.alert(
'Ok',
// No need for Callback function
'Ok',
'Ok'
)
}
else {
navigator.notification.alert(
'Something went wrong while attempting update',
// No need for Callback function
'Atempt Fail',
'Try Again'
)
}
},
error: function(error){
navigator.notification.alert(
error,
// No need for Callback function
'Something wrong',
'Try Again'
)
}
});
return false;
Now PHP File code for retrieve Requested array from HTML page and run PHP-MySQL Update Query
$get_array = $_REQUEST['userarray'];
$query = mysql_query("UPDATE ".$db.".users SET first_name='$get_array["firstname"]', last_name='$get_array["lastname"]' ");
mysql_query($query);
if (!mysql_query($query, $con)) {
//die('Error: ' . mysql_error());
$response['success'] = false;
} else {
$response['success'] = true;
}

Use
data: MyArray,
or
data: {firstname: first_name, lastname: last_name},
instead of
data: "userarray="+ MyArray,
at server side
$get_array = $_POST;
and
$query = mysql_query("UPDATE ".$db.".users SET first_name='" . $get_array["firstname"] . "', last_name='" . $get_array["lastname"] . "'");
Note: the mysql_query is deprecated, use pdo or mysqli, and its unsecure in this form (mysql_real_escape_string() missing)

You've convert your javascript array into a string when you do this:
data: "userarray="+ MyArray,
So basically, php just gets a string.
You may want to do this in your javascript:
var MyArray = {"firstname": first_name, "lastname": last_name};
data: MyArray,
Or
data: {"firstname": first_name, "lastname": last_name},
And in your php script:
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];

var MyArray = {"firstname": first_name, "lastname": last_name};
data: MyArray,

Related

ajax jquery , query not getting called

Made something simple like a follow system using ajax jquery on my own, thats the function:
function follow(name){
jQuery.ajax({
type: "POST",
url: "../include/follow.inc.php",
data: "name",
cache: false,
});
}
and that is the button which calls that function
<button onClick="follow('.$nome.');"></button>
This is how i call the button.
$my_name = $_SESSION['account_name'];
$user = $_POST['name'];
if (isset($_POST['name'])){
$query = "INSERT INTO followed (follower, followed) VALUES ('$my_name', '$user')";
$result = $database->query($query);
}
At the end of the day, it all looks alright until the query is not getting called.
basically what it does is, gets the name (of the user you wish to follow) , it adds the name in follow(name) and proceeds adding it in a query (this is where it fails).
your codes has two problem
1 - you create your variable $name before checking that the name exists or not and in debugging mode you see the notice of php
2 - your codes is open to XSS or SQL Injection Attacks as riggsfolly said in comments
and for your problem: try this and let us known the result
php file:
if(isset($_POST['name'])){
$my_name = $_SESSION['account_name'];
$user = $_POST['name'];
$result = $database->query("INSERT INTO followed (follower, followed) VALUES ('" . $my_name . "', '" . $user . "')");
if($result){
echo('ok');
}else{
echo('error');
}
}
function:
function follow(n){
jQuery.ajax({
type: 'POST',
url: '../include/follow.inc.php',
data: { name: n },
cache: false,
success: function(response){
alert(response);
},
error: function(error){
alert('Error in AJAX request !');
}
});
}
dont forget to use a xss cleaning function for getting your data from clients in methods
$user = your_any_xss_clean_function($_POST['name']);

Ajax data function that should work but doesn't

Within my application I have an Ajax function that adds information to a database. Everything worked perfectly until I added in 2 more parameters which was location and username.
It still works with everything else but it doesn't add those last 2 into the database. The names of within the database is location and username. assignedUsername and storeLocation are set else where in the code.
Ajax:
$("#send").click(function(){
$.ajax({
type: 'POST',
contentType: "application/json",
data: orderFood(),
url: rootURL + "/orderFood",
dataType: "json",
success: function(data)
{
alert(assignedUsername);
alert("Data Added");
$.mobile.changePage("#mainMenu");
},
error: function(data)
{
alert(assignedUsername);
alert("Data NOT Added");
$.mobile.changePage("#mainMenu");
}
});
});
function orderFood()
{
alert(storeLocation + ", " + assignedUsername);
return JSON.stringify({
"food1": food1,
"food2": food2,
"food3": food3,
"food4": food4,
"food5": food5,
"food6": food6,
"food7": food7,
"food8": food8,
"food9": food9,
"location": storeLocation,
"username": assignedUsername
});
}
PHP:
$app->post('/orderFood/', 'orderFood');
function orderFood()
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
$sql = "INSERT INTO subsordered(food1, food2, food3, food4, food5, food6, food7, food8, food9, location, username) VALUES (:food1, :food2, :food3, :food4, :food5, :food6, :food7, :food8, :food9, :location, :username)";
try
{
$db = getConnection();
$stmt=$db->prepare($sql);
$stmt->bindParam("food1",$q->food1);
$stmt->bindParam("food2",$q->food2);
$stmt->bindParam("food3",$q->food3);
$stmt->bindParam("food4",$q->food4);
$stmt->bindParam("food5",$q->food5);
$stmt->bindParam("food6",$q->food6);
$stmt->bindParam("food7",$q->food7);
$stmt->bindParam("food8",$q->food8);
$stmt->bindParam("food9",$q->food9);
$stmt->bindParam("location",$q->location);
$stmt->bindParam("username",$q->username);
$stmt->execute();
$db = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
I know the PHP is correct though testing with cURL but I thought I'd include it just to get the whole picture
I am extremely stuck with this, from what I can see it SHOULD work but it just doesn't

$_POST not being set with AJAX Post value

I'm trying to send a JSON object to a .php file. What troubles me is that my POST value doesn't seem to get into PHP's $_POST array. Here is my code:
jQuery:
$("#submit").click(function(){
var obj = { //create json object to be sent
"name": $("#name").val(),
"email": $("#email").val(),
"r1": $("#r1").val(),
"r2": $("#r2").val(),
"r3": $("#r3").val(),
"intr1": $("#q1").val(),
"intr2": $("#q2").val(),
"intr3": $("#q3").val(),
"set": "set1"
};
var jsonObj = JSON.stringify(obj);
$.post(
"updateAnswers.php",
jsonObj,
function() {
//location.href = 'set2.php';
}
);
})
PHP:
if (isset($_POST["jsonObj"])) { // value is empty
$obj = json_decode($_POST['jsonObj'], true);
$name = $obj['name'];
$email = $obj['email'];
$db = mysqli_connect("localhost", "root", "", "concurs");
$sql="INSERT into players values ('$name', '$email', '0', '0', '0')";
mysqli_query($db, $sql);
}
Thanks in advance!
I dont think you need to stringify obj - try passing obj straight to the $.post function.
$.post("updateAnswers.php", obj, function() {
//location.href = 'set2.php';
});
On the PHP side, the values name, email, r1, etc.. will be directly in the $_POST array.. so you will need to access $_POST['name'] and so on.
echo "Name: ". $_POST['name']; //Show name value
var_dump($_POST); //Show all passed values
Your $sql string does not check for SQL injection. You must (at the very least) replace single quotes with two single quotes like:
$sql = "INSERT into players values ('".str_replace("'","''", $name). "', '".str_replace("'","''", $email). "', '0', '0', '0')";
You are using stringify on your obj and then you pass it to the ajax-function.
But the ajax-function expects the object as objetct not as string.
So just remove var jsonObj = JSON.stringify(obj); and just use obj
Furtermore you have to check for
name
email
r1
...
in your php-script instead of jsonObj because thats what the php actually gets from your script
This with AJAX() send:
$.ajax({
type: 'POST',
url: 'updateAnswers.php',
data: {'jsonObj': jsonObj},
success: function(msg) {
alert(msg);
}
});

Ajax Post 500 server error

I am trying to write some data to a MySQL Table however the .post call is returning with a 500 server error. Any help in the right direction would be great.
I think it's something to do with the _POST variables not sending right.
Here is the code:
JS:
function write_table(response) {
var data = {
'user_id' : response.id,
'user_email' : response.email,
'user_first' : response.first_name,
'user_last' : response.last_name
};
console.log(data);
$.ajax({
'url': './includes/php/login_facebook.php',
'data': data,
'type': 'POST',
'beforeSend': function(xhr, settings) {
console.log('ABOUT TO SEND');
},
'success': function(result, status_code, xhr) {
console.log('SUCCESS!');
},
'complete': function(xhr, text_status) {
console.log('Done.');
},
'error': function(xhr, text_status, error_thrown) {
console.log('ERROR!', text_status, error_thrown);
}
});
}
PHP:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$host = 'localhost';
$un = 'root';
$pw = 'root';
$db = 'bikelouis';
$user_id = $_POST['user_id'];
$user_email = $_POST['user_email'];
$user_first = $_POST['user_first'];
$user_last = $_POST['user_last'];
$conn = mysql_connect($host, $un, $pw) or die(mysql_error());
if ($conn) {
echo '<script> alert("connected!");</script>';
mysql_select_db($db) or die(mysql_error());
$sql = "INSERT INTO users (user_id, user_email, user_first, user_last) VALUES ($user_id, $user_email, $user_first, $user_last)";
} else {
echo 'Connection failed.';
}
?>
I am using facebook connect, that is where 'response' is coming from. That works perfectly.
jQuery Side
$.post() is simply a wrapper for $.ajax() so if you want a little more control and visibility into what's going on, I'd highly suggest using $.ajax() instead.
The data argument for $.post() should be an object of key/value pairs and not a list. That said, I'm not sure what throwing the data object into the user_info list accomplishes, and this may be the root of your problem.
Try this and let me know how it works out for you:
function write_table(response) {
var data = { // This is the format $.post() expects.
'user_email' : response.email,
'user_id' : response.id,
'user_first' : response.first_name,
'user_last' : response.last_name
};
console.log(data);
$.post('./includes/php/login_facebook.php', data, function(result, status, xhr) {
console.log(status, result);
});
}
The same request, performed through $.ajax():
function write_table(response) {
var data = {
'user_email' : response.email,
'user_id' : response.id,
'user_first' : response.first_name,
'user_last' : response.last_name
};
$.ajax({
'url': './includes/php/login_facebook.php',
'data': data,
'type': 'POST',
'beforeSend': function(xhr, settings) {
console.log('ABOUT TO SEND');
},
'success': function(result, status_code, xhr) {
console.log('SUCCESS!',
},
'complete': function(xhr, text_status) {
console.log('Done.');
},
'error': function(xhr, text_status, error_thrown) {
console.log('ERROR!', text_status, error_thrown);
}
});
}
PHP Side
First off, I'd highly recommend opening PHP with <?php rather than <?, as the later is not enabled on all set ups.
Secondly, instead of receiving an Internal Server Error, actually displaying the errors in the browser is so much cleaner. At the beginning of any PHP script you wish to display potential errors on, include the following:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
As for the 500 Internal Server Error you're receiving, it's most likely because you're missing a $ in front of $_POST on line 8.
Instead of:
$user_id = _POST['user_id'];
It should read:
$user_id = $_POST['user_id'];
Inserting
All variables should be encapsulated in ticks / apostrophes.
It's also a great idea to escape the values, to prevent SQL injection attacks:
Try this:
$sql = "
INSERT INTO users
(user_id, user_email, user_first, user_last) VALUES (
'" . mysql_real_escape_string($user_id) . "',
'" . mysql_real_escape_string($user_email) . "',
'" . mysql_real_escape_string($user_first) . "',
'" . mysql_real_escape_string($user_last) . "'
)
";

Echoed Javascript appearing in alert instead of processing

I have created a registration system that uses AJAX to process the form so that I can return false. The relevant js is the top block of code. I pass this data to join.php, which sends it to the database. I run a check in join.php to make sure that nobody with a duplicate email has already signed up. As you can see, if the email already exists, I want to insert a message using javascript. Instead of reading the script tags, it simply pastes them into my alert in plaintext...so my alert has the datastring and then actually says the code <script>...</script>. How can I get this js to process instead?
Javascript:
$(".submit").click(function() {
var dataString = {
school : $("#school").val(),
studentEmail : $("#studentEmail").val(),
studentPassword : $("#studentPassword").val(),
parentEmail : $("#parentEmail").val(),
parentPassword : $("#parentPassword").val(),
studentFirstName : $("#studentFirstName").val(),
studentLastName : $("#studentLastName").val(),
studentPhone : $("#studentPhone").val(),
parentFirstName : $("#parentFirstName").val(),
parentLastName : $("#parentLastName").val(),
parentPhone : $("#parentPhone").val()
};
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
alert ("data sent: "+ data);
}
});
return false;
}
});
join.php
if($_POST) {
$school = mysql_real_escape_string($_POST['school']);
$studentEmail = mysql_real_escape_string($_POST['studentEmail']);
$parentEmail = mysql_real_escape_string($_POST['parentEmail']);
$studentFirstName = mysql_real_escape_string($_POST['studentFirstName']);
$studentLastName = mysql_real_escape_string($_POST['studentLastName']);
$studentPhone = mysql_real_escape_string($_POST['studentPhone']);
$parentFirstName = mysql_real_escape_string($_POST['parentFirstName']);
$parentLastName = mysql_real_escape_string($_POST['parentLastName']);
$parentPhone = mysql_real_escape_string($_POST['parentPhone']);
$check = mysql_query("SELECT studentEmail FROM clients WHERE studentEmail = '{$studentEmail}';");
$num = mysql_num_rows($check);
if (($num) == 0) {
$sql = "INSERT INTO clients ".
"(`studentEmail`, `studentPassword`, `parentEmail`, `parentPassword`, ".
"`studentFirstName`, `studentLastName`, `studentPhone`, `parentFirstName`, ".
"`parentLastName`, `parentPhone`, `school`) ".
" VALUES ('$studentEmail', '$studentPassword', '$parentEmail', ".
"'$parentPassword', '$studentFirstName', '$studentLastName', ".
"'$studentPhone', '$parentFirstName', '$parentLastName', '$parentPhone', '$school')";
$result = mysql_query($sql);
if ($result) {
echo "Database query successful!";
}
else {
die("Database query failed: " . mysql_error());
}
include "emails/signUp.php";
}
else {
echo 'FAIL
<script>
$(".formErrorMessage").html("Email already exists");
</script>';
}
}
The alert shows your script block because you've got this in your success handler:
alert ("data sent: "+ data);
Data is going to be whatever text you output in your PHP. If you want to have variable behavior based on whether your request was successful or not, I'd recommend that your PHP returns JSON containing a success flag and the message. Your JavaScript callback would then look like this:
function(data) {
if (data.success) {
alert ("data sent: "+ data.message);
} else {
$(".formErrorMessage").text(data.message);
}
}
Your PHP should then change your content-type to JSON:
header('Content-Type: application/json');
... and your echos would change to something like this:
echo '{"success": false, "message": "Email already exists."}';
Your server call shouldn't be returning raw HTML. Should return JSON that contains all the status information the server needs to handle things. i.e. in the usual case:
{'success': true}
or
{'success': false, 'emailAlreadyExists': true, 'msg': 'Email Already Exists'}
of
{'success': false, 'msg': 'Database query failed: blahblahMySqlError'}
Then your client JS should handle it...
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
if(data.success) {
alert ("success!");
}
else{
alert("error: " + data.msg);
if(data.emailAlreadyExists){
$(".formErrorMessage").html("Email already exists");
}
}
}
});
from php, you have give formatted status responses
on success:
echo '{"status":"success", message:"Database query successful!"}';
if account already exists:
echo '{"status":"failed", message:"Email already exists"}';
So you will be able to identify this in JavaScript callback function
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(data) {
if(status.error == "failed"){
$(".formErrorMessage").html(data.message);
}
}
});
This is the best way to do it. Or if you just want to execute a string received from php, you can use eval
success: function(data) {
eval(data);
}
In that case there is no need of script tags in response, only the Javascript statement that has to be executed.

Categories