I'm trying to send a string from my JS file to my PHP file with an AJAX POST call and then insert that string into my Wordpress database.
I am able to send the string however I get this error message:
Notice: Undefined index: data in C:\Bitnami\wordpress-5.0.3-2\apps\wordpress\htdocs\wp-content\plugins\Kalkylator\templates\create.php on line 81
line 81 is: $data = $_POST['data'];
JS FILE
$(document).ready(function() {
var testingString = "hello people";
$.ajax({
url: "admin.php?page=jvformbuilder_create",
method: "POST",
data: { 'data': testingString },
success: function(result) {
console.log("result: " + result);
},
error: function(error) {
console.log("error: " + error);
}
});
});
PHP FILE
$data = $_POST['data'];
echo $data;
insertToDB($data);
function insertToDB($data)
{
$db = new mysqli('localhost', 'root', 'password', 'bitnami_wordpress');
if ($db->connect_errno > 0)
{
die('Unable to connect to database [' . $db->connect_error . ']');
}
// Attempt insert query to database.
$testing = "INSERT INTO wp_test (value) VALUES ('$data')";
mysqli_close($db);
}
Here is the file structure
I am currently working on my happypath hence why I don't validate the input to the database.
All help and tips are welcome, thanks in advance :D
Edit: I managed to solve the problem, it was like alot of people suggested that the data was being redirected in admin.php. so I just moved my php function there and now it works (atleast for my happypath). Thanks alot to all who took their time to help :D
You need to pass $data to the insertToDB() function. You currently reference it like this:
$data = $_POST['data'];
echo $data;
insertToDB ();
You need to do this:
$data = $_POST['data'];
echo $data;
insertToDB ($data);
Related
I have a simple Jquery code which makes an ajax call to a php code.
$(document).ready(function(){
var $isbn = $('#isbn');
var $authorName = $('#authorName');
var $bookTitle = $('#bookTitle');
$('#searchButton').click(function(){
var isbnValue = $isbn.val();
var authorNameValue = $authorName.val();
var bookTitleValue = $bookTitle.val();
alert(isbnValue);
$.ajax({
type: "GET",
url: "php/getBooks.php",
dataType: "json",
data: {
isbn: isbnValue
},
success: function (data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
And my PhP code connects to the Database and fetches data based on the query string. Here is my PhP code.
<?php
$dsn = 'mysql:dbname=library;host=localhost';
// 'mysql:host=localhost;dbname=myDatabase'
$username = 'root';
$password = 'maddie';
$isbnValue = $_GET["isbn"];
try {
$db = new PDO($dsn, $username, $password); // also allows an extra parameter of configuration
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$isbn = $db->quote($isbnValue);
$rows = $db->query("SELECT isbn, title FROM book WHERE isbn = $isbn");
$names = array();
foreach ($rows as $row) {
$names[] = array($row['isbn'], $row['title']);
}
print json_encode($names);
} catch(PDOException $e) {
die('Could not connect to the database:<br/>' . $e);
}
?>
When I execute from jQuery I get the below error object as response
Object {readyState: 0, responseText: "", status: 0, statusText: "error"}
Wherease if I directly call the php code using the URL -
http://localhost/LibraryManagement/php/getBooks.php?isbn=970880812
I get the json object as the result. I am not sure where the error is. Any help would be helpful. Thanks in advance.
The code you supplied seems functional. I even tested it locally with jQuery 1.12.1 and had no problems at all.
The error you are receiving is indicative of an ajax call being interrupted before it gets completed. there are many things that can cause this. The most common include cross domain issues and using links or forms actions in concert with your ajax call.
See the following article for more details on this:
http://www.justinball.com/2013/02/25/jqxhr-returning-readystate-0-and-status-0/
A quick google search for:
{readyState: 0, responseText: "", status: 0, statusText: "error"}
will reveal a number of other situations where that can occur as well.
Hope this helps ;)
I really have never done this before and I am getting frustrated because I'm not sure how it fits together. I have a function that I want to call my php (one php file selects info from a database and the second inserts into the database)... I need to use ajax in the way my site is setup but I don't know how to pass data from and to the php files.
In first .js file:
q1LoadVar();
This is my ajax function in second .js file that I have so far (not working):
//ajax code has been edited here since original post:
function q1LoadVar() {
alert("called"); //works!
$.get( "q1LoadVar1.php", function( data ) {
console.log(data); //nothing happens!
// alert(data); //nothing happens!
}, "json" );
}
And here is the code I have in q1LoadVar1.php that I want to select data back from and be able to populate a text area in my html:
/*works when I type this file path directly into the url;
but the file is not communicating back to the ajax function on the
.js file that is calling it*/
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
echo '<script type="text/javascript">alert("working from php!");</script>';
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
$newRow[] = $row;
}
$json = json_encode($newRow);
echo $json; //works on php file directly!
/*while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_AnswerChoosen];
}*/
mysqli_free_result($result);
mysqli_close($link);
?>
Can someone help me understand how to make this all work together? Thank you, Kristen
You can retrieve post data from ajax in php with
$_POST['action']
//in your case will return: test
To return data to ajax you need to use echo
If the success: callback function doesnt get called try to remove datatype: 'json'
I also think that you need to echo $newrow instead of $row.
If this still doesnt work you can catch the error with the error: callback function to see what is wrong.
Try to start with a simple request and work from there.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "yourphp.php",
data: {simplestring: "hi"},
success: function(result){
alert(result);
}
});
});
and yourphp.php
<?php
$simplestring = $_POST['simplestring'];
echo $simplestring;
I'm attempting to access data cross domain (testing locally) but the data keeps failing to load.
$.ajax({
type: 'POST',
url: 'http://localhost/php/ajax/json.php',
dataType: 'jsonp',
data: {action: 'get_json'},
success: function(data) {
console.log(data);
},
error: function() {
console.log("Error loading data");
}
});
The PHP is as follows (function is called through a switch statement earlier in the file).
function get_json() {
$mysqli = db_connect();
$sql = "SELECT * FROM json_test";
$result = $mysqli->query($sql);
$rows = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
array_push($rows, $row);
}
}
echo $_GET['callback']."(".json_encode($rows).");";
}
Headers are set at the start of the PHP document.
header('Content-Type: application/json');
The error I am receiving (if I run the PHP file by itself) is Undefined index: callback. The json string echoes fine as text after this error. (I have tried echo $_POST[...] as well).
How can I get this callback to work or how do I define it properly? Any help is appreciated.
add this parameter:
&jsoncallback=?
I was able to fix the error in the PHP file by changing the callback to the following:
$callback = "";
if (array_key_exists('callback', $_GET) == TRUE) {
$callback = $_GET['callback'];
}
echo $callback."('".json_encode($rows)."');";
The AJAX query now also retrieves the JSON data successfully.
my view contains the following code
this.keypadDisplay = Ext.create('Ext.field.Text', {
xtype:'textfield',
disabled: true,
value: ''
});
my ajax request code is
handler: function(b, e) {
var thisUser = this.getValue();
alert(thisUser);
//params[this.getSubmitParamName()] = this.getValue();
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: thisUser,
method:'GET',
success: function(response, opts){
var text = response.responseText;
console.log(response.responseText);
alert(thisUser);
//alert(this.getValue());
//alert('Value: ' + this.getValue());
Ext.Msg.alert('success', text);
},
failure: function(response, opts){
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
},
scope: this
});
}
here i'm getting the "this.getValue" successfully. i want to insert to this.getValue to the code table.
my code.php contains the following code
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db('form',$con);
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisUser.value']."')";
if(mysql_query($insert))
{
echo('values inserted successfully');
}
else
{
echo('failure' . mysql_error());
}
?>
here im getting the error as "Undefined index:thisUser.Value in .../keypadapp/code.php " on line 5.
can anyone help me to ? thanks in advance...
Assign param value to variable in ajax call:
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: 'thisuser='+thisUser,
Then in php, access the value:
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisuser']."')";
Try changing $_GET['thisUser.value'] to $_GET['thisUser_value'] dots in $_GET and $_POST get converted to underscores in PHP. See this for more info https://stackoverflow.com/a/68742/589909
Update
Looking closer at your code you can't get javascript values of an object in php like you are doing. I assume that thisUser is an object. So when passing it as a param its properties will be posted to the server individually. So if it had a property called foo you would get it like so. $_GET['foo']; also you could dump the get request to see what was sent. var_dump($_GET);
I want to populate a jQWidgets listbox control on my webpage(when page finished loading and rendering) with values from an actual MySQL database table.
PARTIAL SOLUTION: Here
NEW PROBLEM:
I've updated the source code and if I hardcode the SQL string - the listbox gets populated. But I want to make a small JS function - popList(field, table) - which can be called when you want to generate a jQWidgets listbox with values from a MySQL database on a page.
Problem is - for some reason the $field and $table are empty when the PHP script is being executed, and I receive You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM' at line 1 error. What gives?
The page:
<div id="ListBox">
<script type="text/javascript">
popList("name", "categories");
</script>
</div>
popList(field, value):
function popList(field, table) {
$.ajax({
type: "GET",
url: 'getListOfValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: 'json',
success: function(response) {
var source = $.parseJSON(response);
$("#ListBox").jqxListBox({ source: source, checkboxes: true, width: '400px', height: '150px', theme: 'summer'});
},
error: function() {
alert('sources unavailable');
}
});
}
getListOfValues.php:
<?php
require "dbinfo.php";
// Opens a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$field = $_GET["field"];
$table = $_GET["table"];
$field = mysql_real_escape_string($field);
$table = mysql_real_escape_string($table);
$qryString = "SELECT " . $field . " FROM " . $table;
$qryResult = mysql_query($qryString) or die(mysql_error());
$source = array();
while ($row = mysql_fetch_array($qryResult)){
array_push($source, $row[$field]);
}
mysql_close($connection);
echo json_encode($source);
?>
Ok, you have a few things here. First off you need a callback function when you do the ajaxRequest. (I'll explain why in a bit.) So add the following line BEFORE your ajaxReqest.send(null);
ajaxRequest.onreadystatechange = processAjaxResponse;
Then you need to add the processAjaxResponse function which will be called.
function processAjaxResponse() {
if (ajaxRequest.readySTate == 4) {
var response = ajaxRequest.responseText;
//do something with the response
//if you want to decode the JSON returned from PHP use this line
var arr = eval(response);
}
}
Ok, now the problem on your PHP side is you are using the return method. Instead you want PHP to print or echo output. Think about it this way. Each ajax call you do is like an invisible browser. Your PHP script needs to print something to the screen for the invisible browser to grab and work with.
In this specific case you are trying to pass an array from PHP back to JS so json_encode is your friend. Change your return line to the following:
print json_encode($listOfReturnedValues);
Let me know if you have any questions or need any help beyond this point. As an aside, I would really recommend using something like jQuery to do the ajax call and parse the response. Not only will it make sure the ajax call is compliant in every browser, it can automatically parse the JSON response into an array/object/whatever for you. Here's what your popList function would look like in jQuery (NOTE: you wouldn't need the processAjaxResponse function above)
function popList(field,table) {
$.ajax({
type: "GET",
url: 'getListofValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: "json",
success: function(response) {
//the response variable here would have your array automatically decoded
}
});
}
It's just a lot cleaner and easier to maintain. I had to go back to some old code to remember how I did it before ;)
Good luck!