AJAX and PHP code not working - php

I am sending my form data through AJAX but for some reason my PHP script is not running. The test echo's Im using in my PHP script is not showing. The window.alert("success") does show but HIDE and SHOW form1 and form2 also does not work.
Here is the code:
$('#mainform').on('submit', function(event) {
//test for empty fields
//test for Bots
//insert data into DB
//pass t_code on to next form
//create a page number for tabs
event.preventDefault(); //stops form on submit
var a = document.forms["mainform"]["hidden"].value;
if (a === ""){
var formData = {};
$.each($("#mainform").serializeArray(), function (i, field) {
formData[field.name] = field.value;
});
$.ajax({
url: 'insert_tut_description.php',
data: formData,
method:'POST',
success: function(response) {
window.alert("success");
pnum = 1;
t_code = form.elements["t_code"].value;
$("#form1").hide();
$("#form2").show();
document.getElementById("pnum").innerHTML = pnum;
}
});
};
});
<?php
echo "php running";
require 'config/config.php';
$t_title = $conn->real_escape_string($_POST['t_title']);
$t_code = $conn->real_escape_string($_POST['t_code']);
$t_image = $conn->real_escape_string($_POST['t_image']);
$hidden = $conn->real_escape_string($_POST['hidden']);
$t_desc = $conn->real_escape_string($_POST['t_desc']);
$t_url = "something.php";
echo $t_title;
echo t_url;
if(empty($hidden)){
echo "hidden is empty";
$query = "INSERT into tutorial_list (title, description, t_code, t_url, image,) VALUES('" . $t_title . "','" . $t_desc . "','" . $t_code . "','" . $t_url . "','" . $t_image . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
} else {
$conn->close();
}
}
?>

Related

Ajax not working properly. PHP cannot insert data in SQL

