Ajax and jquery not sending data correctly to php - javascript

I created a basic form that uses jquery (ajax) to send data to php. PHP should insert a new record based on the data to a mysql database. The reason for this is because I want to make insertions to the database without having to submit the whole form and then use the submit action for something else later. It seems that the jquery works fine since the alert() shows the correct output for the variables, but the PHP does not insert the data and I don't get an error. I can't figure out why this isn't working? I think it is a problem with my $post() because the function underneath does not execute but I can't pinpoint the error. Any help debugging this would be really appreciated. Or if anyone knows another way to get the same functionality that would be great too? Thanks. (The code below works fine now. I figured out it was a type cast error, and I fixed it. Hopefully someone can find this useful!)
<script type="text/javascript">
function submitgrade(){
alert("In it");
var classID = $("#classSelect").val();
var student = $("#studentSelect").val();
var exam = $("#Exam").val();
var grade = $("#grade").val();
alert(classID+" - "+student+" - "+exam+" - "+grade);
$.post('submitgrade.php',{postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade}, /*1*/
function(data){
$("#grade").html("");
});
};
</script>
<?php /*submitgrade.php*/
$con=mysqli_connect("localhost","root","","studentbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$classID = $_POST['postclassSelect'];
$studentID = $_POST['poststudentSelect'];
$examID = $_POST['postExam'];
$grade = $_POST['postgrade'];
echo $studentID[0]." examID: ". $examID[0];
$gradequery = "INSERT INTO grade VALUES(".intval($studentID).", '".$classID."', ".intval($examID).", ".intval($grade).");";
$result = $con->query($gradequery);
while($row = $result->fetch_assoc())
{
echo "<br /><p>Grade of ". $grade." submitted for exam ". $row['exam_id'] ." in ". $row['class_ID'] ."</p>";
}
?>

Have you include this line in your html page ??
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
An example is here again, may help you
<script>
$(document).ready(function(){
$("input").keyup(function(){
txt=$("input").val();
$.post("my_page.asp",{suggest:txt},function(result){
$("span").html(result);
});
});
});
but your code seems correct too buddy !!

I suggest to continue debugging by attaching an error handler to your $.post call, your code could look this:
$.post('submitgrade.php', {postclassSelect:classID,poststudentSelect:student,postExam:exam,postgrade:grade})
.done(function(response) {
// success
}).fail(function(response) {
// failure
});
Further more you should check:
Is the script running on a server? ajax might not work on a file:/// address
Is the path from javascript location to php file correct?
what do the browser developer tools say about the request that is initiated?

I fixed it. It was actually just a syntax error in my SQL and a type difference error with one of my database columns. The $grade variable is passed into PHP as a string. Once I wrapped all of my variables in intval() it worked as intended. Stare at the code to long, sometimes you go blind. Haha.
Thank you omnidan for the tip about sanitization. Here is a good guide that I used to apply it to my app:
http://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data

Related

Change PHP session variable from AJAX call

I am building a website for a school-project. I have been programming in PHP for about a year now, and javascript shouldn't be that much of a problem either.
However, I ran into a problem a couple of days ago. I have a "warning/notification" bar under my navbar. There is two buttons, one where you close the notification and one where you get redirected to read more about it.
If you click the close button, I want to make an AJAX call to the same file, where I have PHP code that will detect the call and then change a SESSION variable, so the notification doesn't show up again regardless of which file you are on.
This however, does not seem to work no matter how many approaches I have tried. I've had enough of this struggle and would greatly appreciate any help from this wonderful community.
This by the way is all in the same file.
Here's the AJAX code:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
type:"POST",
url:"navbar.php",
data: info
});
});
And here's the PHP code (that prints out the HTML):
<?php
require "includes/database.php";
$sql = "SELECT * FROM posts WHERE (post_sort = 'homepage' OR post_sort = 'everywhere') AND post_type = 'warning'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($_SESSION["closed_notification"] == 'no') {
if($resultCheck >= 1) {
while($row = mysqli_fetch_assoc($result)) {
$post_header = $row["header"];
$post_content = $row["post_content"];
$post_index = $row["post_index"];
echo '<div class="nav_bottom_holder_warning">
<div class="navbar_lower_container">
<p>'.$post_header.'</p>
<button class="btn" id="close_warning">Stäng</button>
<button class="btn" id="show_warning">Visa inlägg</button>
</div>
</div>';
}
}
}
?>
Last but not least, the code that is responsible for changing the actual SESSION:
<?php
$_SESSION["closed_notification"] = "no";
if(isset($_POST["info"])) {
$_SESSION["closed_notification"] = "yes";
}
?>
I have tried numerous approaches to this problem, this is just one of them. At this point I am just clueless of how to solve it, thank you.
EDIT: I have already included this file in another file that contains a "session_start()" command. So using that in this file would be no help.
First of all there is no session_start(); on the first line so it will give you an error for the Session Variable.
Secondly update your ajax code to this:
$("#close_warning").click(function(){
var info = "close";
$.ajax({
url: 'navbar.php',
type: 'post',
data: {info:info}
});
});
It basically means that data:{name1:variable2}
Here you are giving the data from js variable(variable2) 'info' to php as info(name ==> that we generally set the input attribute) so in php you can access it as $_POST['info'];.
And lastly you gave the js variable value 'close' and you just checked whether the variable is set while changing the session variable.
Change it to actually checking the value which is better and clear when others read your code.
Summary:
Change data: info to data:{info:info}
Just use Javascript local storage or session storage. I guess it is not important for the server to know if a user has closed the notification yet or not.
$("#close_warning").click(function(){
// close the notification
$("#notification").hide();
// set 'closed' flag in local storage
storage.setItem('closed', 1);
});
Have javascript hide the notification, if the 'closed' flag is set.
if (storage.getItem('closed')) {
$("#notification").hide();
}

