Insert Into MYSQL DB using jquery/ajax 500 internal server error - php

I'm inserting radio checked data values into mysql db with php/jquery and ajax while inserting values i'm getting internal server 500 error...
Any help is appreciated Thanks!
Html Code
<div>
<input class="radio_div_clicked" value="<?php echo $row['name'];?> name="radio_section" id="<?php echo $row['id'];?>"/>
<p><?php echo $row['name'];?></p>
<button id="add_feed">Add</button>
</div>
JQUERY CODE
<script type="text/javascript">
$('body').delegate('#add_feed','click',function(){
var radio_div_clicked = $('input:radio[name=radio_section]:checked').val();
$.ajax({
type:"POST",
url:"index.php",
cache: false,
data:{
insert_section:1,
radio_div_clicked:radio_div_clicked
},
success:function(data)
{
alert('Successfully Inserted Into Table');
}
});
}
});
</script>
PHP code
<?php
$con = #mysql_connect('localhost','root','') or die('failed to connect server');
$db = mysql_select_db('demo',$con) or die('failed to select db');
if(isset($_POST['insert_section']))
{
$radio_div_clicked = mysql_real_escape_string($_POST['radio_div_clicked']);
$sql = mysql_query("insert into test(name) values($radio_div_clicked)";
if($sql)
{
echo "Successfully Inserted Into Table";
}
else
{
echo "Failed To Insert Value Into Table"
}
}
?>
<?php
mysql_close ($con);
?>

Mysql query values($radio_div_clicked)"; did't closed properly, should be
$sql = mysql_query("insert into test(name) values('".$radio_div_clicked."')");
If you're using chrome, click on network tab, and click the requested link. Then, again click on preview or response header. Usually the details errors showing up there.

Related

Retrieve ID number from MYSQL using AJAX & PHP then hashchange URL using retrieved ID

I'm trying to retrieve the latest video ID number from my database and then use that ID number to hashchange my URL and display the corresponding video. My PHP is working and returning a result but I'm not sure how to take that result and use it in jQuery so that I can use it for the hashchange. I haven't used jQuery much before so any detailed help would be amazing! Please find my current code below. The main question I have is how do I pass the $vidarray to jQuery so I can use that variable?
videoprocess.php
<?php
// Connect To DB
$hostname="localhost";
$database="MYDB";
$username="root";
$password="";
#$conn = mysqli_connect($hostname, $username, $password)
or die("Could not connect to server " . mysql_error());
mysqli_select_db($conn, $database) or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
// Display Error message if fails
echo 'Error, could not connect to the database please try again again.';
exit();
}
$query = "SELECT VIDEOID FROM JubileeTouchVideo ORDER BY ID DESC LIMIT 1";
$result = mysqli_query($conn, $query) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$vidarray = array();
while($row = mysqli_fetch_assoc($result))
{
$vidarray = $row;
}
echo json_encode($vidarray);
//close the db connection
mysqli_close($conn);
?>
videoprocess jquery
$.ajax({
url: "data.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//Not sure what to do after this
}
});
This is how you can pass data to ajax.
$.ajax({
type: "POST",
url: url,
data: <?php echo $vidarray["id"]; ?>,
dataType: "text",
success: function(result) {
//result downloaded so we call parseJSON function
//and pass downloaded result
var json = $.parseJSON(result);
//Not sure what to do after this
}
});

referencing an image from php

I have a function on a website where I have a img reference leading to a php page
<img src="selectimage.php?uid=21312412">
which I need to return an image and update a database file
<?php
$servername = "localhost";
$username = "webz";
$password = "BLAH";
$dbname = "contactlist";
$readid = $_GET["uid"];
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "UPDATE emails SET `read`='1' WHERE `id`='" .$readid. "'";
if ($conn->query($sql) === TRUE) {
echo "<img src='logo11w.png'>";
}
$conn->close();
?>
I figured this would not work as I am referencing a php page in which is referencing the HTML tag
While this is updating my database it is not displaying the image.
how do I make this php file send the image logo11w.png to that img tag
Further note : include or other methods of including this code on the page loading are out of the question because this procedure may be called from a off-server source.
Store user id in one hidden field
You can use ajax for get respone back from php page after updating value in database
<input type="hidden" id="userid" value="user_id_value">
<input type="button" id="getimage" value="GET IMAGE">
<div id="u_img"></div>
$(document).ready(function(){
$('#getimage').click(function() {
var uid = $('#userid').val();
var datastring = "uid="+uid;
$.ajax({
type: "POST",
url: "php_page.php",
data: datastring,
cache: false,
success: function(result) {
$('#u_img').append(result);
}
});
});
});
The most effective method for what I am trying to do turns out to be:
...
if ($conn->query($sql) === TRUE) {
header('Content-Type: image/jpeg');
echo file_get_contents('https://www.google.com/images/srpr/logo11w.png');
} else {
echo "Error updating record: " . $conn->error;
}
...

