I pass form data to php using jquery code then the php code save the data to the mysql database. If the title is "how to save & to mysql database using php", then the title will stored in database as "how to save". How can i fix this?
Here is my JS code
var dataString = 'title='+ title + '&url=' + url + '&description=' + description + '&published=' + published+ '&catid=' + catid;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function() {
$(".button").hide();
$('#messages').html("<div id='message'></div>");
$('#message').html("<h2>weblink Form Submitted!</h2>")
.hide()
.fadeIn(1500, function() {
$('#message');
});
}
});
and php code
<?php
$con = mysql_connect("localhost","db","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dalanrep_dalanreportcom", $con);
$title = mb_convert_encoding(trim($_POST['title']),'HTML-ENTITIES', 'UTF-8');
$url = mb_convert_encoding(trim($_POST['url']),'HTML-ENTITIES', 'UTF-8');
$description = mb_convert_encoding(trim($_POST['description']),'HTML-ENTITIES', 'UTF-8');
$published = mb_convert_encoding(trim($_POST['published']),'HTML-ENTITIES', 'UTF-8');
$catid = mb_convert_encoding(trim($_POST['catid']),'HTML-ENTITIES', 'UTF-8');
$title =mysql_escape_string($title );
$url = mysql_escape_string($url );
$description = mysql_escape_string($description );
$sql="INSERT INTO table (title, url, description,catid)
VALUES ('$title','$url','$description','$catid')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
The & is a special character in URL's. It is the separator character for multiple parameters. You need to either URL-encode the parameter value yourself by encodeURIComponent()
var dataString = 'title' + encodeURIComponent(title) + '&url=' + encodeURIComponent(url) ... ;
or to supply the parameters as a JS object {} so that jQuery will handle it itself.
var data = {
"title": title,
"url": url,
...
};
You need to encode the ampersand if it's data and not a segment delimiter.
<?php
$var = "some title with an & in it";
$title = htmlentities($var);
...
?>
Related
I have a little Form for adding articles to a blog the form processing is via JQuery
JQUERY CODE
$(function() {$(".submit").click(function() {
var title = $("#title").val();
var article = $("#article").val();
var tags = $("#tags").val();
var category = $("#category").val();
var subcategory = $("#subcategory").val();
var username = $("#username").val();
var views = $("#views").val();
var earning = $("#earning").val();
var dataString = 'title='+ title + '&article='+ article + '&tags='+ tags + '&category=' + category + '&subcategory=' + subcategory + '&username=' + username + '&views=' + views + '&earning=' + earning;
if(title=='' || article=='' || tags=='' || category=='' || subcategory=='' || username=='' || views=='' || earning=='')
{
$("#message-fail").fadeIn("slow");
setTimeout(function(){
$("#message-fail").fadeOut("slow");
},5000);
}
else
{
$.ajax({
type: "POST",
url: "inc/add-article.php",
data: dataString,
success: function showSuccessMessage(){
$("#message-success").fadeIn("slow");
setTimeout(function(){
$("#message-success").fadeOut("slow");
},5000);
}
});
}
return false;
});
});
This is my add-article.php file
<?php
if($_POST)
{
$title=$_POST['title'];
$article= $_POST['article'];
$tags=$_POST['tags'];
$category=$_POST['category'];
$subcategory=$_POST['subcategory'];
$username=$_POST['username'];
$views=$_POST['views'];
$earning=$_POST['earning'];
$date = date('d-m-Y H:i:s');
$link = mysql_connect('localhost', 'root', 'bfggyys');
if (!$link) {
die('Verbindung nicht möglich : ' . mysql_error());
}
// benutze Datenbank foo
$db_selected = mysql_select_db('blog', $link);
if (!$db_selected) {
die ('Kann foo nicht benutzen : ' . mysql_error());
}
mysql_query("INSERT INTO articles SET title='".mysql_real_escape_string($title)."', article='".$article2."', tags='".mysql_real_escape_string($tags)."', category='".mysql_real_escape_string($category)."', subcategory='".mysql_real_escape_string($subcategory)."', username='".mysql_real_escape_string($username)."', views='".mysql_real_escape_string($views)."', earning='".mysql_real_escape_string($earning)."', date='".mysql_real_escape_string($date)."'");
}else { }
?>
My Problem is i dont know how to transform the value from article the right way to insert it into db if i insert now a post article value cant be inserted because it stopps inserting into mysql on first space sign .How can i escape it right for inserting into mysql db?
I'm trying to update my database on the event of a change in my select box. The php file I'm calling on to process everything, works perfectly. Heres the code for that:
<?php
$productid = $_GET['pID'];
$dropshippingname = $_GET['drop-shipping'];
$dbh = mysql_connect ("sql.website.com", "osc", "oscpassword") or die ('I cannot connect to the database because: ' . mysql_error()); mysql_select_db ("oscommerce");
$dropshippingid = $_GET['drop-shipping'];
$sqladd = "UPDATE products SET drop_ship_id=" . $dropshippingid . "
WHERE products_id='" . $productid . "'";
$runquery = mysql_query( $sqladd, $dbh );
if(!$runquery) {
echo "Error";
} else {
echo "Success";
}
?>
All I have to do is define the two variables in the url, and my id entry will be updated under the products table, ex: www.website.com/dropship_process.php?pID=755&drop-shipping=16
Here is the jquery function that is calling dropship-process.php:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
$('#drop_shipping').change(function() {
var pid = $.urlParam('pID');
var dropshippingid = $(this).val();
$.ajax({
type: "POST",
url: "dropship_process.php",
data: '{' +
"'pID':" + pid + ','
"'drop-shipping':" dropshippingid + ',' +
'}',
success: function() {
alert("success");
});
}
});
});
I'm thinking that I defined my data wrong some how. This is the first time I've ever used anything other than serialize, so any pointer would be appreciated!
Would it not be enough to define your URl like so:
url: "dropship_process.php?pID="+ pid +"&drop-shipping="+ dropshippingid
Your ajax code is not correct. replace your ajax code by below code:
$.ajax({
type: "POST",
url: "dropship_process.php",
dataType: 'text',
data: {"pID": pid,'drop-shipping': dropshippingid},
success: function(returnData) {
alert("success");
}
});
The javascript parameter "Step" should trigger a switch-case function in php. If Step is one than trigger this piece of code in php and return the output by JSON.
If I take a look in firebug the post string is: Step=one&inputFname=rick&inputLname=bovenkamp I think this is correct. So the problem must be in the php file and I think it's in the $_POST part...
What am I doing wrong? Any help would be very great!
javascript code:
$(document).ready(function() {
$("form#userForm").submit(function() {
var inputFname = $('#inputFname').attr('value');
var inputLname = $('#inputLname').attr('value');
var Step = "one";
$.ajax({
type: "POST",
url: "main.php",
data: {Step: Step,inputFname: inputFname,inputLname: inputLname},
dataType: "json",
contentType:"application/json; charset=utf-8",
success: function(data) {
$("p.succesText").html(data.jsCode);
$("form#userForm").hide();
$("div.success").fadeIn();
},
error: function(xhr, status, error) {
$("form#userForm").hide();
$("p.errorHead").html("Something went wrong.");
$("p.errorText").text("ResponseText: " + xhr.responseText
+ "Statuscode: " + xhr.status
+ "ReadyState: " + xhr.readyState);
$("div.error").fadeIn();
}
});
return false;
});
});
PHP file:
<?php header('content-type: application/json; charset=utf-8');
$log = array();
$varStep = htmlspecialchars(trim($_POST["Step"]));
switch($varStep) {
case "one":
$varFname = htmlspecialchars($_POST["inputFname"]);
$varLname = htmlspecialchars($_POST["inputLname"]);
//Make Database connection
$db = mysql_connect("192.168.178.254","root","852456");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("Ajax" ,$db);
//Generate code and check if code already exists in the database
do
{
$varCode = rand(10000, 99999);
$dbCheckCode = "";
$dbCheckCode = mysql_query("SELECT * FROM TableAjax WHERE code='$varCode'");
}
while (mysql_fetch_array($dbCheckCode) !== false);
//Save the Form data in the database
$sql = "INSERT INTO TableAjax (fname, lname, code) VALUES (".PrepSQL($varFname) . ", " .PrepSQL($varLname) . ", " .PrepSQL($varCode) . ")";
mysql_query($sql);
//Return code to frontend
$log['jsCode'] = $varCode;
break;
}
echo json_encode($log);
//Clean SQL statement
function PrepSQL($value)
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
?>
Put Step in quotes data : {"Step" : Step,....
You are passing the value of the variable as the key in that case, that is to say you are actually passing data : {"one" : "one",.... You should do the same with inputLname and inputFname.
Edit - Explanation
If you look at what the contentType options does here at http://api.jquery.com/jQuery.ajax/, you will see that the default is application/x-www-form-urlencoded which is what you want. Essentially what your PHP error was indicating is that the $_POST array was empty because it did not know how to read your data due to the format. You want your return data to be json, the dataType option was all you needed.
You still would have needed to do what I indicated in the first part of the post, but essentially you had two errors that were tripping you up.
I hope this makes sense!
I am trying to pass some values to my PHP page and return JSON but for some reason I am getting the error "Unknown error parsererror". Below is my code. Note that if I alert the params I get the correct value.
function displaybookmarks()
{
var bookmarks = new String();
for(var i=0;i<window.localStorage.length;i++)
{
var keyName = window.localStorage.key(i);
var value = window.localStorage.getItem(keyName);
bookmarks = bookmarks+" "+value;
}
getbookmarks(bookmarks);
}
function getbookmarks(bookmarks){
//var surl = "http://www.webapp-testing.com/includes/getbookmarks.php";
var surl = "http://localhost/Outlish Online/includes/getbookmarks.php";
var id = 1;
$.ajax({
type: "GET",
url: surl,
data: "&Bookmarks="+bookmarks,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "getbookmarkscallback",
crossDomain: "true",
success: function(response) {
alert("Success");
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
}
function getbookmarkscallback(rtndata)
{
$('#pagetitle').html("Favourites");
var data = "<ul class='table-view table-action'>";
for(j=0;j<window.localStorage.length;j++)
{
data = data + "<li>" + rtndata[j].title + "</li>";
}
data = data + "</ul>";
$('#listarticles').html(data);
}
Below is my PHP page:
<?php
$id = $_REQUEST['Bookmarks'];
$articles = explode(" ", $id);
$link = mysql_connect("localhost","root","") or die('Could not connect to mysql server' . mysql_error());
mysql_select_db('joomla15',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT * FROM jos_content where id='$articles[$i]'";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
for($i = 0; $i < count($articles); $i++)
{
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = $post;
}
}
}
header('Content-type: application/json');
echo $_GET['onJSONPLoad']. '('. json_encode($posts) . ')';
#mysql_close($link);
?>
Any idea why I am getting this error?
This is not json
"&Bookmarks="+bookmarks,
You're not sending JSON to the server in your $.ajax(). You need to change your code to this:
$.ajax({
...
data: {
Bookmarks: bookmarks
},
...
});
Only then will $_REQUEST['Bookmarks'] have your id.
As a sidenote, you should not use alert() in your jQuery for debugging. Instead, use console.log(), which can take multiple, comma-separated values. Modern browsers like Chrome have a console that makes debugging far simpler.
I have taken a jQuery script which would remove divs on a click, but I want to implement deleting records of a MySQL database. In the delete.php:
<?php
$photo_id = $_POST['id'];
$sql = "DELETE FROM photos
WHERE id = '" . $photo_id . "'";
$result = mysql_query($sql) or die(mysql_error());
?>
The jQuery script:
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
The div goes away when I click on it, but then after I refresh the page, it appears again...
How do I get it to delete it from the database?
EDIT: Woopsie... forgot to add the db.php to it, so it works now >.<
There's no way the php could even come close to working. Where is the database? Check out http://www.php.net/manual/en/mysql.examples-basic.php from which you can see there's more to the database than just a query.
<?php
// Connecting, selecting database
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('my_database') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM my_table';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
You have your data as a GET string, but you are using a POST request, try changing your string variable to an object. Like :
$(document).ready(function() {
$('#load').hide();
});
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = { id : id };
$.ajax({
type: "POST",
url: "delete.php",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$("#photo-" + id).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
Plus I am hoping you are preparing your MySQL connection properly in your PHP, you cannot just call mysql_query and hope it will know which database you mean, and how to connect to it by itself :)
Look at #Quotidian answer! :)