I am using Jquery array to fetch variables on dynamic input forms. I could group and output the arrays into the console.log, but no data could be inserted within the multiple table database itself.
here's the Jquery code with ajax and console.log
$("button[name='submit_addPackresCategories']").click(function(){
var packres_categories_name;
$("input[id='packres_categories_name']").each(function(){
packres_categories_name = this.value;
});
console.log(packres_categories_name);
var packres_categories_description;
$("textarea[id='packres_categories_description']").each(function(){
packres_categories_description = this.value;
});
console.log(packres_categories_description);
var packres_categories_paxhead_day = {};
$("input[id^='packres_categories_paxhead_day']").each(function(){
packres_categories_paxhead_day[this.id] = this.value;
});
console.log(packres_categories_paxhead_day);
var packres_categories_paxhead_price = {};
$("input[id^='packres_categories_paxhead_price']").each(function(){
packres_categories_paxhead_price[this.id] = this.value;
});
console.log(packres_categories_paxhead_price);
var packres_categories_paxgroup_size = {};
$("input[id^='packres_categories_paxgroup_size']").each(function(){
packres_categories_paxgroup_size[this.id] = this.value;
});
console.log(packres_categories_paxgroup_size);
var packres_categories_paxgroup_consumable = {};
$("input[id^='packres_categories_paxgroup_consumable']").each(function(){
packres_categories_paxgroup_consumable[this.id] = this.value;
});
console.log(packres_categories_paxgroup_consumable);
$.ajax({
url: "ajax/addPackresCategories.php",
type: "post",
data: {
packres_categories_name: packres_categories_name,
packres_categories_description: packres_categories_description,
packres_categories_paxhead_day: packres_categories_paxhead_day,
packres_categories_paxhead_price: packres_categories_paxhead_price,
packres_categories_paxgroup_size: packres_categories_paxgroup_size,
packres_categories_paxgroup_consumable: packres_categories_paxgroup_consumable
}
})
.done(function(response){
if (JSON.parse(response)) {
alert("Successfully Added New Package!");
}
else {
alert("Failed!");
}
});
});
here's the url for the ajax
<?php
include_once("../db.php");
include "admin_session.php";
$packres_categories_name = $_POST["packres_categories_name"];
$packres_categories_description = $_POST["packres_categories_description"];
$packres_categories_paxhead = array_combine($_POST["packres_categories_paxhead_day"], $_POST["packres_categories_paxhead_price"]);
$packres_categories_paxgroup = array_combine($_POST["packres_categories_paxgroup_size"], $_POST["packres_categories_paxgroup_consumable"])
$sql_insertPackresNameDesc_packresCategories = "INSERT INTO packres_categories(packres_categories_name, packres_categories_description) VALUES('" . mysqli_real_escape_string($conn, $packres_categories_name) . "', '" . mysqli_real_escape_string($conn, $packres_categories_description) . "')";
$query_sql_insertPackresNameDesc_packresCategories = $conn->query($sql_insertPackresNameDesc_packresCategories);
$affectedRows_query_sql_insertPackresNameDesc_packresCategories = mysqli_affected_rows($conn); //will be used to verify if inserted properly on database later
$packres_id = mysqli_insert_id($conn);//will be used later
foreach ($packres_categories_paxhead as $key => $value) {
$sql_insertPackresCategoriesPaxhead_packresCategoriesPaxHead = "INSERT INTO packres_categories_paxhead(packres_id, packres_categories_paxhead_day, packres_categories_paxhead_day) VALUES('" . mysqli_real_escape_string($conn, $packres_id) . "', '" . mysqli_real_escape_string($conn, $key) . "', '" . mysqli_real_escape_string($conn, $value) . "')";
$query_sql_insertPackresCategoriesPaxhead_packresCategoriesPaxHead = $conn->query($insertPackresCategoriesPaxhead_packresCategoriesPaxHead);
$affectedRows_query_sql_insertPackresCategoriesPaxhead_packresCategoriesPaxHead += mysqli_affected_rows($conn);
}
foreach ($packres_categories_paxgroup as $key => $value) {
$sql_insertPackresCategoriesPaxGroup_packresCategoriesPaxgroup = "INSERT INTO packres_categories_paxgroup(packres_id, packres_categories_paxgroup_size, packres_categories_paxgroup_consumable) VALUES('" . mysqli_real_escape_string($conn, $packres_id) . "', '" . mysqli_real_escape_string($conn, $key) . "', '" . mysqli_real_escape_string($conn, $value) . "')";
$query_sql_insertPackresCategoriesPaxGroup_packresCategoriesPaxgroup = $conn->query($sql_insertPackresCategoriesPaxGroup_packresCategoriesPaxgroup);
$affectedRows_query_sql_insertPackresCategoriesPaxGroup_packresCategoriesPaxgroup += mysqli_affected_rows($conn);
}
$conn->close();
if (($affectedRows_query_sql_insertPackresNameDesc_packresCategories != 0) && ($affectedRows_query_sql_insertPackresCategoriesPaxhead_packresCategoriesPaxHead != 0) && ($$affectedRows_query_sql_insertPackresCategoriesPaxGroup_packresCategoriesPaxgroup != 0)) {
echo json_encode(true);
}
else {
echo json_encode(false);
}
?>
arrays of data should be inserted properly into the database, but no data were entering the database.
error line being thrown at console
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Object.<anonymous> (master.js:70)
at u (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
json_encode()- returns the JSON representation of a value.
And you are returning boolean

Ajax, retrieving ID of insert from within function

I'm trying to use Ajax to insert form data into the database and return the ID of that insertion.
It currently works as far as inserting (I can see it in the database) but I'm using alert to test that it's getting the ID of the insert and it simply says undefined.
Is there something I'm doing wrong to retrieve the ID?
<script type="text/javascript">
$(document).ready(function(){
$("#submitForm").click(function(){
var string = $('#pageForm').serialize();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "addPage.php",
data: string,
cache: false,
success: function(result){
alert(result.id);//this will alert you the last_id
}
});
});
});
</script>
addPage.php
$title = $_POST['addTitle'];
$page_type = $_POST['pageType'];
$display_id = $_POST['displayId'];
$duration = $_POST['durationSet'];
$addpage = "
INSERT INTO pages (title, page_type_id, display_id, duration)
VALUES ('$title','$page_type','$display_id','$duration');
";
if ($mysqlConn->query($addpage) === TRUE) {
$last_id = $mysqlConn->insert_id;
echo json_encode(['id'=>$last_id]);
echo "New record created successfully" . $last_id;
} else {
echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}
Try to return last inserted data id
$title = $_POST['addTitle'];
$page_type = $_POST['pageType'];
$display_id = $_POST['displayId'];
$duration = $_POST['durationSet'];
$addpage = "
INSERT INTO pages (title, page_type_id, display_id, duration)
VALUES ('$title','$page_type','$display_id','$duration');
";
if ($mysqlConn->query($addpage) === TRUE) {
$last_id = $mysqlConn->insert_id;
$data = json_encode(['id'=>$last_id]);
echo "New record created successfully" . $data ;
} else {
echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}
https://www.w3schools.com/PHP/php_mysql_insert_lastid.asp
Please first search before ask a question
if ($mysqlConn->query($addpage) === TRUE) {
$last_id = $mysqlConn->insert_id;
echo "New record created successfully" . $last_id;
} else {
echo "Error: " . $addpage . "<br>" . $mysqlConn->error;
}

