Ajax not submitting $_Post - javascript

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);

Related

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

Using two Ajax calls to post then retrieve data

I am currently trying to firstly post the name of the user that I am trying to retrieve from the database to my php code using ajax. Then in the success part of the call I am trying to make a function to retrieve data from a database which matches the name of the user the I previously sent to the page, however no data is coming back to the javascript code.
Here is the function with my ajax calls.
function checkPatientAnswers(event) {
window.open("../src/clinicreview.php", "_self");
var patientname = event.data.patientname;
var dataToSend = 'patientname=' + patientname;
var clinicquestions = getQuestionsForClinic();
var answers = [];
$.ajax({
type: "POST",
url: "../src/getselectedpatient.php",
data: dataToSend,
cache: false,
success: function(result) {
$.ajax({
url: "../src/getselectedpatient.php",
data: "",
dataType: "json",
success: function(row) {
answers = row;
console.log(row);
}
})
}
})
console.log(answers);
for (i in clinicquestions) {
$('#patientanswers').append("<h2>" + clinicquestions[i] + " = " + answers[i]);
}
$('#patientanswers').append("Patient Status = " + answers[answers.length - 1]);
}
And here is my PHP code:
<?php
session_start();
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$patientname = $_POST['patientname'];
$_SESSION['patient'] = $POST['patientname'];
$data = array();
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '$patientname'");
$data = mysql_fetch_row($query);
echo json_encode($data);
mysql_close($con);
?>
jQuery
var dataToSend = {'patientname':patientname};
$.ajax({
type : "POST",
url : "../src/getselectedpatient.php",
data : dataToSend,
dataType : "json",
cache : false,
success: function(result) {
console.log(result);
}
})
PHP
<?php
session_start();
$_SESSION['patient'] = $POST['patientname'];
$con = mysql_connect("devweb2015.cis.strath.ac.uk","uname","mypass") or ('Failed to connect' . mysql_error());
$currentdb = mysql_select_db('yyb11163', $con) or die('Failed to connect' . mysql_error());
$query = mysql_query("SELECT question1, question2, question3, question4, patient_status FROM patient_info where real_name = '".$_POST['patientname']."'");
$data = mysql_fetch_row($query);
mysql_close($con);
echo json_encode($data);
?>
For the record, I do not condone the use of your mysql_* shenanigans. It has been completely REMOVED in PHP 7 and don't try telling me that you will ride PHP 5 till death do you part.
Secondly, you are 8000% open to SQL injection.
I understand that you are most likely just a student at a school in the UK but if your teacher/professor is OK with your code then you are not getting your money's worth.
You probably forgot to set data on the second call:
$.ajax({
url : "../src/getselectedpatient.php",
data : result,
or result.idor whatever.

Display JSON Array as html list

I want to display my JSON array which i got from the PHP server as list in HTML. The code I used loops through the array, but when i replace the array with the variable it does not work.
$(document).ready(function(){
$(document).bind('deviceready', function(){
//Phonegap ready
onDeviceReady();
});
var ownproducts = $('#ownproducts');
$.ajax({
url: 'MYURL',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var products = '<br>'+item.item;
var ul = $('<ul>').appendTo('body');
var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] };
$(json.items).each(function(index, item) {
ul.append($(document.createElement('li')).text(item));
});
ownproducts.append(products);
});
},
error: function(){
ownproducts.text('Error Message');
}
});
});
So i get a JSON file containing data from my database, item.item contains an array but when i replace this:
var json = { items: ['Banana','Cherry','Apple','Strawberry','Pear','Pineapple'] };
for:
var json = { items: item.item };
or:
var json = { items: products };
it does not work (not displaying anything javascript related).
EDIT:
I try to get some items from my database through PHP
<?php
header('Content-type: application/json');
require 'config.php';
$con = mysqli_connect($url,$username,$password,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$userid = $_GET['userID'];
mysqli_select_db($con, $database);
$sql = "SELECT shoppingListID AS id, shoppingListUserID AS userid, shoppingCheckBox AS checkbox, shoppingItem AS item, shoppingDate AS date
FROM shoppinglist
WHERE shoppingListUserID='$userid'
ORDER BY shoppingDate DESC";
$result = mysqli_query($con,$sql) or die ("Query error: " . mysqli_error());
$records = array();
while($row = mysqli_fetch_assoc($result)) {
$records[] = $row;
}
mysqli_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
the ShoppingItem field contains an array like ["Tomatos","Apples","Mangos","Bananas"] the SQL returns multiple shoppinglists from a single user, I want to display the shoppinglists on cards with the items of each list in an html list.
Anyone any suggestions? I appreciate the help.
Let me suppose that your JSON endpoint does in fact return the right data -- in this case visiting what you"ve labeled MYURL generates (I believe!) the text:
jsoncallback({"items":["Banana","Cherry","Apple","Strawberry","Pear","Pineapple"]})
Then we can move on to your logic, which consists in this callback function:
function (data, status) {
$.each(data, function (i, item) {
var products = "<br>" + item.item;
var ul = $("<ul>").appendTo("body");
var json = {
items: ["Banana", "Cherry", "Apple", "Strawberry", "Pear", "Pineapple"]
};
$(json.items).each(function (index, item) {
ul.append($(document.createElement("li")).text(item));
});
ownproducts.append(products);
});
}
What is the problem here? There are a lot. The first is that you should probably not be iterating over data, since that is not your array. Instead you should be iterating over data.items.
The second is that you should probably just be creating the HTML rather than creating a ton of DOM stuff. You can use vanilla JS's Array.prototype.map or Array.prototype.join functions rather than delegating this to JQuery: it is a part of the JS spec that this is sufficient:
function (data, status) {
var html = '<ul><li>' + data.items.join('</li><li>') + '</li></ul>';
$(html).appendTo('body');
}

best option to get php array variable in Javascript produced by php script that requested through an ajax call

Currently I am trying to create a live search bar that only produce 5 results max and more option if there is over 5 results. So what I have done so far is a jquery ajax script to call a php script that runs asynchronously on key up in textbox I have.
I want to get the php array then I will code it further using javascript.
This is my code now:
Javascript code
<script type="text/javascript">
function find(value)
{
$( "#test" ).empty();
$.ajax({
url: 'searchDb.php',
type: 'POST',
data: {"asyn": value},
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
});
}
</script>
SearchDb PHP code:
<?php
function searchDb($abc, $limit = null){
if (isset($abc) && $abc) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$abc%'";
if($limit !== null){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
$lists = array();
while ( $row = mysql_fetch_assoc($result))
{
$var = "<div>".$row["testa"]."</div>";
array_push($lists, $var);
}
}
return $lists;
}
$abc = $_POST['asyn'];
$limit = 6;
$lala = searchDb($abc);
print_r($lala);
?>
How can I get $lala
Have you considered encoding the PHP array into JSON? So instead of just echoing the array $lala, do:
echo json_encode($lala);
Then, on the Javascript side, you'll use jQuery to parse the json.
var jsonResponse = $.parseJSON(data);
Then you'll be able to use this jsonResponse variable to access the data returned.
You need to read jQuery .ajax and also you must view this answer it's very important for you
$.ajax({
url: 'searchDb.php',
cache: false,
type: 'post'
})
.done(function(html) {
$("#yourClass").append(html);
});
In your searchDb.php use echo and try this code:
function searchDb($str, $limit = null){
$lists = array();
if (isset($str) && !empty($data)) {
$sql = "SELECT testa FROM test WHERE testa LIKE '%$data%'";
if(0 < $limit){
$sql .= "LIMIT ". $limit;
}
$result = mysql_query($sql) or die('Error, insert query failed') ;
while ( $row = mysql_fetch_assoc($result))
{
$lists[] = "<div>".$row["testa"]."</div>";
}
}
return implode('', $lists);
}
$limit = 6;
$data = searchDb($_POST['asyn'], $limit);
echo $data;
?>
If you dont have or your page searchDb.php dont throw any error, then you just need to echo $lala; and you will get result in success part of your ajax function
ALso in your ajax funciton you have
//you are using data here
success: function(data) {
return $lala;
var lala = $lala;
$( "#test" ).html($lala);
}
you must try some thing like this
success: function(data) {
var lala = data;
$( "#test" ).html($lala);
}

.ajax() isn't posting to php database query

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??

Categories

Resources