I have a problem with catching AJAX data with PHP and send it to the database. Site is on the WordPress platform.
I have checked for the errors with mysqli_error but there nothing happened. Console not showing any error, just show there is `console.log data from the ajax, so the ajax work.
Here is what I have tried so far.
AJAX:
$.ajax({
type: 'post',
url: ajaxurl,
dataType: 'json',
data: {
'creditCardValue':creditCardValue,
'creditCardValueCvc':creditCardValueCvc,
'phoneNumberForm':phoneNumberForm
}
});
Here is a PHP code:
<?php
if (isset($_POST['button'])) { // button name from html
$creditCardValue = $_POST['creditCardValue'];
$creditCardValueCvc = $_POST['creditCardValueCvc'];
$phoneNumberForm = $_POST['phoneNumberForm'];
$query = "INSERT INTO validations(credit_card_number, credit_card_cvc, phone_number) ";
$query .= "VALUES ({$creditCardValue}, '{$creditCardValueCvc}', '{$phoneNumberForm}' ) ";
$create_post_query = mysqli_query($connection, $query);
}
?>
I need to send all these data to the database so I can later call them and displayed them.
Thanks in advance.
Remove the check for $_POST['button'] as this is not sent with the AJAX data. If you want to check if it's an AJAX call then just check that one of the values has been POSTed:
if (isset($_POST['creditCardValue'])) { ...
Related
I have this ajax snippet to pass the data to the particular php file. The passing data is the name of a html element
Here's my ajax code:
$(document).ready(function () {
alert(imgno);
$.ajax({
url: 'includes/upload-ad-image-inc.php',
type: 'post',
dataType: "html",
data: {
imgno: imgno
}
});
});
values for imgno will be : 1,2,3,4,.....
and this is my upload-ad-image-inc.php
$imageNO = $_POST['imgno'];
$sql = "UPDATE user SET userFName='$imageNO' WHERE userid=1;";
mysqli_query($conn, $sql);
But I get this error saying undefined index: imgno
but what is confusing is, when i change the php file to another php, i works
Can someone please help me?
Finally I found the problem and a solution:
It throws undefined index error when you have multiple ajax functions calling the same PHP file
To overcome this problem, check the passing data using isset() in PHP
if (isset($_POST['imgno'])) {
$imageNO = $_POST['imgno'];
$sql = "UPDATE user SET userFName='$imageNO' WHERE userid=1;";
mysqli_query($conn, $sql);
}
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.
Hi i'm a beginner in using JavaScript i have this html page with JavaScript codes that receives data from the server and display it on this current page, what i'm trying to do is use that data and sending it to another PHP page for my SQL query to get back results.
<script>
var json = sessionStorage.xhr;
var object = JSON.parse(json);
var hard = object["red-fruits"];
var string = JSON.stringify (hard);
var stringData = encodeURIComponent(string);
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
cache: false,
success: function(){
console.log("OK");
}
});
var user = sessionStorage.getItem('impData');
console.log(user);
</script>
This is my PHP page codes, what i'm doing here is getting the data "dataA" from that html page and sending it to this PHP page for the SQL query and getting the results which is the "$haha" array and using JavaScript session function to send it back to the HTML page. But my console only shows "null" can anyone tell me if i'm doing anything wrong or have any suggestion would be really appreciated.
<?php
$connection = mysqli_connect("localhost","root","","") or
die("Error " . mysqli_error($connection));
if (isset($_POST['dataA'])) {
echo $name = $_POST['dataA'];
}
else {
echo "Error";
}
$string = str_replace("]", "", str_replace("[", "", str_replace('"','',$falcon)));
$array = explode(',', $string);
$array2= implode("', '",$array);
$sql = // "SQL query"
$result = mysqli_query($connection, $sql) or die("Error in Selecting " .
mysqli_error($connection));
while($row = mysqli_fetch_array($result)) {
$haha[] = $row['row_name'];
}
?>
<script type="text/javascript">
var tills = <?php echo '["' . implode('", "', $haha) . '"]' ?>;
console.log (tills);
sessionStorage.setItem('impData', tills);
</script>
You are now mixing ajax and session data on a strange way. The session data used by your javascript will not be updated by the php-script till you refresh your page. The correct way to handle data is in the "success" function:
$.ajax({
type: "POST",
url: "http://localhost/web/main.php",
data: {"dataA" : stringData},
dataType : "json",
cache: false,
success: function(data){
console.log(data);
}
});
and in you PHP output the data you want to send to the browser as a json string:
echo json_encode($your_object);
I'm working on a project where I have an HTML file with 2 different divs: "product" and "price". The text inside these divs must come from a row into a database. I can easily access these text values with a php file. I'm also able to get just one of them using AJAX and I can put it inside one of the divs. The problem is I don't know how I can get both product and price and put them inside the divs. I've found some very similar questions but none of the answers have worked for me.
Here is the JS code that I have:
$.ajax({
type: "GET",
url: "url to the php file",
dataType: "html",
success: function(response){
$("#product").html(response);
}
});
Here is the php (the columns I have are just id, product and price):
mysqli_query($link, $query);
$query = "SELECT * FROM products WHERE id = 1";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_array($result)) {
echo "{$row['product']}";
}
}
As I said, the code above works, but only for "product". I want to get both "product" and "price". I really appreciate any help you can provide.
You need to use JSON. Here is a simple example:
$.ajax({
type: "GET",
url: "url to the php file",
dataType: "html",
success: function(response){
$("#name").html(response.name);
$("#shoes").html(response.large);
},
dataType: 'json'
});
And then in the PHP to return back JSON use this approach:
$array = array('name' => 'Bob', 'shoes' => 'large');
echo json_encode($array);
You can amend my PHP so you return back whatever you query from your database.
My ajax code from javascript
function makeRequest(button) {
alert(button.value);
var no =button.value;
$.ajax({
url: "findques.php",
type: 'POST',
dataType:"json",
data: {id:no},
success: function(response) {
$.each(response, function(idx, res){
alert(res.question);
});
},
error:function(err){
console.log(err);
}
});
}
My php code to retrive data is as follows
<?php
$connect =mysql_connect('localhost', 'root', 'password');
mysql_select_db('test');
if($connect->connect_error)
{
die("connection failed : ".$connect->connect_error);
}
if(isset($_POST['id']))
{
$var = mysql_real_escape_string(htmlentities($_POST['id']));
error_log($var);
}
$data = "SELECT * FROM `questions` WHERE no=$var";
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
else{
echo "error";
}
$connect->close();
?>
Im trying to retrive data from Mysql database from ajax through php but it shows me "error.jquery.min.js:6 GET 500 (Internal Server Error)"
Is that a problem with my ajax part or PHP part?? Im using Ubuntu 14.04 with apache 2 server.Some suggest there is a problem with server permissions??
You're using type: 'GET', and in PHP you're using $_POST['id'].
Change type to type: 'POST',
Your problem is invalid php code.
It appears you are using some strange mix of different examples on the server side:
$connect =mysql_connect('localhost', 'root', 'password');
This line returns a handle (a numeric value), and not an object which is what you try to use later on:
if($connect->connect_error)
This leads to an internal error.
To debug things like this you should start monitoring the error log file of your http server. That is where such errors are logged in detail. Without looking into these log files you are searching in the dark. That does not make sense. Look where there is light (and logged errors)!
I used mysqli instead of mysql_connect() and error is gone since mysql_connect() is deprecated on suggestions of patrick
Try changing this...
if(mysql_query($data)==TRUE)
{
$result=mysql_query($data);
$row = mysql_fetch_assoc($result);
$details =array( "id"=>$row['no'],"question"=>$row['Ques'],"op1"=>$row['op1'],"op2"=>$row['op2'],"op3"=>$row['op3'],"op4"=>$row['op4']);
echo json_encode($details);
}
To this...
$result = mysql_query($data);
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_assoc($result);
$details =array(
"id"=>$row['no'],
"question"=>$row['Ques'],
"op1"=>$row['op1'],
"op2"=>$row['op2'],
"op3"=>$row['op3'],
"op4"=>$row['op4']);
echo json_encode($details);
}
Not 100% sure that's the problem, but that's how I structure my basic DB functions, and it works fine.
I would also note that if this is going to to be a public page where users can enter data, I recommend using PHP PDO to handle your database interactions.