So... I've been trying to use a JQuery post requests to insert data in my database for 2 days and can't make it work, and don't have any idea why... I bet someone already faced this issue too, so I'm here looking for this person :)
Here's the issue:
Into the html file, the part with JQuery (it's on a click event):
var eventData;
eventData = {
title: title,
start: start,
end: end
};
$.post("add.php", eventData);
The add.php file:
$con = mysqli_connect("localhost", "root", "", "jqcalendar" );
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
mysqli_query($con, "INSERT INTO jqcalendar(title,start,end) VALUES({$title},{$start},{$end})");
mysqli_close($con);
Can't make this thing work, already tried putting echoes but it seems the php file isn't even being executed by the $.post command... If someone could help I'd really really appreciate it...
EDIT:
the title, start and end are strings previously defined with the "" !
I used the console inspection and got this error at the same line as the
$.post:
$.fullCalendar.select # index.html:35
You have to use quotes when you are specifying the value in a javascript object (otherthan for numbers).
eventData = {
title: "title",
start: "start",
end: "end"
};
Tips
Also, you can see whether there's an error with your javascript part by inspecting element. Right click and click inspect/inspect element. Then go to the console. You will see errors there if there's any once you execute the javascript part.
Also when debugging javascript part, you can use console.log() to see the values of the variables
Figured it out, the problem is within the variables "start" and "end", they're composite date type ISO8601, what was causing trouble when received for inserting into database... thank you all for your time, but now the problem is converting this date object to a custom String...
Related
I am trying to register a button click on my website using PHP.The click downloads a file to client's machine. Database connection was tested before and it works fine. I just need to register that click into DB. Here is my code, could you guide me through?
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
if(isset($_GET['dl']))
{
$server = "xx.xxx.xx.xxx";
$dbusername = "xxxx";
$dbpassword = "xxxx";
$database = "xxxx";
$dbcon = new mysqli($server,$dbusername,$dbpassword, $database);
$userid = $_SESSION['suserid'];
$date_downloaded = date('Y-m-d H:i:s');
$sql = "INSERT INTO external_activity (
userid,
saleid,
activity,
date_register,
) VALUES (
'".$userid."',
'".$ref_no."',
'".'Downloaded file'."',
'".$date_downloaded."'
)";
$dbcon->query($sql);
$dbcon->close();
}
If using jquery is an option, you could create a "register_click.php", paste the if(isset($_GET['dl'])) stuff inside and call it via ajax using an onclick listener that you will have to create and bind to the anchor.
You could do it with POST data instead of GET.
$i = 0;
if $_POST['submit'] {
$i++;
$number_of_times_clicked = $number_of_times_clicked_stored_into_database + $i;
}
After that restore the new value back into the database. If you really want the onclick you need javascript. PHP is unable to check when a button is clicked, since the code only works once when the page is loaded.
This is too long for a comment.
The & in your code might give you some problems, I said "might". If so, then consider changing those to & (ampersands).
Should it be the case, then you could change:
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
to:
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
Then you will need to check and see if each GET array is is set/not empty with isset() and !empty().
References:
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
I only see if(isset($_GET['dl'])) as a single array, so it's unsure as to how you're wanting to fetch the other GET arrays in your URL and if you did set those.
Your present code (if it's the full code), will throw a few notices about certain variables not being defined.
For example, the if(isset($_GET['dl'])) and using the other GET arrays, would look like this:
if( isset($_GET['f']) && !empty($_GET['l']) && !empty($_GET['dl']) ){
// do something inside here
}
You also need to make sure that the session was indeed started with session_start(); and to be included inside all files using sessions.
Reference:
http://php.net/manual/en/function.session-start.php
This is usually the first line under the opening PHP tag.
<?php
session_start();
// rest of your code
The $userid = $_SESSION['suserid']; needs to have a value/equal something, so that is unknown as to whether or not there is indeed a value for it.
Error reporting will be of help here for you, as will checking for errors against your query.
References:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
You also have a trailing comma in date_register, < and that needs to be removed, as I already stated in comments.
That alone would have thrown a syntax error.
The use of '".'Downloaded file'."' is unclear. If you just want to insert the Downloaded file as a string, then you can just place it inside single quotes 'Downloaded file' and do:
$sql = "INSERT INTO external_activity (
userid,
saleid,
activity,
date_register
) VALUES (
'".$userid."',
'".$ref_no."',
'Downloaded file',
'".$date_downloaded."'
)";
Make sure that the date_register column type is DATE and not VARCHAR or other format. Although VARCHAR would not throw an error, it's best to use MySQL's built-in dating functions; that column's type is unknown.
Now, make sure that the userid column is not an AUTO_INCREMENT'ed column, otherwise your code will fail.
If the ultimate goal here is to "UPDATE" that userid column, then use just that, UPDATE:
http://dev.mysql.com/doc/refman/5.7/en/update.html
You also need to make sure that all columns' types are correct and have a length long enough to accomodate the incoming data and that there are no characters that MySQL will complain about, such as apostrophes.
Escaping those with a prepared statement will ensure that it doesn't throw/cause a syntax error and is something you should be using in order to help prevent against an SQL injection and you are open to one right now.
References:
https://en.wikipedia.org/wiki/Prepared_statement
https://en.wikipedia.org/wiki/SQL_injection
This is the best way that I can offer for the question, given the information left in the question.
Again; check for errors. That is one of the most important things that needs to be done during the development of your code.
My jqgrid loads perfectly data, but when I want to commit changes on it, nothing happens on my database.
I don't know exactly when happens the "enter key" event for saving the row, so I don't know where put this code:
jQuery("#lista").saveRow(id, function(){alert("changes saved")}, 'guardar_lista.php');
I already saw this example: JQgrid checkbox onclick update database
but I'm very hard headed about how to use ajax for send the info (sorry, I'm a newbie).
Can you give me a code example of how to send the info with ajax?
Here is my Editurl code:
<?
$dbhost="localhost";
$dbuser="root";
$dbpassword="";
$database="db_proyecto";
$db = mysql_connect($dbhost, $dbuser, $dbpassword) or die("Connection Error: " . mysql_error());
mysql_select_db($database, $db);
if($_POST['oper']=='edit'){
$invid=$_POST['id'];
$tax=$_POST['tax'];
$note=$_POST['note'];
$total=$_POST['total'];
$SQL="update invheader set note='"+$note+"' where invid="+$invid;
mysql_query($SQL,$db);
}
Thank you in advance #ruffin! (Sorry for the delay, I was very busy)
Well, you're going to have to post a little more code for us to know for sure. Your grid should have a value for your editurl, which is the page that's going to process your updated data (iirc). Just to be clear, that url is where you'd insert your mysql_query jive.
Note that you're either going to have jive coming in your $_GET or $_POST collection with the new values from the grid, with "_empty" for the id column if it's a new row (since it's not filled; this is a new row). (Yes, I realize you're updating, but just in case you add soon enough.)
Eg... ("FORM" each time means it's coming from the $_POST array)
FORM: PREFIX :: REV
FORM: FNAME :: Joe
FORM: MNAME :: Frazier
FORM: LNAME :: Test
FORM: SUFFIX :: suffix
FORM: oper :: add
FORM: id :: _empty
Decent code to review here:
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing
More on _empty and form editing here:
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:form_editing
So we need your editurl, we need to know that the "php code for update data" is IN that page, and we probably should see what you've got on the page with the grid in full to give a SUPER WONDERFUL answer. ;^)
You should probably also write up a dummy page at your editurl that iterates through all the values from your $_GET and $_POST collections and writes them to a file so that you can check what the grid is sending you -- and that you're getting anything at all. Also, please please PUH-lease use mysql_real_escape_string() around $name and at least an int check for $id!
I want to display a string "Your status has been posted" for something around 3 or so seconds than I want it to go away.
As of right now I have a news feed where the user can post messages and after they post it echoes that string of text until the url is re-enetered. Does anyone have any suggestions?
if ($_POST['submit'])
{
$body = $_POST['body'];
if ($body)
{
include ('connect.php');
$date = date("Y-m-d");
$email = $_SESSION['email'];
$who = mysql_query("SELECT firstname FROM people WHERE email = $email");
$insert = mysql_query("
INSERT INTO status VALUES('','$email','$body','$date')");
echo ('Your status has been posted <p></p>');
}
else
echo 'Status required to post into news feed! <p></p>';
}
?>
Status :
Thanks for your help!
Jeff
You need to add some JavaScript to do this. Here is an outline to get you started:
<p id="info-message">Your status has been posted</p>
<script>
setTimeout(function(){
document.getElementById('info-message').style.display = 'none';
/* or
var item = document.getElementById('info-message')
item.parentNode.removeChild(item);
*/
}, 3000);
</script>
Also you may want fade-out effects. For that I'd recommend using a library like jQuery or Scriptaculous.
Useful links:
https://developer.mozilla.org/en/Window.setTimeout
http://api.jquery.com/fadeOut/
http://script.aculo.us/
Oh, by the way, your script is vulnerable to SQL injection. Always escape your query parameters (or use prepared queries)!
You can't do that with php. Try Javascript instead.
Unless you go for some weird "100 Continue" approach interleaved before you present your next web page you will need to do this in javascript.
If this i to display for a period after they first see a webpage then you can have something like a This message will disappear and then add a script which is called from your tag's onLoad action which would (e.g.) sleep for three seconds and then set the content of that div to be empty.
I'd use AJAX for that. You can assure yourself that the data has been well inserted into the DB, and then show the message with javascript for amount the time you want.
If sending output to the browser, then you can use javascript to control the time-window you want your text to be visible.
If using jquery you could use .hide() http://api.jquery.com/hide/
You cannot achieve this with PHP only; you need JavaScript. Here's a simple example using jQuery: http://jsfiddle.net/4surX/
I need some help figuring out why the following scenario does not work. I'm trying to retrieve a value from the last updated ID in mysql, then pass that value via javascript over to an ajax call which calls a .php page, which also calls another function "ZEND_emaiL" in a different php page.
In the very first php page that retrieves the id from mysql LAST_INSERT_ID(), if I hard code the value "100" it works, but if I use the value returned from LAST_INSERT_ID() it causes a failure.
Here's the php code for the LAST_INSERT_ID():
$sql='SELECT LAST_INSERT_ID();';
$last_updated_id = $db->get_var( $sql );
$last_updated_id = $last_updated_id+0;//make int
echo $last_updated_id; //send output back to the ajax call
var_dump($last_updated_id); ------------->RETURNS **int 149**
if I send back a hard coded "100" like this: echo 100; then it works.
Any ideas? Thanks for your help in advance.
The following are values retrieved from the php page that contains the ZEND_email() function. I grabbed these for debugging purposes hoping it would help.
RETURN VALUES for Hard Coded:
var_dump($n_id);---------->Returns **int 100**
var_dump($sqlresult);----->Returns **resource 24**
var_dump($row);----------->Returns **array of data to parse through**
RETURN VALUES FOR Passed in Variable (Fails):
function ZEND_email($to, $from="", $subject="", $msg="", $notif_id='', $root_dir="")
{
var_dump($notif_id);---------------------->RETURNS **string '100'**
$notif_id = $notif_id+0;//convert to int
var_dump($notif_id);---------------------->RETURNS **int 100**
$n_id = $notif_id;
$xsql = $sql_str->SQL_SELECT_all_notif_attachments($account_id, $n_id);
$sqlresult=mysql_query($xsql);
$row=mysql_fetch_row($sqlresult);
var_dump($n_id);---------------->RETURNS **int 100**
var_dump($sqlresult);----------->RETURNS **resource 24**
var_dump($row);----------------->RETURNS **boolean false**
}
you are aware that you could use mysql_insert_id() ?
see http://uk.php.net/manual/en/function.mysql-insert-id.php which would give you an INT value directly,
btw, to convert a variable to integer you can use:
$foo = (int) $bar
or
$foo = intval($bar);
or
$foo = settype($bar,'int');
Hard to tell from those code snippets. Better check what's going on on the client-side.
E.g. with firebug you can both check the actual response data and step into the javascript code.
Had to scrap this code...couldn't get it all to work with the feature for the app so we dropped it. Thanks for your help.
Alright, this pretty much goes along with my previous question. I'm still trying to figure out how to display data from an array which is created by a PHP file- using JS/jQuery. I'm working on a points system for ZetaBoards, and I've currently got it set up here. (Points will be displayed below the users post count once I get this working.. you guys can't see the +/- functions which work fine, haha. :p )
http://outlinetokens.hostei.com/scripts/output.php
So, for each user- I can get their user ID, I just don't know how to check if their name is in the array. (and if it is, display their points) I'm guessing I'll have to do something like this? Here's the chunk of the code that deals with this.. you'll see where I need help.
if (location.href.match('/topic/')) {
$.getScript('http://outlinetokens.hostei.com/scripts/output.php', function () {
$('td.c_username a.member').each(function () {
value = 0;
u = $(this).attr('href').split('profile/')[1].split('/')[0];
// this is where I need to do the 'search.' Just a basic guess.. help. D:
if (values.uid == u) {
value = values.points;
}
$(this).parents('tr').next().find('dl.user_info').append('<dt>' + options.system_name + ':</dt><dd class="Points"><span id="point_total">' + value + '</span></dd>');
});
})
}
...in case the code tag screwed it up:
http://ryjoe.pastebin.com/raw.php?i=0bsZNnVq`
Thanks! (:
Why are these lines in your data formatted like this:
{'uid','342230','name','Joe','points','250'}
instead of this:
{'uid': '342230', 'name': 'Joe', 'points','250'}
If that was formatted correctly you could access the properties.
I'm not sure if I'm reading your question right, but you can load JSON with jQuery, instead of a script.
If then, the array is one of usernames, you can just use response.hasOwnProperty(username) or similar to check if it's in the JSON object you got back
Also, in php use json_encode
You want JQuery.parseJSON. Load the data string, parse it, and assuming its valid JSON, it will become a JS object. Then just access the members in the usual way.