JavaScript function won't run after using header(), but does run if no use of header() (in php)

I apologize if my question title is at all confusing, this is my first post and despite reading https://stackoverflow.com/help/on-topic I feel like I may still have some flaws in my question-writing abilities.
TL;DR: JavaScript animation works if I do not use header("location: ProjectUserProfile.php?UploadSuccessful"), but doesn't if I do (and I need to). Any reasons or solutions?
Anyway,
The context:
I have a html form embedded in a php document which is used to upload an image, delete an image, etc.
The main code takes place on ProjectUserProfile.php (and works perfectly), and after the image has been uploaded, I use header("location: ProjectUserProfile.php?UploadSuccessful") to return to the page, and prompt a refresh.
The problem:
If I do not use header("location: ProjectUserProfile.php?UploadSuccessful"), the image will not change, etc, so it is a necessity for me to use it. However, recently I have implemented "slide in notifications" if you will which display success and error messages. These work correctly normally, but fail to appear if I return to the page using header("location: ProjectUserProfile.php?UploadSuccessful").
<?php
// all the uploading etc that works occurs here
header("location: ProjectUserProfile.php?UploadSuccessful");
echo "<script> openMessage('Information','The duplicate files were successfully uploaded!') </script>";
?>
After redirecting to ProjectUserProfile.php?UploadSuccessful, there is failure to acknowledge openMessage, and so nothing happens.
Whereas, had I not used header("location: ProjectUserProfile.php?UploadSuccessful"), the "notification" would slide in and work.
Does anyone have any solutions or suggestions?
Relevant code for the javascript function 'openMessage()' below:
function openMessage(Purpose, DisplayText){
var notificationDiv = document.getElementById("slideinNotification");
if(notificationDiv){
alert("exists");
}
else{
alert("does not exist");
}
document.addEventListener("DOMContentLoaded", function(event){
if(Purpose == "Information"){
document.getElementById("slideInNotification").style.backgroundColor = "#4CAF50";
}
else if(Purpose == "Warning"){
document.getElementById("slideInNotification").style.backgroundColor = "#FF9800";
}
else if(Purpose == "Error"){
document.getElementById("slideInNotification").style.backgroundColor = "#F44336";
}
document.getElementById("notificationMessage").innerHTML = DisplayText;
moveElement();
});
}
<?php
if($filesWereDeleted == true){
$connection = new mysqli("localhost", "root", "root", "project");
$result = $connection -> query("UPDATE UserProfileImage SET UploadStatus = 1 WHERE UserUniqueID = '$userProfileId'");
header("location: ProjectUserProfile.php?DeletionSuccessful");
echo "<script> openMessage('Information','The profile image was successfully deleted!') </script>";
}
?>
<div id = "slideInNotification" class = "slideNotification">
<p id = "notificationMessage" class = "notificationInfo"></p>
×
</div>
First, your UPDATE query exposed to SQL Injection, if you get the id from the user, I hope note, read about prepared statement.
Second, about your problem, you echo the notify script in the same response you send the Location header , so before the the browser even load your JavaScript code it redirect the client to the new page when your notify javascript code not echoed...
If your problem is that user updates it's image and it's doesn't appear due it cached you can use uniqid() in the get query of image src or modify time, more effective
The thing is, once you use header("location: ProjectUserProfile.php?DeletionSuccessful"); you're not supposed to write anything into the output, as the browser will ignore it. That aside, I'm not exactly sure about how a single line of <script> openMessage('Information','The duplicate files were successfully uploaded!') </script> could mean anything to the browser, since that wouldn't constitute an HTML document by itself, unless you're receiving it through AJAX or loading it into an <iframe>; but even then, I doubt mixing control instructions (a redirect) with view markup (the script tag) would be a good idea.
You're going to have to post the confirmation message in ProjectUserProfile.php, so move your script tag there. You can use that ?UploadSuccessful bit as reference for you to know whether to include your script for the message in the document is necessary or not.