Getting my form data to post to mysql database

Pretty new to php/mysql and jquery, and I'm having trouble getting my form data to upload to my mysql db. I've tried a few different approaches and done my research, but none of the suggestions I've found online are working for me, which is why I'm posting here. So here's my most recent failed approach:
in my index file:
<head>
...
<script type="text/javascript">
$(document).ready(function() {
// Announcement form AJAX submit
$('#announcementForm').submit(function() {
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
if (data.error) {
$('#error').css('display', 'block');
} else {
$('#note').show();
$('#error').hide();
$('#fields').hide();
}
}
});
return false;
});
});
</script>
</head>
<body>
...
<form class="dl_form" id="announcementForm" method="post">
<dl>
<dt>Announcement</dt>
<dd><textarea id="Announcement" sytle="width: 300px; height: 150px;" name="Announcement"></textarea></dd>
</dl>
<dl>
<dt>Announcement Type:</dt>
<dd><input type="radio" name="Type" value="schedule">Scheduling</input></dd>
<dd><input type="radio" name="Type" value="general">General</input></dd>
</dl>
<dl>
<dt></dt>
<dd><input type="submit" value="submit" /></dd>
</dl>
</form>
<div id="note">
<p>Announcement posted successfully!"</p>
</div>
<div id="error">You haven't completed all of the required fields</div>
And then in my ajax.php file I have (some lines have been replaced with "######" for security reasons):
<?php
//database credentials
$server = '######';
$username = '######';
$password = '######';
$database = '######';
$connect = mysql_connect($server, $username, $password ) or die(mysql_error.'error connecting to db');
//select database
mysql_select_db($database, $connect) or die(mysql_error.'error selecting db');
//$typeValue = $('input:radio[name=Type]:checked').val());
if (!empty($_POST)){
$Announcement = $_POST['Announcement'];
$Type = $_POST['Type'];
if (!empty($Announcement) && !empty($Type) )
{
//insert data into db
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement."')") or die(mysql_error());
}else {
echo json_encode(array(
'error' => true,
'msg' => "You haven't completed all required fields!"
));
exit;
}
}
?>
Any help you guys can provide would be much appreciated.
Thanks
UPDATE IN RESPONSE TO Jay Blanchard:
I just ran the console in my browser. The only error I'm getting is:
SCRIPT1004: Expected ';'
in reference to the first line of my JS:
$function() {
...
UPDATE 2:
Just updated my code to reflect my most recent changes...before I could at least trigger the submit click even and the fields would empty, indicating that at least something was happening. With my new round of changes however, not even that triggers, so I'm still pretty stuck
In your php you've made a mistake with your echo statement its not jason_encode instead its json_encode.
Additionally
Also you Should remove AnnouncementID from your query if in database it is auto increment, because db will warn you for incorrect integer value for column AnnouncementID.
EDIT: In your php part in statement
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement"')") or die(mysql_error());
You are forgetting a concatenation operator . after '".$Announcement which should be
mysql_query("INSERT into announcements (AnnouncementID, Type, Announcement)
VALUES ('', '".$Type."', '".$Announcement."')") or die(mysql_error());
and in your jquery instead of
$function() {
use
$(document).ready(function(){

Why is PHP mysql_insert_id() returning zero?

I have the following code. The $last_id is always showing zero. I do have a column in the "source" table that has auto-increment id. What is the problem with this code?
index.php:
<?php
// connect to the database
include('connect-db.php');
$last_id = mysql_insert_id($connection);
$content = "Please type your content here!";
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
function(data){
alert("Your ID: <?php echo $last_id;?>");
}
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
connect-db:
<?php
$server = 'localhost';
$user = 'mumbo';
$pass = 'mumbo123';
$db = 'jumbo';
$connection = mysql_connect($server, $user, $pass)
or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db)
or die ("Could not connect to database ... \n" . mysql_error ());
?>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
try this as submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
echo mysql_insert_id();
}
?>
and in the javascript:
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
function(data){
alert("Your ID: " + data);
}
);
return false;
});
});
</script>
This line is computed when the original page loads:
alert("Your ID: <?php echo $last_id;?>");
So it's effectively:
alert("Your ID: 0");
Since all you've done at that point is connect, there is no insert id. I'm not familiar with jquery, but presumably the data parameter to your callback should contain data about the response from submit.php. You need to make submit.php return the ID, then get that data through whatever means in jquery, and display it.
Edit: actually, it looks like what you're doing can't really do what I said, anyhow.
http://api.jquery.com/submit/
You're setting up a handler which is run whenever the form is submitted - however, this is before the submit actually happens, so you can't actually get the ID there. Your options are to use something like XmlHttpRequest to make an asynchronous call, or have this popup on the submit.php page.
First of all do not use mysql, use mysqli or pdo, mysql is a deprecated system and should not be used. It is not secure and can be hacked easily.
Second, mysql_insert_id only works if you call it directly after the insert...
AKA
if ($content != '') {
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
$last_id = mysql_insert_id();
echo $last_id
mysql_close($connection);
then your jquery must say
alert("Your ID: "+data);
The function data that is returned is whatever you echo from your script. Jquery retrieves it in whatever callback variable you set (data) and then you can use it.

How to generate a JSON based on form selections to build SQL statement by using a jQuery AJAX call to a PHP script

I have an HTML form(2 list-boxes and a check-box) which I want to use for filtering results on the page.
How can I make it so when I press the Submit button(.onclick(function(){})) it would execute a jQuery AJAX call to a PHP script on my local server that will, firstly, check if anything was selected in the list-boxes and if the check-box was checked and then based on that build a SQL statement to query my database and retrieve the result as JSON.
How would you do it, theoretically. I already have the PHP script to simply grab everything from my table and save it as JSON:
<?php
// databse connection info
require("dbinfo.inc.php");
// try to open a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// select the active MySQL database to work with
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// grab data about every campus and which instituion they belong to
$query = 'select statement to grab all the data from a table';
$result = mysql_query($query);
// check if $results has anything
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// time to start generating our huge XML
while ($row = #mysql_fetch_assoc($result)){
$finalarray[] = $row;
$main_arr['products'] = $finalarray;
}
// close connection to the database
mysql_close($connection);
// echo, save and write the file
// print json_encode($main_arr);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($main_arr));
fclose($fp);
?>
First send the data from the form with ajax:
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url : 'myPHPfile.php',
data: {form : $('form').serialize()}
}).done(function(data) {
var myJSONresult = data;
});
});
In your PHP file you'll get the form with
$form = $_POST['form'];
and there's no need to save to a file, just send it back by echoing
echo json_encode($main_arr);
Here is an example of posting to a php file and grabbing the data with ajax.
The result will get logged into the console.
I assume you know how to process the json with js once it has been retrieved?
//the php
<?php
//bla bla connect to database etc
//if form has been submitted with ajax
if(isset($_POST["ajax_request"])){
//build query
$id = $_POST["id"];
$fruit = $_POST["fruit"];
$query = "SELECT * FROM fruits WHERE id=$id AND fruit='$fruit'";
//fetch from db
$result = mysql_query($query);
//send out json
die(json_encode($result));
}
?>
//the jquery
<script type="text/javascript">
$(document).ready(function(){
//on submit
$("#ajaxForm").submit(function(e){
//stop default page refresh
e.preventDefault();
//define the form
var form = $(this);
//get the form data
var data = form.serialize();
//send it via ajax
$.ajax({
type : "post",
dataType : "json",
url : "url to your php here",
data : data+"&ajax_request=1",
success : function(json){
console.log(json);
},
error : function(a,b,c){
console.log(a,b,c);
}
});
});
});
</script>
//the html
<form id="ajaxForm" method="post" action="">
<input type="text" name="id" required="required" placeholder="enter id"/>
<input type="text" name="fruit" required="required" placeholder="enter fruit"/>
<input type="submit" name="submit"/>
</form>

Categories