Image change from dropdown using AJAX

Here I have one drop down menu on which selection other dropdown changes result the id of other dropdown is "style_code". Now I also want to change image on dropdown selection, it is like when I select color from dropdown it changes sizes which is other dropdown, but I also want to change image on color selection.
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data:'id='+val,
success: function(data){
$("#style_code").html(data);
}
});
}
</script>
Here is check.php
<?php
$con=mysqli_connect("localhost","root","","db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con,$query);
while ( ($row=mysqli_fetch_array($results))){?>
<option value="<?php echo $row["color_name"]; ?>">
<?php echo $row['size'] ; ?>
</option>
<?php
}
}
?>
Your difficulty comes from the fact that you are returning HTML code from the PHP script. My advice is to return JSON data then generate style_code children with jQuery.
It would be something like that :
check.php
<?php
$con = mysqli_connect("localhost", "root", "", "db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query = "SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
$data = new stdClass(); // This object will carry the results
while (($row = mysqli_fetch_object($results))) {
$data->option[] = $row;
}
// Another query to get the image name
$query = "SELECT name FROM image_name WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
if ($row = mysqli_fetch_object($results)) {
$data->image_name = $row->name;
}
header('Content-Type: application/json');
echo json_encode($data);
}
HTML & Javascript:
...
<div class="thumb-image" id="style_image" >
<img src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" />
</div>
...
<script language="javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data: {id: val},
dataType:'json',
success: function(data) {
$("#style_code").children().remove(); // empty the dropdown
// Add new options in the dropdown from the result data
data.option.forEach(function (item) {
$("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
});
// Change the 'src' attribute of the <img>
$("#style_image").find('img').attr('src', 'images/' + data.image_name + '?d=' + Date.now().toString());
}
});
}
</script>

Ajax - Sending and Receiving