I can't get a value from a PHP array...?

I'm writing a script to retrieve the scores from an osu! beatmap. The script uses the osu! API, which can be found here. I've obtained a valid API key, and got the info from the website. My project can be found here: failosu!.
This script is called by AJAX, and the variable s is passed via POST.
My problem is with the returned array.
In the following snippet (not really, it's pretty much my entire script), I make a request for the beatmap information first. In doing this, I am passing a variable, s (beatmap set ID), to the server, and trying to get the variable b (beatmap ID).
However, whenever I call $d1['beatmap_id'], it doesn't return anything to the main page. Instead, my AJAX script runs the error function rather than the success function. Does anyone know what my problem is?
if($_POST['id']) {
$s = $_POST['id'];
$k = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$u0 = "https://osu.ppy.sh/api/get_beatmaps?k=".$k."&s=".$s;
$d0 = json_decode(file_get_contents($u0));
$d1 = get_object_vars($d0[0]);
$b = $d1["beatmap_id"];
// THE CODE STOPS WORKING HERE FOR SOME REASON ????
$u = "https://osu.ppy.sh/api/get_scores?k=".$k."&b=".$b."&m=0";
echo $u;
$d = json_decode(file_get_contents($u));
for($i=0;$i<count($d);$i++) {
echo "<li>".$i." ".$d[$i]['username']."</li>";
}
}
Does anyone know what's wrong? Do you need me to tell you more information about my code?

Live Dynamic search of MySQL table using jquery and php

I am sure there are a number of articles covering this topic, but every piece of code I try just doesn't seem to work. If this has been answered somewhere else already, I am sorry that I could not find it.
I am trying to create a live search that displays all data in my table until someone starts typing in an input field. As soon as they start typing a key, I want to run a select query on my table to narrow the results if any of the columns contain the string that is currently being typed (kind of like how google starts showing you results as you type in the search bar).
My code seems to work up until I try to use either $.get or $.post to interact with my php file that runs the MySQL search. I am kind of new to web development and have been teaching myself as I go along, but this one has stumped me for 2 days now. Here is the code I currently have (although I have tried about 20 different versions):
jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
document.getElementById("search").onkeyup(searchScript());
function searchScript(){
var search = $("#search").val();
if(search==""){
return;
}
else{
$.get("resultspage.php",{search : search},function(result){
$("#results").html(result);
}});
}
</script>
<table id="results">
<?php
<...var assignments storing my db login data...>
$con=mysqli_connect($host,$username,$password,$database);
$sql="SELECT * FROM Registration";
if(mysqli_query($con,$sql)){
$result=mysqli_query($con,$sql);
}
else{
echo "error: " . mysqli_error($con);
}
while($row=mysqli_fetch_array($result))
{
<...code that displays the results...>
?>
</table>
My PHP file
$search=$_GET['search'];
<...variables storing log in data...>
$con=mysqli_connect($host,$username,$password,$database);
$sql="SELECT * FROM Registration WHERE CONCAT(fName,lName,storeName,numLocations,primaryPhone,secondPhone,email,products) LIKE %$search%";
if(mysqli_query($con,$sql)){
$result=mysqli_query($con,$sql);
}
else{
echo "error: " . mysqli_error($con);
}
while($row=mysqli_fetch_array($result))
{
<...code that displays results....>
}
Any help would be much appreciated! Thank you.
Recognizing that jquery is another mountain to climb, I would still learn & use it for it's simplicity. Once the data has been retrieved from the server, use jquery to hide the values not starting with or containing the entered value (.match() below), instead of repeated calls to the server.
Not knowing the structure of your table, a framework you might try:
$( "#search" ).keyup(function() {
// Test search letter entry is working
alert( "Handler for .keyup() called." );
var s = $("#search").attr("value"); // Typed in letter
// Pass an array of table contents
// there are a couple ways you could approach the 'gathering' of table items...
$(".individual-item-class").each(function(index, element) {
if (!element.match(/s/))
$(element:parent).css("display","none");
else
$(element:parent).css("display","table-row")
}):
});
This code will not get you off the ground, but pointed in a direction.
You can learn about selectors and a few jquery functions. Used here are each(), attr() and css().

How do I auto-refresh my php chat-script?

I am having trouble getting my php chat script to auto refresh when mysql data is changed. I have done a good bit of research and it seems a lot of other people's solutions are more complicated then what I need (I'm going for something very basic).
I do not know any javascript so detailed comments would be appreciated if js is involved.
Here is the php script that I have created. It is functioning (at least for me).
include 'connect2.php';
echo "
Enter a Message:
<form method=post action='' name=chat>
<input type=text name=message>
<input type=submit name=chat value=Submit>
</form>
";
if (isset($_POST['chat'])) {
$message = $_POST['message'];
mysql_query("INSERT INTO chat set message='$message',user='$_SESSION[username]'");
}
$sql = "select * from chat order by id desc limit 15";
$result = mysql_query($sql) or die ("An error has occured with in the database.");
while ($data = mysql_fetch_assoc($result)) {
$db_message = $data['message'];
$db_user = $data['user'];
echo "$db_user : $db_message <br>";
}
?>
Any help would be appreciated, thanks! :)
You can use setInterval and jQuery library ajax functions to check for it.
For example, it's very simple to do with jQuery:
$(document).ready(function() {
// check once in five seconds
setInterval(function() {
$.get('/script.php', {do: 'new_messages'}, function(response) {
if(response == 1) {
window.location.reload();
}
});
}, 5000);
});
And somewhere on server:
if(isset($_GET['do']) && $_GET['do'] == 'new_messages') {
// some your code that detects if there's any new messages, and sets
// $there_are_new_messages to true, if there's any
...
if($there_are_new_messages) {
echo 1;
exit; // avoid further output
}
}
Please remember, that for this to work you need to ensure that there's no output before ajax block, as you can get into unexpected results.
Also consider that using output is not a good practice at all to show your script everything is ok. Better way is to set HTTP header with corresponding response code.
The best way to do this in your case would probably be using Ajax (and jQuery) and refreshing every X seconds.
Ready Handler- http://api.jquery.com/ready/
Javascript Timer- http://www.w3schools.com/js/js_timing.asp
Ajax Request- http://api.jquery.com/jQuery.post/
PHP json_encode- http://php.net/manual/en/function.json-encode.php
$( document ).ready(function() { //set up refresh timer on page load
var refreshTimer = setInterval(function(){refreshMessages()},5000); //creates timer to request every 5 seconds
});
function refreshMessages(){
$.post( "getMessages.php", function( data ) { //fire ajax post request
alert("Got messages: " + data); // this just alerts the data when the request is done, you'll probably want to format/print
});
}
On the getMessages.php side of things, you'll want to pull your messages from the database how you normally would. In this case, json encoding your php messages array would be an easy way for you to iterate the returned object.
<?php
$messages = // get messages array from database
echo json_encode($messages);
?>

Categories