I have 2 files, A .js and a .php. The .php connects to the MySQL DB and the .js is the front end of the system.
I'm in the middle of trying to set it up so it sends a hash key to the ajax which returns the correct data for the related person from the database.
So far it does work as it send the hash from the URL to the PHP file and returns back the data in the console log.
//AJAX Function
//Grabs Varibles from PHP
var hash = window.location.hash.substr(1);
$(function() {
$('.hashfield').text(hash)
});
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
console.log(data);
},
error:function() {
console.log("FAIL");
}
})
This is within the .js file which sends the hash
<?php
if(isset($_REQUEST['WorkingHash'])){
$hash = $_POST['hash'];
function IDHASH($hash){
echo $hash;
}
IDHASH($hash);
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, CustomerName, ContactName, Address, City, PostalCode, Country FROM customers WHERE ID=$hash";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
This is the .php file. I need to return the data from the database related to the correct customer ID.
All the data being echoed from the while loop will need it's own variably within a js format
My Goal is to retrieve each entry from the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
}
instead use
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
print_r(json_encode($row));
}
and in js
javacript
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
data = JSON.parse(data);
console.log(data);
//YOU CAN USE data.ID , data.CustomerName and so on
},
error:function() {
console.log("FAIL");
}
})
How about something like this:
Edit
instead of return data echo it like this:
if ($result->num_rows > 0) {
// echo the data instead of return
echo json_encode($result->fetch_assoc());
}
To access the properties of the object you can in your success function do that :
success: function(data){
// parse your data first
data = JSON.parse(data);
//Return of AJAX Data
console.log(data.CustomerName);
console.log(data.ContactName);
// you can assign them to a variables if you want
var customerName = data.CustomerName;
var ccontactName = data.CustomerName;
}

Get response text back from php after ajax request

I want to add data to my database, and get back the response from php which accesses the database.
javascript code:
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
var responseText = "onbekend";
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
So when the a name isn't valid or is already in existence, I can add this message to a span element in my html.
This is my php code:
<?php
if($_POST)
{
// Create connection
$con=mysqli_connect("localhost","root","root","websitedb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$date = getdate();
$date_time = $date['year'] . "-" . $date['mon'] . "-" . $date['mday'] . " " . $date['hours'] . ":" . $date['minutes'] . ":" . $date['seconds'];
$uitdagerArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitdager'] . "'");
$uitgedaagdeArray = mysqli_query($con,"SELECT id FROM deelnemers WHERE naam='" . $_POST['uitgedaagde'] . "'");
$uitdager = mysqli_fetch_array($uitdagerArray);
$uitgedaagde = mysqli_fetch_array($uitgedaagdeArray);
$uitdagerId = $uitdager['id'];
$uitgedaagdeId = $uitgedaagde['id'];
$sql="INSERT INTO duels (uitdager, uitgedaagde, aanmaakdatum, gespeeld) VALUES ('" . $uitdagerId . "','" . $uitgedaagdeId . "','" . $date_time . "','" . "0" . "')";
if(!mysqli_query($con,$sql)) {
echo mysql_errno() . ": " . mysql_error() . "\n";
}
else {
echo "Duel Toegevoegd";
}
mysqli_close($con);
}
?>
So is it possible that the text from echo in my php code will be passed to the 'response' from the succes function?
edit:
this is my html code
<div id="nieuwDuel">
<h2>Nieuw Duel</h2>
<form name="form" method="post">
Uitdager: <input type="text" id="naamUitdager" placeholder="naam uitdager">
Uitgedaagde: <input type="text" id="naamUitgedaagde" placeholder="naam uitgedaagde">
<input type="submit" class="nieuwDuelToevoegen">
</form>
<span id="duelToegevoegd" style="display:none"></span>
Home
</div>
I assume that your PHP code is right. then what you need to change is your jQuery code.
just change the following code :
responseText = jQuery(response);
document.getElementById("duelToegevoegd").innerHTML=responseText;
into following :
responseText = response;
$('#duelToegevoegd').html(responseText);
I don't know what you are going to do with
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
So, I leave it out for now
hope it helps
Yes it should work. Try changing your JS to
var request = $.ajax({
type: "POST",
url: "nieuwDuel.php",
data: dataString,
success: function(response)
{
console.log(response);//This will output the response you are getting to the console so you can check it
$("#duelToegevoegd").html(response);
$( "#openstaandeDuels" ).load( "getOpenstaandeDuels.php" );
}
});
Also I wouldn't echo out any errors you get back to the client
echo "Failed to connect to MySQL: " . mysqli_connect_error();
Although it depends who the user is, but you don't want anyone unauthorised to see these errors

Categories